Creating SQL table using dynamic variable name

▼魔方 西西 提交于 2021-01-20 18:09:43

问题


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.


回答1:


DECLARE @MyTableName nvarchar(20);
DECLARE @DynamicSQL nvarchar(1000);

SET @MyTableName = "FooTable";


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

EXEC(@DynamicSQL);



回答2:


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




回答3:


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.




回答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




回答5:


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'



来源:https://stackoverflow.com/questions/2905878/creating-sql-table-using-dynamic-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!