Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm looking for a way to select all databases on my sql server, which only contain the table "dbo.mytable"

How can i do this ?

I already have these two sql queries :

Select name From sys.databases Where database_id > 5

And

IF EXISTS
    (SELECT * FROM sys.objects 
    WHERE object_id = OBJECT_ID(N'[dbo].[mytable]') AND type in (N'U')) 
  Select 1 [Exists]
Else
  Select 0 [Exists]

The first query, lists all databases on my sql server, and the second checks if dbo.mytable exists. I would like to merge them.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
279 views
Welcome To Ask or Share your Answers For Others

1 Answer

A concise way that brings them all back in one resultset is

SELECT name
FROM   sys.databases
WHERE  CASE
         WHEN state_desc = 'ONLINE' 
              THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[mytable]', 'U')
       END IS NOT NULL 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...