Cynon
Cynon

Reputation: 117

IF Exists MSSQL always errors

I'm trying to drop a table if it exists.

I created a table, that worked fine. I can drop the table with the DROP TABLE command. What I can't do is any form of this:

DROP TABLE IF EXISTS customer;

In fact, I can't seem to get any form of IF EXISTS to work at all. I went to the MS website and looked up how to do this, and their example won't even run:

CREATE TABLE T1 (Col1 int);  
GO  
DROP TABLE IF EXISTS T1;  
GO  
DROP TABLE IF EXISTS T1;  

Any ideas?

Upvotes: 0

Views: 157

Answers (1)

Dan Guzman
Dan Guzman

Reputation: 46203

According to the documentation, the IF EXISTS clause is only allowed in Azure SQL Database and SQL Server 2016 or later. So it seems you are using SQL Server 2014 or earlier.

You'll need to first check that the table exists in earlier versions. One method is checking for a OBJECT_ID that is NOT NULL:

IF OBJECT_ID(N'dbo.customer', 'U') IS NOT NULL DROP TABLE dbo.customer;

Upvotes: 5

Related Questions