这个链接是我找到问题答案的一部分。
Simon发布了
“做个老板。写点如下:
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
非常感谢大家。 干杯! 添
答案 0 :(得分: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)