Search code examples
sql-server

How to access temptable after creating it dynamically


I am using the statement

SELECT    * 
INTO      #gsig_ref  
FROM      gsign 
WHERE     [name] NOT LIKE 'RESERVE%' OR [name] NOT LIKE 'Spare%'



EXECUTE('SELECT * INTO #db1 FROM ' + @db1)
EXECUTE('SELECT * INTO #db2 FROM ' + @db2)

where @db1 will be supplied at runtime (for eg @db1 = '#gsig_ref')

If I say select * from #db1... it says invalid object. Please help me how to access data from #db1.. since i have use this in another query like

SELECT        DISTINCT @p1 INTO #curs_name
FROM          #db1 
WHERE         @p1 NOT IN (SELECT @p2 FROM #db2)
ORDER BY      @p1

How can #db1 be acccessed in the above query and also @p1 is the input variable to this procedure and I should use it for the distinct @p1..


Solution

  • A local temporary table that is created in a stored procedure is dropped when the procedure ends; other stored procedures, or the calling process, can't see them.

    You could generate the entire SQL, effectively moving the temporary table to the dynamic SQL, like:

    declare @sql varchar(max);
    set @sql = 'select into #t1 ....; select * from #t1';
    exec (@sql);
    

    If I read that, I wonder why your outer procedure even needs the temporary table, but there may be good reasons for that.

    Another option, if you're sure only one call is executed at the same time, is to use a global temp table. They're declared with a double hash, like ##TempTable. Global temp tables survive the end of their procedure, but can be referenced from multiple sessions.