The table name is Scores
.
Is it correct to do the following?
IF EXISTS(SELECT *
FROM dbo.Scores)
DROP TABLE dbo.Scores
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.
The ANSI SQL/cross-platform way is to use the INFORMATION_SCHEMA, which was specifically designed to query meta data about objects within SQL databases.
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo')
drop table dbo.Scores;
Most modern RDBMS servers provide, at least, basic INFORMATION_SCHEMA support, including: MySQL, Postgres, Oracle, IBM DB2, and Microsoft SQL Server 7.0 (and greater).
I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:
CREATE FUNCTION [dbo].[Table_exists]
(
@TableName VARCHAR(200)
)
RETURNS BIT
AS
BEGIN
If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @TableName)
RETURN 1;
RETURN 0;
END
GO
To delete table User
if it exists, call it like so:
IF [dbo].[Table_exists]('User') = 1 Drop table [User]
A better visual and easy way, if you are using Visual Studio, just open from menu bar,
View -> SQL Server Object Explorer
it should open like shown here
Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.
This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.