表名为Scores。

执行以下操作是否正确?

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

当前回答

我使用:

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

其他回答

从SQL Server 2016,您可以使用

DROP TABLE IF EXISTS dbo.Scores

参考:DROP IF EXISTS-SQL Server 2016中的新事物

它将很快出现在SQL Azure数据库中。

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

我编写了一个小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]

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

drop table if exists tableName cascade;