我有一种情况,我想更新多列,但我不想写这么多UPDATE
行。
是否可以将变量用作列名? ,然后该变量将在WHILE
循环内发生变化,请考虑以下示例。
EX:
表:测试
Column01
Column02
Column03
Column04
Column05
Column06
Column07
Column08
Column09
Column10
DECLARE @ctr INT = 01
WHILE @ctr <= 10
BEGIN
-->> Is it possible to perform concatenation here to manipulate column name ?
UPDATE Test SET (Column + @ctr) = SomeValueHere... -->> assume that @ctr = 01
END
SET @ctr = @ctr + 1
每个循环的查询都会显示:
-->> The first loop will look something like
UPDATE Test SET Column01 = SomeValueHere...
-->> The second loop will look something like
UPDATE Test SET Column02 = SomeValueHere...
我怎样才能做到这一点? 提前谢谢。
答案 0 :(得分:0)
您可以使用动态SQL执行此操作。
DECLARE @script NVARCHAR(max)
SET @script = 'UPDATE Test SET (Column' + @ctr + ') = ' [whatever]
EXECUTE (@script)