get a list of tables and the primary key

Solutions on MaxInterview for get a list of tables and the primary key by the best coders in the world

showing results for - "get a list of tables and the primary key"
Debora
28 Jun 2020
1select schema_name(tab.schema_id) as [schema_name], 
2    tab.[name] as table_name, 
3    pk.[name] as pk_name,
4    substring(column_names, 1, len(column_names)-1) as [columns]
5from sys.tables tab
6    left outer join sys.indexes pk
7        on tab.object_id = pk.object_id 
8        and pk.is_primary_key = 1
9   cross apply (select col.[name] + ', '
10                    from sys.index_columns ic
11                        inner join sys.columns col
12                            on ic.object_id = col.object_id
13                            and ic.column_id = col.column_id
14                    where ic.object_id = tab.object_id
15                        and ic.index_id = pk.index_id
16                            order by col.column_id
17                            for xml path ('') ) D (column_names)
18order by schema_name(tab.schema_id),
19    tab.[name]
20