Drop a SQL Server table if exists

Blue and white cubes structure

How to drop a SQL Server table 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.

How to Drop a SQL Server if exist in the database by using an existence check?

SQL Server Error:

« 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 the table name, the DBMS system is throwing an error because the table does not exist. 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.

  SELECT 1 FROM sys.objects
  WHERE object_id = object_id(N'[dbo].[SALES]')
    AND type in (N'U') 

This post shows how to Drop a SQL Server table only if it exist, after checking in the objects system table of the SQL Server database, after this only it is dropping the table.

Here is a SQL script to create a SQL Server table.

Be the first to comment

Leave a Reply