是否可以将变量列名称传递给更新语句?

时间:2013-07-19 10:40:03

标签: sql sql-server sql-server-2008 tsql

我有一个数据表,列出了12个周期列的值。我试图将月初的数据归零,但未成功。我的查询的第一部分返回列名,然后我想将其传递给Update语句,但那就是一切都出错了?请帮忙。*

DECLARE @A VARCHAR(20) = (SELECT listofperiod FROM [periods] P 
                          INNER JOIN (SELECT monthofyear 
                          FROM  ref_calender RC 
                          WHERE RC.date = Dateadd(m,-1,CONVERT(DATE,Getdate())))
                          RC ON P.monthofyear = RC.monthofyear) 

UPDATE FD SET  @A = 0 
       FROM   [test_table] FD 
       INNER JOIN [glx]AG ON FD.company = AG.company 
       AND FD.acctnum = AG.account_id  '

2 个答案:

答案 0 :(得分:3)

您必须使用动态SQL来实现此目的:

DECLARE @sql NVARCHAR(MAX)

SET @sql = 'UPDATE FD 
            SET ' + @A + '= 0 
            FROM   [test_table] FD 
           INNER JOIN [accpac_glx]AG 
                   ON FD.company = AG.company 
                      AND FD.acctnum = AG.account_id'

EXEC (@sql)

答案 1 :(得分:3)

您可以使用多个条件set语句执行此操作:

UPDATE FD 
SET    Period1 = (case when @A = 'Period1' then 0 else Period1 end),
       Period2 = (case when @A = 'Period2' then 0 else Period2 end),
       Period3 = (case when @A = 'Period3' then 0 else Period3 end),
       Period4 = (case when @A = 'Period4' then 0 else Period4 end)
FROM   [test_table] FD 
       INNER JOIN [glx]AG 
               ON FD.company = AG.company 
                  AND FD.acctnum = AG.account_id

即,将值设置为当前值,除非标志(@A)表示将值重置为0.