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

后端 未结 3 1555
深忆病人
深忆病人 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条回答
  •  闹比i
    闹比i (楼主)
    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.

提交回复
热议问题