Monday, February 4, 2013

SQL Code Snippet - Check for and drop temp tables

Many times when doing development, I will see examples where people ran a piece of code multiple times, and then had drop table statements littering their code, usually commented out, but sometimes not (causing headaches when testing their code and having to return it because the table does not exist when you run it).

One of the easiest bits of code that you can add when testing, and is usually harmless to leave in your code overall, is the following:


IF object_id('tempdb..#tmp') IS NOT NULL
BEGIN
   DROP TABLE #tmp
END

The code checks for the existence of the table with the object_id given, and if it exists, drops it.

Extremely useful, but I am always surprised at how few people use this that do SQL development every day.

No comments:

Post a Comment