Check for the Existence of a Temp Table

Do you suffer from the pain of temporary tables hanging around long after you need them? Have you ever found yourself frantically googling, trying to remember the syntax to check for the existence of a temporary table before deleting it?

I, too, used to suffer alongside you, dear readers. I, too, know your pain of re-running a script only to find that a temporary table was skulking around in memory somewhere, waiting to ruin my carefully crafted three-value logic.

Well, my pain is gone thanks to my new found understanding of naming things in tempdb! You too can remove the terrible pain and suffering of searching for temp tables in your code and instead can use this one, that’s right only one, simple step to make sure that your temp tables are cleaned up by the time you need them again!

IF OBJECT_ID('tempdb..#magic') IS NOT NULL
  DROP TABLE #magic;

You’re welcome. Please make all checks payable to ‘cash’.

Menu