Search code examples
t-sqltemp

Dynamic SQL Command push into Temp table


I need to push the results from this code below into a undefined TEMP table. Temp table must be undefined because I wont know the column names of the result set .

declare @sql varchar(4000)
set @sql ='Select * from #Test'

exec (@sql) 

--Need to insert the final result set into #TempTableName because I need to use it in code lower down in my Stored Procedure.


Solution

  • Found the answer.............

    Needed to use a Global Temp table and that did it for me.

    declare @sql varchar(4000)
    set @sql ='Select * INTO ##TempTableName from #Test'
    
    exec (@sql) 
    
    Select * from ##TempTableName 
    

    The ## is for a global temp table and that worked for me.