TSQL Writing into a Temporary Table from Dynamic SQL

后端 未结 8 1751
自闭症患者
自闭症患者 2020-12-11 04:55

Consider the following code:

SET @SQL1 = \'SELECT * INTO #temp WHERE ...\'
exec(@SQL1)
SELECT * from #temp  (this line throws an error that #temp doesn\'t ex         


        
相关标签:
8条回答
  • 2020-12-11 05:28

    There is a method of creating dummy temp table with single identity column, then altering that table with desired schema through dynamic SQL and populating it. That way you can use temporary table both in dynamic and regular SQL, join with it...

    -- Create dummy table
    CREATE TABLE #tmpContactData (PK int NOT NULL IDENTITY(1,1))
    
    -- Alter its schema
    DECLARE @sqlCommand nvarchar(max)
    SELECT @sqlCommand = '
    ALTER TABLE #tmpContactData
    ADD 
        EmployeeId int,
        Address varchar(100),
        Phone varchar(50)
    '
    EXECUTE(@sqlCommand)
    
    -- Fill it
    SELECT @sqlCommand = '
    INSERT INTO #tmpContactData
    SELECT t.EmployeeId, t.Address, t.Phone 
    FROM (  SELECT EmployeeId=1000, Address=''Address 1000'', Phone=''Phone 1000'' 
            UNION 
            SELECT 1001, ''Address 1001'', ''Phone 1001'' 
            UNION 
            SELECT 1002, ''Address 1002'', ''Phone 1002''
    ) t
    '
    EXECUTE(@sqlCommand)
    
    --select from it
    SELECT * FROM #tmpContactData
    
    --CleanUp
    DROP TABLE #tmpContactData
    
    0 讨论(0)
  • 2020-12-11 05:29

    Did you try to create your template table explicitly?

    Create Table #temp (..)
    
    0 讨论(0)
提交回复
热议问题