Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 494
Ricardo Avatar asked Mar 09 '15 14:03

Ricardo


2 Answers

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.

like image 71
shA.t Avatar answered Nov 15 '22 08:11

shA.t


Here try this:

select 1 as FIELD into #TEMP
drop table #TEMP
GO
select 1 as FIELD into #TEMP
like image 39
Stephan Avatar answered Nov 15 '22 09:11

Stephan