DROP IF Exists SQL Server | DROP IF Exists Table | DROP IF Exists Procedure
SQL Server 2016 introduces a new DROP IF EXISTS SQL Server statement to DROP objects such as tables, columns, indexes, stored procedures, schemas, triggers and user-defined functions.
DROP IF EXISTS statement can be used to check whether the object exists before it is dropped or removed from the database.
This is Part 3 of 10 Part T-SQL Enhancements in SQL Server 2016 for Developers and DBAs. Click here to read it from the beginning….
There are times when before executing the TSQL code, we need to check if the stored procedure exists on SQL Server or if the table exists in SQL Server and if so, first, we need to drop them before executing the code. This article introduced the DROP IF EXISTS Statement, making it easier for you to DROP TABLE or DROP PROCEDURE if it exists on the SQL Server Database.
Drop If Exists SQL Server Clause
Prior to SQL Server 2016 you would write the T-SQL script similar to one below to check whether the object existed before it could be dropped from the database.
Use <DATABASENAME> GO IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SchemaName].[TableName]') AND [type] IN (N'U')) DROP TABLE [SchemaName].[TableName] GO
Trending SQL Server Articles and Tips
TSQL Query To Drop Table if Exists SQL Server | TSQL Query To Drop Procedure if Exists SQL Server
Example DROP IF EXISTS in SQL Server 2016
Starting SQL Server 2016, you could achieve the same functionality by executing the below simplified T-SQL script.
Use <DATABASENAME> GO DROP TABLE IF EXISTS [SchemaName].[TableName] GO DROP PROCEDURE IF EXISTS [SchemaName].[ProcedureName] GO
Clicking Next Page button to continue reading the topics and click on the Previous Page button to revisit the previous topic.
- ALTER TABLE WITH (ONLINE = ON | OFF)
- MAXDOP for DBCC CHECKDB, DBCC CHECKTABLE and DBCC CHECKFILEGROUP
- ALTER DATABASE SET AUTOGROW_SINGLE_FILE
- ALTER DATABASE SET AUTOGROW_ALL_FILES
- COMPRESS and DECOMPRESS Functions
- STRING_SPLIT and STRING_ESCAPE Functions
- FORMATMESSAGE Statement
- SERVERPROPERTY Function
- TRUNCATE TABLE WITH PARTITIONS
- DROP IF EXISTS