Search code examples
sql-servert-sqlsessiontemp-tables

TSQL Writing into a Temporary Table from Dynamic SQL


Consider the following code:

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

Apparently this is because the exec command spins off a separate session and #temp is local to that session. I can use a global temporary table ##temp, but then I have to come up with a naming scheme to avoid collisions. What do you all recommend?


Solution

  • Didn't find a workable solution that did everything I needed so I switched to using ##global temp tables instead.