How to drop table if exists in sql server
By FoxLearn 2/19/2024 8:53:35 AM 62
IF OBJECT_ID('YourTableName', 'U') IS NOT NULL BEGIN DROP TABLE YourTableName; END
- OBJECT_ID('YourTableName', 'U')
: This function retrieves the object identification number (ID) of a specified object in the current database. In this case, it checks if the table with the name 'YourTableName' exists. The second argument 'U'
specifies that it's a user-defined table.
- IS NOT NULL
: Checks if the object ID returned by OBJECT_ID
is not null, which means the table exists.
- DROP TABLE YourTableName;
: This statement drops the table named 'YourTableName' if it exists.
By wrapping the DROP TABLE
statement inside the IF
block, you ensure that the table is dropped only if it exists in the database. This helps prevent errors that might occur if you attempt to drop a table that doesn't exist.
Another way you can use
1. DROP TABLE if exists querying the sys.tables
IF EXISTS(SELECT * FROM sys.tables WHERE SCHEMA_NAME(schema_id) LIKE 'dbo' AND name like 'YourTableName') DROP TABLE [dbo].[YourTableName]; GO
2. DROP TABLE if exists querying the INFORMATION_SCHEMA.TABLES
-- check if table exists in INFORMATION_SCHEMA.TABLES we will drop it IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA = 'dbo') DROP TABLE [dbo].[YourTableName]; GO
3. SQL Server 2016 and up, you can use DROP TABLE IF EXISTS
-- DROP TABLE only if it exists DROP TABLE IF EXISTS [dbo].[YourTable];
- SQL Server Migration Assistant
- How to Download and Restore Northwind database to SQL Server
- How to use SQL INSERT INTO SELECT Statement
- Data type SQL Server
- How to fix 'The specified directory for the INSTALLSHAREDDIR parameter is not valid'
- How to get all table names of a particular database using TSQL
- How to use ROW_NUMBER Function in SQL Server
- How to convert varchar to uniqueidentifier in SQL Server