2

我需要识别数据库中的所有主键。以下代码似乎可以很好地完成这项工作:

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

我遇到的问题是某些键是复合键。此查询标识哪些键是复合键(sys.indexes 表中特定 indexName 的多行),但它没有向我显示顺序。我需要知道这一点,因为:

PRIMARY KEY CLUSTERED 
(
[bl_id] ASC,
[fl_id] ASC,
[rm_id] ASC
)

不一样:

PRIMARY KEY CLUSTERED 
(
[rm_id] ASC
[fl_id] ASC,
[bl_id] ASC,

)

4

1 回答 1

3

key_ordinal 似乎可以解决问题:

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
于 2013-10-16T19:36:15.933 回答