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). (号这将删除该表仅当它包含任何行(如果该表不存在会引发错误)。)
Instead, for a permanent table you can use (相反,对于永久表,您可以使用)
IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL
DROP TABLE dbo.Scores;
Or, for a temporary table you can use (或者,对于临时表,您可以使用)
IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
DROP TABLE #T;
SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …
. (SQL Server 2016+有一种更好的方法,使用DROP TABLE IF EXISTS …
) See the answer by @Jovan . (请参阅@Jovan的答案 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…