How do I list all tables in all databases in SQL Server in a single result set?

后端 未结 16 1236
轮回少年
轮回少年 2020-11-28 07:36

I am looking for T-SQL code to list all tables in all databases in SQL Server (at least in SS2005 and SS2008; would be nice to also apply to SS2000). The catch, however, is

16条回答
  •  天涯浪人
    2020-11-28 08:03

    I needed something that I could use to search all my servers using CMS and search by server, DB, schema or table. This is what I found (originally posted by Michael Sorens here: How do I list all tables in all databases in SQL Server in a single result set? ).

    SET NOCOUNT ON
    DECLARE @AllTables TABLE
            (
             ServerName NVARCHAR(200)
            ,DBName NVARCHAR(200)
            ,SchemaName NVARCHAR(200)
            ,TableName NVARCHAR(200)
            )
    DECLARE @SearchSvr NVARCHAR(200)
           ,@SearchDB NVARCHAR(200)
           ,@SearchS NVARCHAR(200)
           ,@SearchTbl NVARCHAR(200)
           ,@SQL NVARCHAR(4000)
    
    SET @SearchSvr = NULL  --Search for Servers, NULL for all Servers
    SET @SearchDB = NULL  --Search for DB, NULL for all Databases
    SET @SearchS = NULL  --Search for Schemas, NULL for all Schemas
    SET @SearchTbl = NULL  --Search for Tables, NULL for all Tables
    
    SET @SQL = 'SELECT @@SERVERNAME
            ,''?''
            ,s.name
            ,t.name
             FROM [?].sys.tables t 
             JOIN sys.schemas s on t.schema_id=s.schema_id 
             WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
             AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
             AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
             AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
          -- AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
               '
    -- Remove the '--' from the last statement in the WHERE clause to exclude system tables
    
    INSERT  INTO @AllTables
            (
             ServerName
            ,DBName
            ,SchemaName
            ,TableName
            )
            EXEC sp_MSforeachdb @SQL
    SET NOCOUNT OFF
    SELECT  *
    FROM    @AllTables
    ORDER BY 1,2,3,4
    

提交回复
热议问题