Dynamic SQL results into temp table in SQL Stored procedure

后端 未结 8 1365
孤独总比滥情好
孤独总比滥情好 2020-11-28 10:08

The code is as follows:

ALTER PROCEDURE dbo.pdpd_DynamicCall 
@SQLString varchar(4096) = null

AS

Begin

    create TABLE #T1 ( column_1 varchar(10) , colu         


        
8条回答
  •  攒了一身酷
    2020-11-28 11:00

    create a global temp table with a GUID in the name dynamically. Then you can work with it in your code, via dyn sql, without worry that another process calling same sproc will use it. This is useful when you dont know what to expect from the underlying selected table each time it runs so you cannot created a temp table explicitly beforehand. ie - you need to use SELECT * INTO syntax

    DECLARE @TmpGlobalTable varchar(255) = 'SomeText_' + convert(varchar(36),NEWID())
    
    -- select @TmpGlobalTable 
    
    -- build query
        SET @Sql = 
            'SELECT * INTO [##' + @TmpGlobalTable + '] FROM SomeTable'
    EXEC (@Sql)
    EXEC ('SELECT * FROM [##' + @TmpGlobalTable + '] ')
    EXEC ('DROP TABLE [##' + @TmpGlobalTable + ']')
    PRINT 'Dropped Table ' + @TmpGlobalTable 
    

提交回复
热议问题