Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop a table if it exists?

The table name is Scores.

Is it correct to do the following?

IF EXISTS(SELECT *           FROM   dbo.Scores)   DROP TABLE dbo.Scores 
like image 423
tmaster Avatar asked Oct 25 '11 09:10

tmaster


People also ask

How do you drop a table in SQL if it exists?

Option 1 - DROP TABLE if exists using OBJECT_ID() function (all supported versions) Using OBJECT_ID() will return an object id if the name and type passed to it exists.

How do you delete a table that already exists?

The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.

Can you drop a table if reference key exists on another table?

In SQL Server, you cannot drop a table if it is referenced by a FOREIGN KEY constraint. You have to either drop the child tables before removing the parent table, or remove foreign key constraints.

What happens if you drop a table on which a view exists?

When you drop a view, the definition of the view and other information about the view is deleted from the system catalog. All permissions for the view are also deleted. Any view on a table that is dropped by using DROP TABLE must be dropped explicitly by using DROP VIEW.


2 Answers

Is it correct to do the following?

IF EXISTS(SELECT *           FROM   dbo.Scores)   DROP TABLE dbo.Scores 

No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).

Instead, for a permanent table you can use

IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL    DROP TABLE dbo.Scores;  

Or, for a temporary table you can use

IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL   DROP TABLE #TempTableName;  

SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by @Jovan.

like image 152
Martin Smith Avatar answered Oct 06 '22 01:10

Martin Smith


From SQL Server 2016 you can use

DROP TABLE IF EXISTS dbo.Scores 

Reference: DROP IF EXISTS - new thing in SQL Server 2016

It will be in SQL Azure Database soon.

like image 40
Jovan MSFT Avatar answered Oct 06 '22 01:10

Jovan MSFT