April 1, 2011 at 1:06 pm
I am trying to use this code I picked up to check for the existence of a table, but it doesn't seem to work right. Could someone please help out?
IF EXISTS (SELECT * from sysobjects
WHERE id = object_id('[DATABASE].[dbo].[TableName]') AND
OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE TableName
Thank you.
Steve
April 1, 2011 at 1:13 pm
Compared to the database you're running this code from, where is the table to be dropped? If it's in another database, then OBJECT_ID isn't going to work as you might expect it to.
--Jeff Moden
Change is inevitable... Change for the better is not.
April 1, 2011 at 1:30 pm
I am pulling from the same database. Basically what I am doing is creating a temp table in a sproc. Before I do I want to make sure the old one has been deleted.
April 1, 2011 at 4:57 pm
Ah... ok. From the code example you gave, I'm not sure if you're trying to drop an actual Temp Table or an expendible table in the current database. One of the two following methods should do the trick just fine (I use them all the time)...
--===== This will conditionally drop a table from the current database
IF OBJECT_ID('dbo.SomeTableName','U') IS NOT NULL
DROP dbo.SomeTableName
;
--===== This will conditionally drop a Temp Table for the current scope
IF OBJECT_ID('tempdb..#SomeTempTableName','U') IS NOT NULL
DROP #SomeTempTableName
;
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply