The table name is Scores
.
Is it correct to do the following?
IF EXISTS(SELECT * FROM dbo.Scores) DROP TABLE dbo.Scores
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With