Press "Enter" to skip to content

DROP IF EXISTS

In SQL Server 2016, DROP IF EXISTS was introduced to T-SQL for certain objects.

Below are the ones that I use most frequently, alongside the pre-SQL Server 2016 version for dropping the objects after checking that they exist.

Database:

-- SQL2016:
DROP DATABASE IF EXISTS testDatabase;
GO

-- Pre-SQL2016:
IF EXISTS (SELECT * FROM sys.databases WHERE name = N'testDatabase')
  DROP DATABASE testDatabase;
GO

Table:

-- SQL2016:
DROP TABLE IF EXISTS dbo.testTable;
GO

-- Pre-SQL2016:
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'testTable' 
    AND SCHEMA_NAME(schema_id) = 'dbo')
  DROP TABLE dbo.testTable;
GO

-- Alternative pre-SQL2016
IF OBJECT_ID('dbo.testTable', 'U') IS NOT NULL
  DROP TABLE dbo.testTable;
GO

Temp table:

-- SQL2016:
DROP TABLE IF EXISTS #testTempTable;
GO

-- Pre-SQL2016:
IF OBJECT_ID('tempdb..#testTempTable') IS NOT NULL
  DROP TABLE #testTempTable;
GO

Index:

-- SQL2016:
DROP INDEX IF EXISTS testIndex ON dbo.testTable;
GO

-- Pre-SQL2016:
IF EXISTS (SELECT * FROM sys.indexes I 
    INNER JOIN sys.tables T ON T.object_id = I.object_id 
    WHERE I.name = 'testIndex' 
      AND T.name = 'testTable' AND SCHEMA_NAME(T.schema_id) = 'dbo')
  DROP INDEX testIndex ON dbo.testTable;
GO

View:

-- SQL2016:
DROP VIEW IF EXISTS dbo.testView;
GO

-- Pre-SQL2016:
IF EXISTS (SELECT * FROM sys.views WHERE name = 'testView' 
    AND SCHEMA_NAME(schema_id) = 'dbo')
  DROP VIEW dbo.testView;
GO

Procedure:

-- SQL2016:
DROP PROCEDURE IF EXISTS dbo.testProc;
GO

-- Pre-SQL2016:
IF EXISTS (SELECT * FROM sys.procedures WHERE name = 'testProc' 
    AND SCHEMA_NAME(schema_id) = 'dbo')
  DROP PROCEDURE dbo.testProc;
GO

Temp procedure:

-- SQL2016:
DROP PROCEDURE IF EXISTS #testTempProc;
GO

-- Pre-SQL2016:
IF OBJECT_ID('tempdb..#testTempProc') IS NOT NULL
  DROP PROCEDURE #testTempProc;
GO

User:

-- SQL2016:
DROP USER IF EXISTS testUser;
GO

-- Pre-SQL2016:
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = 'testUser' 
    AND type IN ('S', 'U'))
  DROP USER testUser;
GO

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *