Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop a table in SQL Server 2008 only if exists

Our company is migrating one of its products from SQL Server 2005 to 2008, and in the logs I've noticed excess of errors about deleting tables if it does not exist. In SQL Server 2005 we had this to delete tables

IF OBJECT_ID('dbo.Units', 'U') IS NOT NULL
   DROP TABLE dbo.Units

which doesn't seem to work anymore.

What would be the proper way of deleting a table only if it exists in SQL Server 2008?

like image 484
kooker Avatar asked Feb 11 '15 23:02

kooker


1 Answers

This should do it!

IF EXISTS 
        (SELECT 
             TABLE_NAME 
         FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TableToDrop') 
DROP TABLE TableToDrop
like image 106
Spiky Avatar answered Oct 04 '22 21:10

Spiky