How to find column names for all tables in all databases in SQL Server

前端 未结 13 617
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 04:30

I want to find all column names in all tables in all databases. Is there a query that can do that for me? The database is Microsoft SQL Server 2000.

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 04:38

    Normally I try to do whatever I can to avoid the use of cursors, but the following query will get you everything you need:

    --Declare/Set required variables
    DECLARE @vchDynamicDatabaseName AS VARCHAR(MAX),
            @vchDynamicQuery As VARCHAR(MAX),
            @DatabasesCursor CURSOR
    
    SET @DatabasesCursor = Cursor FOR
    
    --Select * useful databases on the server
    SELECT name 
    FROM sys.databases 
    WHERE database_id > 4 
    ORDER by name
    
    --Open the Cursor based on the previous select
    OPEN @DatabasesCursor
    FETCH NEXT FROM @DatabasesCursor INTO @vchDynamicDatabaseName
    WHILE @@FETCH_STATUS = 0
       BEGIN
    
       --Insert the select statement into @DynamicQuery 
       --This query will select the Database name, all tables/views and their columns (in a comma delimited field)
       SET @vchDynamicQuery =
       ('SELECT ''' + @vchDynamicDatabaseName + ''' AS ''Database_Name'',
              B.table_name AS ''Table Name'',
             STUFF((SELECT '', '' + A.column_name
                   FROM ' + @vchDynamicDatabaseName + '.INFORMATION_SCHEMA.COLUMNS A
                   WHERE A.Table_name = B.Table_Name
                   FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''NVARCHAR(MAX)'')
                   , 1, 2, '''') AS ''Columns''
       FROM ' + @vchDynamicDatabaseName + '.INFORMATION_SCHEMA.COLUMNS B
       WHERE B.TABLE_NAME LIKE ''%%''
             AND B.COLUMN_NAME LIKE ''%%''
       GROUP BY B.Table_Name
       Order BY 1 ASC')
    
       --Print @vchDynamicQuery
       EXEC(@vchDynamicQuery)
    
       FETCH NEXT FROM @DatabasesCursor INTO @vchDynamicDatabaseName
    END
    CLOSE @DatabasesCursor
    DEALLOCATE @DatabasesCursor
    GO
    

    I added a where clause in the main query (ex: B.TABLE_NAME LIKE ''%%'' AND B.COLUMN_NAME LIKE ''%%'') so that you can search for specific tables and/or columns if you want to.

提交回复
热议问题