Question

This is in relation to my previous question. I am running a exec statement as below and I get an error Incorrect syntax near '+@dbname+'. Any help is greatly appreciated. Thanks.

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')
Was it helpful?

Solution

It looks like you are trying to dynamically choose what database you're running this query on. You can do when you are creating the query your are going to exec, but you can't have a variable in your query that represents the database.

This should work

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top