简体   繁体   English

将所有表中的所有整数列设置为0,其中当前值为空

[英]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): 我正在寻找一种在SQL Server中迭代运行以下查询(或达到相同结果)的方法:

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? 我已经使用以下查询来获取所有类型为'int'的列,但如何才能达到上述要求?

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. 对于某些动态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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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