2014-03-25 69 views
0

我要確保這是獲得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' 
+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]涵蓋化合物(多列)索引,並顯示他們的訂單

+0

你說得對,我有你的觀點,但是這個查詢實際上並沒有給我多列PK,如果這是目的。 – rgx71

+0

它在索引中每列返回一行,而不是每列一列。 –

+0

好的謝謝,我的壞。 – rgx71

相關問題