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.
First, declare two variables, @table for holding the name of the table from which you want to query and @sql for holding the dynamic SQL. Second, set the value of the @table variable to production. products . Fourth, call the sp_executesql stored procedure by passing the @sql parameter.
The TABLE keyword specifies that this variable is a table variable. After the TABLE keyword, we have to define column names and datatypes of the table variable in SQL Server.
DECLARE @MyTableName nvarchar(20);
DECLARE @DynamicSQL nvarchar(1000);
SET @MyTableName = "FooTable";
SET @DynamicSQL = N'SELECT * INTO ' + @MyTableName + ' FROM BarTable';
EXEC(@DynamicSQL);
Unfortunately, you can't use bind variables for table names, column names, etc. IN this case you must generate dynamic SQL and use exec
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With