SQL Server: Drop a temporary table if it already exists

I recently needed to drop a temporary table if it already existed, I don’t know why but I ended up using the following script:
BEGIN TRY
DROP TABLE #[TABLE]
END TRY
BEGIN CATCH
END CATCH

It’s a familiar construct, we simply try the drop, catch any errors, ignore them and carry on with the rest of the script.

I find this much easier than the normal SQL Server drop scripting you will see when you generate a drop and create script, but of course any real errors won’t be caught by this and I don’t think you can even use that for temporary tables, hence why I used the above instead.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s