简体   繁体   中英

Set all integer columns in all tables to 0 where the value is currently null

I'm looking for a way in SQL Server to iteratively run the following query (or to achieve the same result):

UPDATE <table> SET <column> = 0 WHERE <column> IS NULL

I've used the following query to get all the columns of type 'int', but how can I achieve the above requirement?

SELECT table_name, column_name FROM information_schema.columns where data_type = 'int' and table_name not like 'v_%' and table_name not like 'sym_%'

This is reasonably simple with some dynamic sql. I would be EXTREMELY careful doing this on any system and would ask questions about why this is a good idea. I would never do this on my system but the code is actually fairly straight forward.

declare @SQL nvarchar(max) = ''

SELECT @SQL = @SQL + 'Update [' + TABLE_NAME + '] set [' + COLUMN_NAME + '] = 0 where [' + COLUMN_NAME + '] IS NULL;'
FROM information_schema.columns 
where data_type = 'int' 
    and table_name not like 'v_%' 
    and table_name not like 'sym_%'

select @SQL
--exec sp_executesql @SQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM