Creating SQL table using dynamic variable name

前端 未结 5 940
滥情空心
滥情空心 2021-02-05 17:23

I want to create backup SQL tables using variable names.

something along the lines of

DECLARE @SQLTable Varchar(20) 
SET @SQLTable = \'SomeTableName\' +         


        
相关标签:
5条回答
  • 2021-02-05 17:49

    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

    0 讨论(0)
  • 2021-02-05 17:57
    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'

    0 讨论(0)
  • 2021-02-05 17:58
    DECLARE @MyTableName nvarchar(20);
    DECLARE @DynamicSQL nvarchar(1000);
    
    SET @MyTableName = "FooTable";
    
    
    SET @DynamicSQL = N'SELECT * INTO ' + @MyTableName + ' FROM BarTable';
    
    EXEC(@DynamicSQL);
    
    0 讨论(0)
  • 2021-02-05 18:00

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

    0 讨论(0)
  • 2021-02-05 18:03
    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.

    0 讨论(0)
提交回复
热议问题