I need to identify all the primary keys in a db. The following code appears to do the job quite well:
SELECT i.name AS IndexName,
OBJECT_NAME (ic.OBJECT_ID) AS TableName,
COL_NAME (ic.OBJECT_ID, ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
The problem I have is that some of the keys are compound keys. This query identifies which keys are compound (multiple rows for a particular indexName in the sys.indexes table) but it does not show me the order. I need to know this because:
PRIMARY KEY CLUSTERED
(
[bl_id] ASC,
[fl_id] ASC,
[rm_id] ASC
)
is not the same as:
PRIMARY KEY CLUSTERED
(
[rm_id] ASC
[fl_id] ASC,
[bl_id] ASC,
)
key_ordinal seems to do the trick:
SELECT i.name AS IndexName,
OBJECT_NAME (ic.OBJECT_ID) AS TableName,
COL_NAME (ic.OBJECT_ID, ic.column_id) AS ColumnName,
ic.Key_ordinal as ColumnOrder
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
ORDER BY ic.OBJECT_ID, ic.Key_ordinal
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.