0

这个链接是我找到我的问题的部分答案的地方。

SQL 替换所有 NULL

西蒙发布

“当老板。写这样的东西:

select 'update ' + table_name + ' set [' + column_name + '] = '''' where [' + column_name + '] is null'
from tempdb.information_schema.columns
where table_name = 'YourTableName'

它会为你吐出一个很大的查询。别客气”

但我想知道是否有办法使用参数中的结果集并执行所有更新语句。我尝试过这样的事情

DECLARE @sql2 AS NVARCHAR(MAX) = N' 
SELECT ''UPDATE '' + table_name + '' SET ['' + column_name + ''] = '''''''' WHERE ['' + column_name + ''] IS NULL''
FROM tempdb.information_schema.columns
WHERE table_name = ''##tempF'''

EXEC sp_executesql @stmt = @sql2;

DECLARE @sql3 AS NVARCHAR(MAX);
SET @sql3 = (SELECT @sql2);

EXEC sp_executesql @stmt = @sql3;

但它有两个结果集,如下所示:

UPDATE ##tempF SET [claimid] = '' WHERE [claimid] IS NULL
UPDATE ##tempF SET [hdr_status] = '' WHERE [hdr_status] IS NULL
UPDATE ##tempF SET [memid] = '' WHERE [memid] IS NULL

非常感谢大家。干杯! 蒂姆

4

1 回答 1

0

像这样

--initialize variables
DECLARE @UpdateColumns varchar(max) = '' 
DECLARE @IsNullColumns varchar(max) = ''

SELECT 
    @UpdateColumns = @UpdateColumns + ',[' + COLUMN_NAME + '] = ISNULL([' + COLUMN_NAME + '],'''')',
    @IsNullColumns = @IsNullColumns + ' OR [' + COLUMN_NAME + '] IS NULL'
FROM tempdb.information_schema.columns
WHERE table_name = '##tempF'

这应该用以下值填充两个变量:

@UpdateColumns = ',[claimid] = ISNULL([claimid],''''),[hdr_status] = ISNULL([hdr_status],''''),[memid] = ISNULL([memid],'''')'
@IsNullColumns = ' OR [claimid] IS NULL OR [hdr_status] IS NULL OR [memid] IS NULL'

然后你需要把它全部组装起来(记住删除每个变量的第一个字符(STUFF 函数非常适合):

DECLARE @qry varchar(max) = 'UPDATE ##tempF SET ' 
+ STUFF(@UpdateColumns,1,1,'') + ' WHERE ' 
+ STUFF(@IsNullColumns,1,4,'') --the 4 in here is to get rid of ' OR ' (4 chars)

EXEC(@qry)
于 2013-07-03T23:12:20.533 回答