Comma Separated List of all columns in the Database (Tablename | Column_names…)

后端 未结 3 1557
深忆病人
深忆病人 2021-02-03 10:30

In SQL Server, I would like see Table_Name and all the Columns associated with that Table_Name in a database. So the Output should look like this:

      TABLE_N         


        
相关标签:
3条回答
  • 2021-02-03 11:07
    select name as TABLE_NAME,
           STUFF(COLUMN_NAME, 1, 1, '') AS COLUMN_NAME
    from sys.tables t
    CROSS APPLY 
    ( 
            SELECT 
                ',' + name AS [text()] 
            FROM 
                sys.columns c
            WHERE 
                c.object_id = t.object_id
            FOR XML PATH('') 
        ) o (COLUMN_NAME)
    
    0 讨论(0)
  • 2021-02-03 11:22
    Select TABLE_SCHEMA, TABLE_NAME
        , Stuff(
            (
            Select ', ' + C.COLUMN_NAME
            From INFORMATION_SCHEMA.COLUMNS As C
            Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
                And C.TABLE_NAME = T.TABLE_NAME
            Order By C.ORDINAL_POSITION
            For Xml Path('')
            ), 1, 2, '') As Columns
    From INFORMATION_SCHEMA.TABLES As T
    

    As mentioned in comments, the above will include views. If you want to exclude views you can do the following:

    Select T.TABLE_SCHEMA, T.TABLE_NAME
        , Stuff(
            (
            Select ', ' + C.COLUMN_NAME
            From INFORMATION_SCHEMA.COLUMNS As C
            Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
                And C.TABLE_NAME = T.TABLE_NAME
            Order By C.ORDINAL_POSITION
            For Xml Path('')
            ), 1, 2, '') As Columns
    From INFORMATION_SCHEMA.TABLES As T
        Left Join INFORMATION_SCHEMA.VIEWS As V
            On V.TABLE_SCHEMA = T.TABLE_SCHEMA
                And V.TABLE_NAME = T.TABLE_NAME
    Where V.TABLE_NAME Is Null
    
    0 讨论(0)
  • 2021-02-03 11:26

    Since your question mentions 'in a database', rather than use the information schema, I used the database:

    select t.name, 
            STUFF ((
                select ',' + c.name
                from TEST_DB.sys.columns c
                    join TEST_DB.sys.tables tt on tt.object_id = t.object_id and t.object_id = c.object_id
                    join TEST_DB.sys.schemas s on tt.schema_id = s.schema_id
                order by t.name, c.column_id
                for xml path('')), 1, 1, '') as columns
    from TEST_DB.sys.tables t
                where t.name = 'PutTableNameHere if you want to filter'
    

    Leave the where clause out for all tables in a specific database.

    0 讨论(0)
提交回复
热议问题