如果表存在,如何删除它?

问题描述:

表名是Scores.

以下做法正确吗?

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

以下做法正确吗?

Is it correct to do the following?

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

否.只有当表包含任何行时才会删除该表(如果表不存在,则会引发错误).

No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).

相反,您可以使用永久表

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

或者,您可以使用临时表

IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
  DROP TABLE #TempTableName; 

SQL Server 2016+ 有更好的方法,使用 DROP TABLE IF EXISTS ....请参阅 @Jovan 的回答.

SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by @Jovan.