Thursday, June 28, 2007

Dropping Temp Tables in SQL Server

A typical task in a some stored procedures is to check whether or not a table exists and if so do something with it, perhaps dropping it.

If it is a temp table people sometimes are not sure how to go about this.

Here is some simple code to accomplish the task:


IF OBJECT_ID('tempdb..#tempT') IS NOT NULL
BEGIN
DROP TABLE #tempT
END


Remember that all the temp tables you create actually get created in the tempdb database, which is a system database (not the database you are using!). So replace #tempT with the name of your temp table, but leave the tempdb in there.

No comments: