表名为Scores。

执行以下操作是否正确?

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

当前回答

SQL Server 2016及以上版本最好、最简单的版本是删除表(如果存在)[表名称]

Ex:

DROP TABLE IF EXISTS dbo.Scores

如果假设上面的方法不起作用,那么可以使用下面的方法

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

其他回答

我希望这有助于:

begin try drop table #tempTable end try
begin catch end catch

我使用:

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

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

SQL Server 2016及以上版本最好、最简单的版本是删除表(如果存在)[表名称]

Ex:

DROP TABLE IF EXISTS dbo.Scores

如果假设上面的方法不起作用,那么可以使用下面的方法

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