表名为Scores。

执行以下操作是否正确?

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

当前回答

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]

如果您正在使用visual Studio,只需从菜单栏打开,

查看->SQL Server对象资源管理器

它应该像这里所示那样打开

选择并右键单击要删除的表,然后删除。应显示这样的屏幕。单击更新数据库以确认。

此方法非常安全,因为它会向您提供反馈,并会警告删除的表与其他表之间的任何关系。

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

drop table if exists tableName cascade;

我使用:

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

ANSI SQL/跨平台方法是使用INFORMATION_SCHEMA,它专门用于查询SQL数据库中对象的元数据。

if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo')
    drop table dbo.Scores;

大多数现代RDBMS服务器至少提供基本的INFORMATION_SCHEMA支持,包括:MySQL、Postgres、Oracle、IBM DB2和Microsoft SQL Server 7.0(及更高版本)。