EXEC中的简单SQL代码抛出错误

时间:2014-04-30 15:06:59

标签: sql sql-server-2008-r2 exec

这与我先前的问题有关。我正在运行如下的exec语句,我收到错误'+ @ dbname +'附近的语法不正确。任何帮助是极大的赞赏。谢谢。

exec('
declare @dbname nvarchar(100)
set @dbname = ''HUM_FM_1_SYNTQ_TEST''

select @dbname

Select seriesvariables_value from
(
select *, row_number() over 
(order by SeriesVariables_ID asc) as rownum from ''+@dbname+''
.dbo.Seriesvariables where 
SeriesVariables_Label = ''Enter Tablet Segment Pull Date'' and
Series_ID = 42) as tbl1 
where rownum = 1')

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试动态选择您正在运行此查询的数据库。您可以在创建要转到exec的查询时执行此操作,但在查询中不能有代表数据库的变量。

这应该有效

declare @dbname nvarchar(100)
set @dbname = 'HUM_FM_1_SYNTQ_TEST'

exec('

select @dbname

Select seriesvariables_value from
(
select *, row_number() over 
(order by SeriesVariables_ID asc) as rownum from '+@dbname+'
.dbo.Seriesvariables where 
SeriesVariables_Label = ''Enter Tablet Segment Pull Date'' and
Series_ID = 42) as tbl1 
where rownum = 1')