Reputation: 135
I'm trying to use a dynamically generated fully-qualified table name in sql server 2008. For example, this does not work:
select max([id]) from @dbName+N'.[T1]'
This will give an error like:
Msg 102, Level 15, State 1, Line 73
Incorrect syntax near '+'.
I know that something like this works:
declare @qualifiedTable varchar(200) = @dbName+N'.[T1]'
select max([id]) from @qualifiedTable
But I have to do this LOTS of times so I would really like to do it in line. Is it possible?
Upvotes: 0
Views: 6706
Reputation: 2185
This should work:
sp_executesql N'select (max([id]) from ' + @dbName + '.dbo.[T1]';
Upvotes: 2