Table name as variable

SoftwareGeek picture SoftwareGeek · May 15, 2010 · Viewed 428.6k times · Source

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?

Answer

mdma picture mdma · May 15, 2010

For static queries, like the one in your question, table names and column names need to be static.

For dynamic queries you should generate the full SQL dynamically, and use sp_executesql to execute it.

Here is an example of a script used to compare data between the same tables of different databases:

static query:

SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]

since I want easily change tha name of table and schema I have created this dynamic query:

declare @schema varchar(50)
declare @table varchar(50)
declare @query nvarchar(500)

set @schema = 'dbo'
set @table = 'ACTY'

set @query = 'SELECT * FROM [DB_ONE].['+ @schema +'].[' + @table + '] EXCEPT SELECT * FROM [DB_TWO].['+ @schema +'].[' + @table + ']'

EXEC sp_executesql @query

Since dynamic queries have many details that need to be considered and they are hard to mantain I recommend that you read : The curse and blessings of dynamic SQL