SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Create Temp Table Dynamically
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

plahanov
Starting Member

India
1 Posts

Posted - 08/07/2012 :  02:58:05  Show Profile  Reply with Quote
My requirement is to create a temp table and insert data into the temp table dynamically ( all sql statements are inside the string variable and execute it finally) .

I tried the following

DECLARE @SQL VARCHAR(200)

SET @SQL = 'CREATE TABLE #TEMPPDET (ANULVESAL NUMERIC(16,4),BASIC NUMERIC(16,4)) SELECT * FROM #TEMPPDET'
SELECT @SQL

EXEC(@SQL) -- here it returns the table headers

SELECT * FROM #TEMPPDET -- shows error Invalid object name '#TEMPPDET'.


The above script successfully execute and returns the results from the temp table (for the select query in the @sql variable )

But when I execute the SELECT * FROM #TEMPPDET
statement after the EXEC(@SQL) it shows some error.

So the scope of the temp table is only inside the variable ( string)?
How can I create a temp table dynamically like the above example and can able to use the temp table

Plahanov

SwePeso
Patron Saint of Lost Yaks

Sweden
29138 Posts

Posted - 08/07/2012 :  03:23:41  Show Profile  Visit SwePeso's Homepage  Reply with Quote
It has to do with scope.
if you create the temporary table in the dynamic sql, the table is destroyed when the scope ends.


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47189 Posts

Posted - 08/07/2012 :  10:00:17  Show Profile  Reply with Quote
you should be creating temporary table outside of dynamica sql and populating it with exec(@sql) call

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.16 seconds. Powered By: Snitz Forums 2000