There is already an object named '##Temp' in the database

孤街醉人 提交于 2019-11-30 16:42:50

问题


I have a stored procedure on SQL Server 2000. It contains:
select ... into ##Temp ...
...
drop table ##Temp

When I run the stored procedure with ADO a second time, it prompts:
There is already an object named '##Temp' in the database.
Could anyone kindly tell me what's wrong?


回答1:


You should re-write your stored proc to drop the temp table if it exists, then you won't ever have this issue

IF (SELECT object_id('TempDB..##Temp')) IS NOT NULL
BEGIN
    DROP TABLE ##Temp
END



回答2:


You are using a global temp table as indicated by the ## at the beginning of the table name. This means multiple sessions can access the table.

It's likely that you have a connection open that created the table, but failed to drop it. Are you sure that the first ADO run actually drop the table. Could it have failed, or did the flow control in the procedure skip the drop statement?

You may want to test the procedure in SQL Server Enterprise Manager to see if it reports any errors.




回答3:


Since you chose to use a global temporary table ##Temp, it is visible to all SQL connections at any given time. Obviously, while the stored proc is running for one connection, a second connection comes in and tries to create yet another ##Temp but that already exists....

Use connection-local #Temp tables (only one #) instead.




回答4:


Oh, it's all my fault. I called the SP twice through one connection by mistake.
That's why it always reports error when being called the second time.
Of course you won't know that by reading my description. Sorry guys...




回答5:


For me this solution works :

IF (SELECT object_id ='#Temp') IS NOT NULL
BEGIN
   DROP TABLE #Temp
END


来源:https://stackoverflow.com/questions/3474053/there-is-already-an-object-named-temp-in-the-database

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