Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

sql - 如果SQL Server中存在表,如何删除表?(How to drop a table if it exists in SQL Server?)

The table name is Scores . (表名是Scores 。)

Is it correct to do the following? (执行以下操作是否正确?)

IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores 
  ask by tmaster translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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的答案 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...