如何访问特定数据库上的INFORMATION_SCHEMA.TABLES

时间:2012-05-07 15:26:19

标签: sql tsql

我正在尝试获取服务器上的数据库列表,其数据库包含表“Foobar”。我遇到的障碍是我无法弄清楚如何将@CurrDB与INFORMATION_SCHEMA结合使用。有什么建议吗?

DECLARE @CurrDB varchar(255)
DECLARE RecSet CURSOR FOR
Select [name] FROM master..sysdatabases
OPEN RecSet

Fetch NEXT FROM RecSet Into @CurrDB

WHILE (@@FETCH_STATUS = 0)   
BEGIN 
    Fetch NEXT FROM RecSet Into @CurrDB
    IF (EXISTS (SELECT * FROM @CurrDB..INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Foobar')) 
    BEGIN 
        print @CurrDB
        --do other stuff
    END 
END

Close RecSet
DEALLOCATE RecSet

2 个答案:

答案 0 :(得分:3)

试试这个:

sp_msforeachdb 'SELECT ''?'' As DatabaseName 
                FROM   [?].INFORMATION_SCHEMA.TABLES 
                WHERE  TABLE_Name = ''foobar'''

您还可以使用以下代码使用数据库名称列表填充表变量。

Declare @DatabaseList Table(DatabaseName VarChar(200))

insert Into @DatabaseList
Exec sp_msforeachdb 'If Exists(SELECT ''?'' As DatabaseName 
                FROM   [?].INFORMATION_SCHEMA.TABLES 
                WHERE  TABLE_Name = ''YourTableNameHere'') Select ''?'''

Select * From @DatabaseList

答案 1 :(得分:0)

以下存储过程将根据传递给此sp的参数显示所有数据库和表。

CREATE PROCEDURE Usp_findtablenameinalldatabase @TableName VARCHAR(256) 
AS 
    DECLARE @DBName VARCHAR(256) 
    DECLARE @varSQL VARCHAR(512) 
    DECLARE @getDBName CURSOR 

    SET @getDBName = CURSOR 
    FOR SELECT name 
        FROM   sys.databases 

    CREATE TABLE #tmptable 
      ( 
         DBName     VARCHAR(256), 
         SchemaName VARCHAR(256), 
         TableName  VARCHAR(256) 
      ) 

    OPEN @getDBName 

    FETCH next FROM @getDBName INTO @DBName 

    WHILE @@FETCH_STATUS = 0 
      BEGIN 
          SET @varSQL = 'USE ' + @DBName + '; INSERT INTO #TmpTable SELECT ''' + @DBName + 
          ''' AS DBName, SCHEMA_NAME(schema_id) AS SchemaName, name AS TableName FROM sys.tables WHERE name LIKE ''%' 
          + @TableName + 
                        '%''' 

          EXEC (@varSQL) 

          FETCH next FROM @getDBName INTO @DBName 
      END 

    CLOSE @getDBName 

    DEALLOCATE @getDBName 

    SELECT * 
    FROM   #tmptable 

    DROP TABLE #tmptable 

go 

如何调用此sp:

EXEC usp_FindTableNameInAllDatabase 'TableName'