Drop Table If Exists Sql Server

 247 Total Views,  3 views today

Drop Table If Exists Sql Server:
Use the DROP TABLE statement to drop or remove an existing table definition and data for the specified table from the database.

Solution: 1
USE YourDatabaseName
GO
IF OBJECT_ID(‘YourTableName’, ‘U’) IS NOT NULL
DROP TABLE YourTableName;

Solution: 2
USE YourDatabaseName
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(‘YourTableName’) AND type in (‘U’))
DROP TABLE YourTableName;

Solution: 3
USE YourDatabaseName
GO
IF EXISTS (SELECT * FROM sys.objects WHERE name = ‘YourTableName’ and type = ‘U’)
DROP TABLE YourTableName;

Solution: 4 (From SQL Server 2016)
USE YourDatabaseName
GO
DROP TABLE IF EXISTS YourTableName;

Note: The DROP TABLE statement will fail if any other table is referencing the tableĀ  to be dropped through a foreign key constraint. If there are foreign key constraint, you must drop them first before dropping the primary key table.
Also See: Sql Drop Temp Table If Exists

Leave a Reply

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