简体   繁体   中英

Select from temp table fails

I'm inserting data into a temp table and querying the temp table fails

DECLARE @SQLQuery AS NVARCHAR(500)

SET @SQLQuery  = 'SELECT  Top 100 *
                  INTO #tempTable
                  FROM ' + @origDB + '.dbo.' + @origTable + ' o WITH (NOLOCK) ' 

EXECUTE sp_executesql @SQLQuery

and when I try to query the temp table , like so

select * from #tempTable

I get the following error :

Invalid object name '#tempTable'.

Courtesy of MSDN

The problem that you have is with the scope. The TEMP table is creatd at the scope of the EXEC() method and hence it is not available after the function returns. To fix this, create your temp table before calling EXEC() and use an INSERT INTO instead of SELECT INTO.

As others have said, the scope of a temporary table is limited to the session context in which it is created - a stored procedure runs in its own context.

You could use a global temporary table ##tempTable , but it's generally a bad idea as it would be available to other sessions than the one creating it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM