我有64列,我正在尝试自动化循环过程。循环运行但它显示0个受影响的行。如果我逐列更新表,它可以工作。 知道为什么它显示0个受影响的行以及可以做什么?
update temp set col1 = 'C' where col1 IS Null; -- works (276 rows affected)--
declare @count as int;
declare @name as varchar(max);
set @count = 2;
while @count < (SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'temp')+1
Begin
Set @name = (select name from (select colorder, name from (SELECT *
FROM syscolumns WHERE id=OBJECT_ID('temp')) colnames) as cl where colorder = @count)
Print @name
update temp set @name = 'C' where @name IS Null;
SET @count = @count + 1;
END;
答案 0 :(得分:0)
您需要在运行时使用动态SQL来更新不同的列,如下所示。
注意:我刚添加/修改了动态sql部分。
declare @count as int;
declare @name as varchar(max)
declare @sql nvarchar (1000)
set @count = 2
while @count < (SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'temp')+1
Begin
Set @name = (select name from (select colorder, name from (SELECT *
FROM syscolumns WHERE id=OBJECT_ID('temp')) colnames) as cl where colorder = @count)
Print @name
set @sql = N'update temp set ' + @name + '= ''C'' where ' + @name + ' is null ';
exec sp_executesql @sql
SET @count = @count + 1
END;