Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Dropping #Temp Tables

Author  Topic 

SQLCode
Posting Yak Master

143 Posts

Posted - 2004-12-15 : 17:52:02
Hi,

To drop a table already existing we use
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Drop table [dbo].[MyTable]

To Drop a #Temp Table?

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#MyTempTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Drop table [dbo].[#MyTempTable]

This does not work since it is not in sysobjects. How would I do it?
I need it for DTS

Any help is greatly appreciated.

Thanks.

nr
SQLTeam MVY

12543 Posts

Posted - 2004-12-15 : 18:27:24
You should never need to do this as you should know whether or not you have created a temp table. Created in diferent/nested bactches the temp tables are different objects.

but
if object_id('tempdb..#mytbl') is not null


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

clarkbaker1964
Constraint Violating Yak Guru

428 Posts

Posted - 2004-12-15 : 23:13:35
Thank's for the tip...
I usually write the drop table at the end of my process in QA but I often find myself fixing bugs and running the delete before rerunning the procedure... yea yea onerror goto blah blah blah


Go to Top of Page

nr
SQLTeam MVY

12543 Posts

Posted - 2004-12-15 : 23:15:43
while i'm testing in qa I will put at the top
drop table #a
go
drop table #b
go
...

Will give errors if the table isn't there but will carry on.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2004-12-16 : 01:21:32
In production code youi won't need this since the temp tables are dropped when they go out of scope. For debugging, you can use this technique:

create table #Junk (
pkey int primary key
)
go

if exists (
select *
from tempdb.dbo.sysobjects
where id = Object_id('tempdb.dbo.#Junk')
)
begin
drop table #Junk
end



HTH

=================================================================

Happy Holidays!
Go to Top of Page

clarkbaker1964
Constraint Violating Yak Guru

428 Posts

Posted - 2004-12-16 : 02:13:04
Yea and I don't have QA close connections on completion i think that's an option so the temp table will remain as long as the connection is open... Thank guys for the additional feedback. Anyone see the osql question I posted?

Go to Top of Page
   

- Advertisement -