如何确定复合键中的列位置

时间:2013-10-16 19:26:04

标签: sql sql-server-2008

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

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,

1 个答案:

答案 0 :(得分: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