i am trying to execute this query:
declare @tablename varchar(50)
set @tablename = 'test'
select * from @tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "@tablename".
What’s the right way to have table name populated dynamically?
Solution
Table names and column names need to be static, if the query is static. For dynamic table or column names, you should generate the full SQL dynamically, and use sp_executesql to execute it.
More details here: The curse and blessings of dynamic SQL
The post Sql Server Select Into Variable Table Name appeared first on Solved.