选择仅包含特定表的数据库

时间:2013-05-13 10:19:03

标签: sql sql-server sql-server-2008-r2

我正在寻找一种方法来选择我的sql server上的所有数据库,它只包含表“dbo.mytable”

我该怎么做?

我已经有了这两个sql查询:

Select name From sys.databases Where database_id > 5

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]

第一个查询,列出我的sql server上的所有数据库,第二个查询是否存在dbo.mytable。我想合并它们。

由于

3 个答案:

答案 0 :(得分:13)

将它们全部带回一个结果集的简洁方法是

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

答案 1 :(得分:4)

您可以使用sp_Msforeachdb作为未记录的存储过程并在所有数据库上运行:

EXEC sp_Msforeachdb "use [?];select * from sys.tables where name='MYTable' "

有关sp_msforeachtable的更多信息:The undocumented sp_MSforeachdb procedure

答案 2 :(得分:4)

返回数据库列表,其中包含指定的表 -

<强>查询:

DECLARE 
      @SQL NVARCHAR(MAX)
    , @table_name SYSNAME

SELECT @table_name = 'dbo.test'

IF OBJECT_ID('tempdb.dbo.#db_temp') IS NOT NULL
    DROP TABLE #db_temp 

CREATE TABLE #db_temp (db_nm SYSNAME)

SELECT @SQL = (
    SELECT '
        USE [' + d.name + ']; 

        INSERT INTO #db_temp (db_nm)
        SELECT DB_NAME()
        WHERE EXISTS(
            SELECT 1
            FROM sys.objects
            WHERE [object_id] = OBJECT_ID(''' + @table_name + ''')
                AND [type] = ''U''
        )'
    FROM sys.databases d
    WHERE d.name NOT IN ('master', 'tempdb', 'model', 'msdb')
        AND d.state_desc != 'OFFLINE'
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')

EXEC sys.sp_executesql @SQL

SELECT * 
FROM #db_temp dt

<强>输出:

USE [...]; 

INSERT INTO #db_temp (db_nm)
SELECT DB_NAME()
WHERE EXISTS(
    SELECT 1
    FROM sys.objects
    WHERE [object_id] = OBJECT_ID('...')
        AND [type] = 'U'
)

...