Creating SQL table using dynamic variable name
Asked Answered
S

5

13

I want to create backup SQL tables using variable names.

something along the lines of

DECLARE @SQLTable Varchar(20) 
SET @SQLTable = 'SomeTableName' + ' ' + '20100526' 
SELECT * INTO quotename(@SQLTable)
 FROM SomeTableName

but i'm getting

Incorrect syntax near '@SQLTable'.

It's just part of a small script for maintence so i don't have to worry about injections.

Sakti answered 25/5, 2010 at 15:3 Comment(0)
R
25
DECLARE @MyTableName sysname;
DECLARE @DynamicSQL nvarchar(max);

SET @MyTableName = 'FooTable';


SET @DynamicSQL = N'SELECT * INTO ' + QUOTENAME(@MyTableName) + ' FROM BarTable';

EXEC sp_executesql @DynamicSQL;
Refresher answered 25/5, 2010 at 15:9 Comment(2)
exec @DynamicSQL should be: exec(@DynamicSQL); -- without the parenthesis, throws "name not a valid identifier".Constantino
I have the same result as @plditallo. Without the parenthesis I get error: "Could not find stored procedure..." EXEC without brackets attempts to call a procedure. #8383253Lantz
F
6

Unfortunately, you can't use bind variables for table names, column names, etc. IN this case you must generate dynamic SQL and use exec.

Fungous answered 25/5, 2010 at 15:5 Comment(0)
O
5
DECLARE @Script NVARCHAR(MAX);
SET @Script = N'SELECT * INTO SomeTableName_' + N'20100526' + N' FROM SomeTableName';
EXEC sp_executesql @Script

I've left the date separate as I assume you want to calculate it for every run.

Oregano answered 25/5, 2010 at 15:8 Comment(0)
T
4

You should look into using synonyms:

-- Create a synonym for the Product table in AdventureWorks2008R2. CREATE SYNONYM MyProduct FOR AdventureWorks2008R2.Production.Product; GO

-- Query the Product table by using the synonym. USE tempdb; GO SELECT ProductID, Name FROM MyProduct WHERE ProductID < 5; GO

http://msdn.microsoft.com/en-us/library/ms177544.aspx

Troxell answered 25/5, 2010 at 19:5 Comment(0)
E
1
DECLARE @MyTableName nvarchar(20);
DECLARE @DynamicSQL nvarchar(1000);

SET @MyTableName = "FooTable";


SET @DynamicSQL = N'SELECT * INTO ' + @MyTableName + ' FROM BarTable';

exec @DynamicSQL;

this query is correct but just use single quote at the ("FooTable")='FooTable'

Euell answered 17/4, 2017 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.