表名为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

其他回答

我使用:

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]

如果您使用长代码,并且希望为临时表编写更少的代码,请创建以下过程:

CREATE PROCEDURE MF_DROP (@TEMP AS VARCHAR(100)) AS
    EXEC('IF OBJECT_ID(''TEMPDB.DBO.' + @TEMP + ''', ''U'') IS NOT NULL DROP TABLE ' + @TEMP)

执行中:

EXEC MF_DROP #A
CREATE TABLE #A (I INT) ....

我希望这有助于:

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

简单的是:

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

其中dbo.TableName是所需的表,“U”是表的类型。