字段名称存储在变量中

时间:2014-06-10 15:45:31

标签: sql sql-server tsql

是否可以这样做?

DECLARE @TableName As varchar(50)
set @TableName = 'tbl_goccurrence'   
DECLARE @OccurrenceFileNo As varchar(50)
    exec ('select ' + @OccurrenceFileNo + ' = occurrencefileno from @TableName where id=902000000001387589')
    print @OccurrenceFileNo

我得到的错误是:'='

附近的语法不正确

2 个答案:

答案 0 :(得分:1)

您可以将sp_executesql与输出参数一起使用,将值指定给@occurrenceFileNo

DECLARE @OccurrenceFileNo As varchar(50)
exec sp_executesql N'select @OccurrenceFileNo = occurrencefileno from tbl_goccurrence where id=902000000001387589', N'@OccurrenceFileNo varchar(50) out', @occurrenceFileNo out
print @OccurrenceFileNo

答案 1 :(得分:0)

{根据更新的问题重新开始}

我想你想要:

exec sp_executesql N'select @OccurrenceFileNo = occurrencefileno from ' 
                 +  @TableName 
                 + ' where id=902000000001387589'
                  , N'@OccurrenceFileNo varchar(50) out'
                  , @occurrenceFileNo out