June 19, 2009 at 6:07 am
I would like to check the existance of an object in a second database.
Running a query with "use [db1]" works fine, but seeing as you cannot use 'Use' in a proc... im lost
Lets say I'm running the query from db2
Then i want to do a check on an object to see if it exists. simple right?
if exists(select * from dbo.sysobjects where id = object_id(N'[db1].[dbo].[sale]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
print 'True'
Else Print 'False'
I've also tried:
if exists(select * from db1.dbo.sysobjects where id = object_id(N'[dbo].[sale]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
print 'True'
Else Print 'False'
And finally tried:
if exists(select * from master.dbo.sysobjects where id = object_id(N'[dbo].[sale]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
print 'True'
Else Print 'False'
No Luck.
Is there any way to query sysobjects in a proc for a different db than the one you are working in?
I've stripped out the query, and I'm now debugging for the following query:
select * from dbo.sysobjects where id = object_id(N'[dbo].[sale]') and OBJECTPROPERTY(id, N'IsUserTable') = 1
If I select the correct database or "use db1" then it works. when on a different database, no combination sof servernames/databasenames.schema.objects does the trick.
June 19, 2009 at 6:11 am
prefix the database name in the query.
if exists(select * from db2.dbo.sysobjects where id = object_id(N'[db2].[dbo].[sale]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
June 19, 2009 at 6:28 am
Tried this as well. No Luck 🙁
June 19, 2009 at 6:32 am
select * from db2..sysobjects where name='myTablename' and xtype='U' should return a row if myTableName exists in db2 or NULL if it doesn't.
June 19, 2009 at 6:39 am
ok here is a generic query:
if exists(select * from msdb.dbo.sysobjects where id = object_id(N'[msdb].[dbo].[RTblClassDefs]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
print 'true'
Stand on msdb, and run the query, true is printed
Stand on any other db, run it... and nothing.
June 19, 2009 at 6:43 am
The problem is that "OBJECTPROPERTY(id, N'IsUserTable')" is going to check against the id in the current database, not the id in db2.
Try this:-
if exists(select * from db2.dbo.sysobjects where id = object_id(N'[db2].[dbo].[sale]') and Xtype = 'U')
June 19, 2009 at 6:47 am
Ian Scarlett, You da man!
Thanks!
That did the trick just nicely!
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply