Why DROP TABLE doesn't seem to take effect before a SELECT INTO?

倖福魔咒の 提交于 2020-01-03 16:45:39

问题


The following tSQL query is puzzling me:

select 1 as FIELD into #TEMP
drop table #TEMP
select 1 as FIELD into #TEMP

When I run it from SQL Server Management Studio session window (pressing F5 to the whole query, as a group), I get the following error:

Msg 2714, Level 16, State 1, Line 3
There is already an object named '#TEMP' in the database.

Note that table #TEMP doesn't exist before the query is executed.

I thought that the code shouldn't produce any errors as line 2 is dropping the temporary table. But it is as if the drop isn't taking effect when line 3 is executed.

My questions:

  1. Why does the error happen?
  2. How do I fix the query so it executes as intended?

PS. The query above is a simplification of a real world query of mine that is showing the same symptoms.

PS2. Regardless of whether this is a sound programming practice or not (as Sean hinted in his comments), this unexpected behavior prompted me to look for information on how these queries are parsed in the hopes that the knowledge will be helpful to me in the future.


回答1:


As I found the seek of existing tables are different:

select 1 as FIELD into #TEMP
drop table #TEMP

When you use into statement after those commands:

select 1 as FIELD into #TEMP

Error is:

There is already an object named '#TEMP' in the database.

And When you use a select on #TEMP after those commands:

select * from #TEMP

Error is:

Invalid object name '#TEMP'.

So, In first case THERE IS an object with #TEMP name and in the other case THERE IS NOT an object with #TEMP name !.

An important note from technet.microsoft is:

DROP TABLE and CREATE TABLE should not be executed on the same table in the same batch. Otherwise an unexpected error may occur.


In notes of dropping tables by SQL Server Database Engine:

The SQL Server Database Engine defers the actual page deallocations, and their associated locks, until after a transaction commits.

So the second error on using select statement may related to the actual page deallocations and the first error on using into statement may related to duration between lock associated until the transaction commits.




回答2:


Here try this:

select 1 as FIELD into #TEMP
drop table #TEMP
GO
select 1 as FIELD into #TEMP


来源:https://stackoverflow.com/questions/28944223/why-drop-table-doesnt-seem-to-take-effect-before-a-select-into

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!