in

ASP.NET Weblogs

Jason Nadal

Restless C#ding

Check for the existence of a sql temp table

Here's an easy way to check if a temp table exists, before trying to create it (ie. for reusable scripts) from Simon Sabin's post :

IF object_id('tempdb..#MyTempTable') IS NOT NULL
BEGIN
   DROP TABLE #MyTempTable
END

CREATE TABLE #MyTempTable
(
   ID int IDENTITY(1,1),
   SomeValue varchar(100)
)
GO


That way, if you have to change databases in the query window, you don't have to drop the tables before you run it again.

Published Feb 24 2006, 08:10 AM by thejay2
Filed under:

Comments

 

Bilal Haidar [MVP] said:

Hello Jason:
Although Temp tables might come handy sometimes. However, I knew recently that using a table declared as a TABLE Type is much better, especially that you don't need to make sure the temp table is deleted or not, since it will be automatically deleted, here is an example:

DECLARE @TempTable TABLE
(
Id INT,
Name VARCHAR(50)
)

Then you can deal with the table @TempTable similar to any other table, with some limitations, but at least it does what is required from a temp table.

Hope that helps,
Regards
February 24, 2006 8:24 AM
 

Bill said:

Sometimes a temp table is necessary.  For example, if you are inserting data from executing a sproc.

Example:

INSERT INTO #job_status

EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,'sa', @jobid

July 12, 2007 12:16 PM
 

zom said:

Declared table variables suffer a performance hit when dealing with larger (1k records+) datasets in my experience.

Temp tables are still king when dealing with temporary data sets for performance.

April 16, 2008 11:02 AM
 

Smita said:

Hey, it works gr8!!

Thanks!!

Cheers!!

April 16, 2008 5:23 PM
 

Gnana said:

that was useful! thanks!

April 17, 2008 10:14 AM
 

Ray said:

I like in memory tables too. If you need to use it in a loop with an identity column where you want to repopulate the in memory table each time thru the loop. Truncate table will not work, and Delete table, doesn't reset the identity. I guess you can calculate it.

April 17, 2008 4:55 PM
 

dev said:

thanks dude it works i was finding a lot in server 2000 books.

but i found over here.

again thanks for the help

July 31, 2008 3:13 AM
 

Daft said:

Cool tip, works a treat, thanks :)

August 7, 2008 7:04 AM
 

moongy said:

oh, thats what i looking for. thanks alot !

September 16, 2008 5:13 AM

Leave a Comment

(required)  
(optional)
(required)  
Add