How to drop a SQL Server table only if exists? How to drop it only if the existence check shows it already exists in the database to avoid errors, using the DROP TABLE keyword. Indeed when running long SQL scripts or running scripts twice, it is much better to test the table existence. Indeed, we highly recommend testing the table existence to avoid the following error message.
With SQL Server, how to DROP a TABLE only if it exists with an existence check?
« Msg 3701, Level 11, State 5, Line 1
Cannot drop the table ‘SALES’, because it does not exist or you do not have permission. »
You want to DROP a table from your SQL Server database, but using directly the SQL command DROP TABLE followed by your table name, the DBMS system is throwing an error because the table is not an existing object. The solution is to test the existence of the table using a simple SQL query.
Solution: Test the SQL Server table existence before dropping it with the IF EXISTS and DROP functions.
IF EXISTS ( SELECT 1 FROM sys.objects WHERE object_id = object_id(N'[dbo].[SALES]') AND type in (N'U') ) BEGIN DROP TABLE [dbo].[SALES] END;
This post shows a SQL query to DROP a table after checking that it actually exists in the SQL Server database, and only if it exists in the database. Here is a SQL script to create a SQL Server table.