Dynamic SQL results into temp table in SQL Stored procedure

后端 未结 8 1320
孤独总比滥情好
孤独总比滥情好 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 10:50
    CREATE PROCEDURE dbo.pdpd_DynamicCall 
    AS
    DECLARE @SQLString_2 NVARCHAR(4000)
    SET NOCOUNT ON
    Begin
        --- Create global temp table
        CREATE TABLE ##T1 ( column_1 varchar(10) , column_2 varchar(100) )
    
        SELECT @SQLString_2 = 'INSERT INTO ##T1( column_1, column_2) SELECT column_1 = "123", column_2 = "MUHAMMAD IMRON"'
        SELECT @SQLString_2 = REPLACE(@SQLString_2, '"', '''')
    
        EXEC SP_EXECUTESQL @SQLString_2
    
        --- Test Display records
        SELECT * FROM ##T1
    
        --- Drop global temp table 
        IF OBJECT_ID('tempdb..##T1','u') IS NOT NULL
        DROP TABLE ##T1
    End
    
    0 讨论(0)
  • 2020-11-28 10:51

    Not sure if I understand well, but maybe you could form the CREATE statement inside a string, then execute that String? That way you could add as many columns as you want.

    0 讨论(0)
  • 2020-11-28 10:57
    INSERT INTO #TempTable
    EXEC(@SelectStatement)
    
    0 讨论(0)
  • 2020-11-28 10:58

    Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-11-28 11:01

    Try:

    SELECT into #T1 execute ('execute ' + @SQLString )
    

    And this smells real bad like an sql injection vulnerability.


    correction (per @CarpeDiem's comment):

    INSERT into #T1 execute ('execute ' + @SQLString )
    

    also, omit the 'execute' if the sql string is something other than a procedure

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