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?
Also, You can use this...
Change your last statement to this:
This is how I do mine in a Stored Procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the DB already, and remove if it does. Then the next block will use a SELECT INTO Statement to create the table and populate it with records from another table with parameters.
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
You can't use a table name for a variable, you'd have to do this instead:
Use
sp_executesql
to execute any SQL, e.g.