SQL Server SELECT INTO @variable?

前端 未结 7 1513
走了就别回头了
走了就别回头了 2020-12-02 03:56

I have the following code in one of my Sql (2008) Stored Procs which executes perfectly fine:

    CREATE PROCEDURE [dbo].[Item_AddItem]
        @CustomerId u         


        
7条回答
  •  我在风中等你
    2020-12-02 04:26

    I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.

    So far what I do is concatenate the entire SQL code with the variables to use. Like this:

    declare @table_name as varchar(30)
    select @table_name = CONVERT(varchar(30), getdate(), 112)
    set @table_name = 'DAILY_SNAPSHOT_' + @table_name
    
    EXEC('
            SELECT var1, var2, var3
            INTO '+@table_name+'
            FROM my_view
            WHERE string = ''Strings must use double apostrophe''
        ');
    

    I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!

提交回复
热议问题