表名为Scores。

执行以下操作是否正确?

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

当前回答

IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
    DROP TABLE Scores
GO

其他回答

Or:

if exists (select * from sys.objects where name = 'Scores' and type = 'u')
    drop table Scores

确保在末尾使用级联约束来自动删除依赖于表的所有对象(例如视图和投影)。

drop table if exists tableName cascade;

在SQL Server 2016(13.x)及更高版本中

DROP TABLE IF EXISTS dbo.Scores

在早期版本中

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

U是您的桌子类型

我编写了一个小UDF,如果其参数是现有表的名称,则返回1,否则返回0:

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

要删除表User(如果存在),请按如下方式调用它:

IF [dbo].[Table_exists]('User') = 1 Drop table [User]

我使用:

if exists (select * 
           from sys.tables 
           where name = 'tableName' 
           and schema_id = schema_id('dbo'))
begin
    drop table dbo.tableName
end