Home > T-SQL > T-SQL Drop temp table if it exists

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'))
	drop table #tblTemp;
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

Categories: T-SQL Tags:
  1. No comments yet.
  1. No trackbacks yet.