22

When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).

I'll post the method that I use, but I'd like to see if there is a better way.

4 Answers 4

31
IF Object_Id('TempDB..#TempTable') IS NOT NULL
BEGIN
    DROP TABLE #TempTable
END
16

The OBJECT_ID function returns the internal object id for the given object name and type. 'tempdb..#t1' refers to the table #t1 in the tempdb database. 'U' is for user-defined table.

IF OBJECT_ID('tempdb..#t1', 'U') IS NOT NULL
  DROP TABLE #t1

CREATE TABLE #t1
(
  id INT IDENTITY(1,1),
  msg VARCHAR(255)
)
0

The best way is to use:

DROP TABLE IF EXISTS #TempTable
1
  • For SQL Server 2016 onwards.
    – TT.
    Feb 12 at 9:36
-1
SELECT name
FROM sysobjects
WHERE type = 'U' AND name = 'TempTable'
1
  • 1
    Keith, it looks like that query will find normal user tables, but not temporary tables. Jan 13, 2009 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.