T-SQL Drop temp table if it exists

The Problem

I often work in SQL Server with temp tables and they can be a pain when developing as you may have code like

Create Table #tblTemp( Id int , Value nvarchar(32))

Insert Into #tblTemp
select Id, Value from SomeOtherTableAndLotsOfJoins

--Drop Table #tblTemp

You comment out the drop as you want to check the results and do some testing but next time you want to run the script you have to remember to call the “Drop Table”

The Solution

Put this at the top of your script

if exists(SELECT * FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tblTemp'))
begin
    drop table #tblTemp;
end

As of SQL 2016 or later

DROP TABLE IF EXISTS #tlbTemp;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.