Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A table name as a variable

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 the table name populated dynamically?

like image 983
SoftwareGeek Avatar asked May 15 '10 01:05

SoftwareGeek


People also ask

Can I use table name as variable in SQL?

The sp_executesql command supports accepting Table name as Parameter (Variable) in the following SQL Server versions i.e. 2000, 2005, 2008, 2008R2, 2012, 2014, 2017, 2019 and higher.

Is a table a variable?

Definition. The table variable is a special type of the local variable that helps to store data temporarily, similar to the temp table in SQL Server. In fact, the table variable provides all the properties of the local variable, but the local variables have some limitations, unlike temp or regular tables.

What is table type variable?

A variable is a characteristic that can be measured and that can assume different values. Height, age, income, province or country of birth, grades obtained at school and type of housing are all examples of variables. Variables may be classified into two main categories: categorical and numeric.


2 Answers

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 to easily change the 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 maintain, I recommend that you read: The curse and blessings of dynamic SQL

like image 114
mdma Avatar answered Sep 22 '22 23:09

mdma


Change your last statement to this:

EXEC('SELECT * FROM ' + @tablename) 

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 database 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.

--DECLARE TABLE NAME VARIABLE DYNAMICALLY DECLARE @table_name varchar(max) SET @table_name =     (SELECT 'TEST_'             + DATENAME(YEAR,GETDATE())             + UPPER(DATENAME(MONTH,GETDATE())) )  --DROP THE TABLE IF IT ALREADY EXISTS IF EXISTS(SELECT name           FROM sysobjects           WHERE name = @table_name AND xtype = 'U')  BEGIN     EXEC('drop table ' +  @table_name) END  --CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE EXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''') 
like image 37
Tim Avatar answered Sep 25 '22 23:09

Tim