views:

170

answers:

4

I have a client application that creates a temp table, the performs a bulk insert into the temp table, then executes some SQL using the table before deleting it.

Pseudo-code:

open connection
begin transaction
CREATE TABLE #Temp ([Id] int NOT NULL)
bulk insert 500 rows into #Temp
UPDATE [OtherTable] SET [Status]=0 WHERE [Id] IN (SELECT [Id] FROM #Temp) AND [Group]=1
DELETE FROM #Temp WHERE [Id] IN (SELECT [Id] FROM [OtherTable] WHERE [Group]=1)
INSERT INTO [OtherTable] ([Group], [Id]) SELECT 1 as [Group], [DocIden] FROM #Temp

DROP TABLE #Temp
COMMIT TRANSACTION
CLOSE CONNECTION

This is failing with an error on the DROP statement:

Cannot drop the table '#Temp', because it does not exist or you do not have permission.

I can't imagine how this failure could occur without something else going on first, but I don't see any other failures occurring before this.

Is there anything that I'm missing that could be causing this to happen?

+1  A: 

possibly something is happening in the session in between?

Try checking for the existence of the table before it's dropped:

IF object_id('tempdb..#Temp') is not null
BEGIN
   DROP TABLE #Temp
END
Nick Kavadias
I am adding some instrumentation to try to determine if the table is really gone, but in the meantime I can't see anything that could be causing this. There is no SQL occurring in the session other than what I have described and I am not getting any errors from the other statements
StarBright
A: 

The other failure is the AS in the table declaration

Scot Hauder
+2  A: 

I think you aren't creating the table at all, because the statement

CREATE TABLE #Temp ([Id] AS int)

is incorrect. Please, write it as

CREATE TABLE #Temp ([Id] int)

and see if it works.

eKek0
Sorry for the confusion, I was changing the table name to protect the innocent and I typed it wrong... The actual table definition is semantically correct, I will update the question
StarBright
+1  A: 

I've tested this on SQL Server 2005, and you can drop a temporary table in the transaction that created it:

begin transaction
create table #temp (id int)
drop table #temp
commit transaction

Which version of SQL Server are you using?

You might reconsider why you are dropping the temp table at all. A local temporary table is automatically deleted when the connection ends. There's usually no need to drop it explicitly.

A global temporary table starts with a double hash (f.e. ##MyTable.) But even a global temp table is automatically deleted when no connection refers to it.

Andomar
+1 for "why drop the temp table"
Philip Kelley