如何将变量用作列名

时间:2015-05-28 04:04:18

标签: sql sql-server

当我尝试将变量用作列名时,我收到以下错误。

错误

  

Msg 207,Level 16,State 1,Line 45
  列名称“@WKNUM”无效。

代码

SET NOCOUNT ON
GO

DECLARE @WKNUM int

SET @WKNUM = 17
WHILE (@WKNUM < 20)
BEGIN;

    UPDATE dbo.DataModel_TEST_NUM
    SET dbo.DataModel_TEST_NUM.[@WKNUM] = dbo.TEST2.[New Value]
    FROM dbo.TEST2
    INNER JOIN dbo.DataModel_TEST_NUM
        ON dbo.TEST2.[Opportunity ID] = dbo.DataModel_TEST_NUM.opportunityID
    WHERE (dbo.TEST2.WKNUM = @WKNUM)

    SET @WKNUM = @WKNUM + 1
END;
GO
SET NOCOUNT OFF
GO

知道为什么会出现这个错误吗?

3 个答案:

答案 0 :(得分:1)

通常,您不能在尝试时将变量用作列名:

最好是构建包含所有变量的更新字符串,然后在完成后执行:

DECLARE @SqlString VARCHAR(1000)
SET @SqlString = 'UPDATE dbo.DataModel_TEST_NUM SET dbo.DataModel_TEST_NUM.[' + @WKNUM + '] = dbo.TEST2.[New Value]
                  FROM dbo.TEST2 INNER JOIN dbo.DataModel_TEST_NUM ON dbo.TEST2.[Opportunity ID] = dbo.DataModel_TEST_NUM.opportunityID
                  WHERE (dbo.TEST2.WKNUM = ' + @WKNUM + ' )  '

EXEC(@SqlString)

答案 1 :(得分:0)

UPDATE dbo.DataModel_TEST_NUM
SET    dbo.DataModel_TEST_NUM.[@WKNUM] = dbo.TEST2.[New Value]------What you are try to do here ...!!!
 ---you can not define column name like this..
FROM   dbo.TEST2
INNER JOIN
dbo.DataModel_TEST_NUM ON dbo.TEST2.[Opportunity ID] = dbo.DataModel_TEST_NUM.opportunityID
WHERE        (dbo.TEST2.WKNUM = @WKNUM )  

您将 @WKNUM 定义为 INT ,它将为您提供值17,18,19 .. 是否确认你有列名这样......如果是,那么你必须像这样使用动态sql ..

DECLARE @update VARCHAR(1000)
SET @update = 'UPDATE dbo.DataModel_TEST_NUM SET dbo.DataModel_TEST_NUM.[' + @WKNUM + '] = dbo.TEST2.[New Value]
                  FROM dbo.TEST2 INNER JOIN dbo.DataModel_TEST_NUM ON dbo.TEST2.[Opportunity ID] = dbo.DataModel_TEST_NUM.opportunityID
                  WHERE (dbo.TEST2.WKNUM = ' + @WKNUM + ' )  '

EXEC(@update )

答案 2 :(得分:0)

我发现只有一个问题是您使用的是变量名而不是实际的列名。

begin  tran
create table DataModel_TEST_NUM (opportunityID int, WKNUM int )
create table TEST2 (opportunityID int, WKNUM int, new_value int )

insert into DataModel_TEST_NUM values (1, 18) , (2,25 ),(3,19 ), (4,30)

insert into TEST2 values (1, 18, 19) , (2 ,25 ,26 ),(3,19, 20 ), (4,30,31)


--SET NOCOUNT ON
--GO
select * from DataModel_TEST_NUM

DECLARE @WKNUM int

SET @WKNUM = 17
WHILE (@WKNUM < 20)
BEGIN;

    UPDATE dbo.DataModel_TEST_NUM
    SET [WKNUM] = dbo.TEST2.[new_value]
    --select *
    FROM dbo.TEST2
    INNER JOIN dbo.DataModel_TEST_NUM
        ON dbo.TEST2.[opportunityID] = dbo.DataModel_TEST_NUM.opportunityID
    WHERE (dbo.TEST2.WKNUM = @WKNUM)

    SET @WKNUM = @WKNUM + 1
END;
--GO
--SET NOCOUNT OFF
--GO

select * from DataModel_TEST_NUM
select * from test2

rollback 

--actual data
opportunityID   WKNUM
    1           18
    2           25
    3           19
    4           30

--after while loop and update query 
opportunityID   WKNUM
    1           19
    2           25
    3           20
    4           30

我有一些建议。

  1. 虽然测试SET NOCOUNT选项始终关闭。
  2. Aly在创建表时遵循标准规则,在您的情况下,您在列名中提供空格。永远不要创建这种类型的列名。