使用sp_executesql时列名无效

时间:2012-01-04 04:48:07

标签: sql sql-server-2005

当我尝试在存储过程中执行动态查询时,我收到错误。

我的代码是:

DECLARE @Query nvarchar(max)
DECLARE @AllowanceBadge nvarchar(20)
DECLARE @AllowFieldName nvarchar(50)
DECLARE @Amount Decimal
SET @AllowanceBadge  ='SIP0980'
SET @AllowFieldName ='xxxxx'
SET @Amount = 100

SET @Query = 'UPDATE tbl_PayrollTransaction SET '+ @AllowFieldName +' = '+convert(varchar,@Amount) + 'WHERE BadgeNumber = '+@AllowanceBadge
            EXEC SP_EXECUTESQL @Query

我收到了以下错误

  

Msg 207,Level 16,State 1,Line 1
  列名称'SIP0980'无效。

告诉我我哪里错了。

由于

1 个答案:

答案 0 :(得分:5)

SIP0890需要引用

DECLARE @Query nvarchar(max)
DECLARE @AllowanceBadge nvarchar(20)
DECLARE @AllowFieldName nvarchar(50)
DECLARE @Amount Decimal
SET @AllowanceBadge  ='SIP0980'
SET @AllowFieldName ='xxxxx'
SET @Amount = 100

SET @Query = 'UPDATE tbl_PayrollTransaction SET '+ @AllowFieldName +' = '+convert(varchar,@Amount) + 'WHERE BadgeNumber = '''+@AllowanceBadge+''''
            EXEC SP_EXECUTESQL @Query