Temporary tables existence during Dynamic SQL usage in SQL Server

Published 13 November 08 12:33 AM | SQL Master 

Here is an interesting question posted in the forums here asking about:

Lots of time I face the problem with dynamic sql that I cant get the temporary table with data created through dynamic sql.

for instance:

SET NOCOUNT ON
DROP TABLE Employee
CREATE TABLE Employee(EmpId INT, EmpName VARCHAR(50), Sal    DECIMAL(13,2))
INSERT INTO Employee VALUES(1, 'Nishant', 30000)
INSERT INTO Employee VALUES(2, 'Ashish', 40000)
INSERT INTO Employee VALUES(3, 'Sushant', 60000)

EXEC('SELECT * INTO #Temp FROM Employee')

SELECT * FROM #Temp
DROP TABLE #Temp


Is there any way to get temporary table?

To cut long story short, as you may aware that the local temporary table that is created at one level of the code is not visible or dropped once the execution is finished, though the table gets created in the dynamic sql batch but you cannot query the table after the batch is executed.  You can create the temporary table in advance (before invoking the dynamic sql) and then insert in your dynamic sql. If the table structure is unknown in advance then you can still create it at the outer level with a dummy column, and then inside a dynamic sql batch alter and add the columns you need/drop the dummy column, followed by insert in another dynamic batch.

 For all the information about DSQL refer to The curse and blessings of dynamic SQL bible.

 

Comments

# Other SQL Server Blogs around the Web said on November 13, 2008 12:42 AM:

Here is an interesting question posted in the forums here asking about: Lots of time I face the problem

# SQL Server Transact-SQL (SSQA.net) : Temporary tables existence during Dynamic SQL usage in SQL Server said on November 13, 2008 12:49 AM:

PingBack from http://sqlserver-qa.net/blogs/t-sql/archive/2008/11/13/5068.aspx

# ravims said on January 28, 2009 4:09 PM:

Excellent problem.

Since each EXEC is considered one batch, the #temp table is created within the batch and is not accesable from another EXEC.

Replace the last 3 lines of the code using the code below, it will work.

EXEC ('

SELECT * INTO #Temp FROM Employee;

SELECT * FROM #Temp;

DROP TABLE #Temp;

');

ravims

Anonymous comments are disabled

About SQL Master

**__________________________________** SQL Server MVP, Sr. DBA & industry expert. - Knowledge is of two kinds. We know a subject ourselves or we know where we can find information on it. It is also a power and you will gain by sharing it.

Search

Go

This Blog

«November 2008»
SMTWTFS
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

Syndication