获取表的主键列

时间:2014-03-25 22:14:14

标签: sql-server

我想确定这是获取给定表名称的pk名称,架构,表名和列名的正确方法。

SELECT i.name AS IndexName,
       (SELECT SCHEMA_NAME([schema_id]) FROM sys.[tables] WHERE [object_id] = ic.OBJECT_ID) SchemaName,
       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
   AND OBJECT_NAME(ic.OBJECT_ID) = 'MyTable'

我相信这是有效的

SELECT i.name AS IndexName,
       SCHEMA_NAME([schema_id]) SchemaName,
       OBJECT_NAME(ic.OBJECT_ID) AS TableName,
       COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName, 
       ic.key_ordinal
  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
 INNER JOIN sys.[tables] st
    ON st.[object_id] = ic.OBJECT_ID
 WHERE i.is_primary_key = 1
   AND SCHEMA_NAME([schema_id]) = 'auth'
   AND OBJECT_NAME(ic.OBJECT_ID) = 'Profile'

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点,没有人“正确的方式”。这个可行,但是一些边缘情况会让你失望。一些小调整:

SELECT
  schema_name(t.schema_id) AS SchemaName
 ,t.name AS TableName
 ,i.name AS IndexName
 ,co.name AS ColumnName
 ,ic.key_ordinal AS ColumnOrder  --  [2]
  FROM sys.tables AS t
 INNER JOIN  sys.indexes AS i
    ON i.OBJECT_ID = t.OBJECT_ID
 INNER JOIN sys.index_columns AS ic
    ON i.OBJECT_ID = ic.OBJECT_ID
   AND i.index_id = ic.index_id
 INNER JOIN sys.columns AS co
    ON co.column_id = ic.index_column_id
   AND co.object_id = t.object_id
 WHERE i.is_primary_key = 1
   AND t.name = 'MyTable'
   AND schema_name(t.schema_id) = 'dbo'  --  [1]
 ORDER BY ic.key_ordinal  --  [2]

[1]允许您指定要搜索的模式(仅在您定义了超过dbo时才重要)

[2]涵盖复合(多列)索引,并显示其顺序