DROP TABLE fails for temp table

旧街凉风 提交于 2019-12-05 10:43:46

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

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.

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.

kamlesh kamble
BEGIN TRAN

IF object_id('DATABASE_NAME..#TABLE_NAME') is not null
BEGIN
   DROP TABLE #TABLE_NAME
END

COMMIT TRAN

Note:Please enter your table name where TABLE_NAME and database name where it says DATABASE_NAME

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