What is the best way to determine if a temporary table exists in SQL Server?

When writing a T-SQL script that I plan to re-run, I often use temporary tables to store temporary data. Since the temporary table is created on the fly, I would like to leave this table only if it exists (before its creation).

I will post the method that I use, but I would like to see if there is a better way.

+17
sql-server
Aug 05 '08 at 18:18
source share
3 answers
IF Object_Id('TempDB..#TempTable') IS NOT NULL BEGIN DROP TABLE #TempTable END 
+25
Aug 05 '08 at 18:21
source share

The OBJECT_ID function returns the identifier of the internal object for the name and type of this object. 'tempdb .. # t1' refers to table t1 in the tempdb database. 'U' for user table.

 IF OBJECT_ID('tempdb..#t1', 'U') IS NOT NULL DROP TABLE #t1 CREATE TABLE #t1 ( id INT IDENTITY(1,1), msg VARCHAR(255) ) 
+14
Aug 05 '08 at 18:21
source share
 SELECT name FROM sysobjects WHERE type = 'U' AND name = 'TempTable' 
0
Sep 17 '08 at 20:50
source share



All Articles