查询获取外键索引

时间:2012-10-18 19:12:55

标签: sql-server foreign-keys indexing

我在sql server中寻找一个查询,它会显示我数据库中所有外键索引的列表。我的数据库中有一堆索引,有些是在表的外键上,我希望删除除了外键和主键之外的所有索引。

3 个答案:

答案 0 :(得分:2)

这是一个可以满足您需求的查询。

SELECT 
sc.name + '.' + t.name as tableName,
i.name as indexName,
c.name as columnName
FROM sys.foreign_key_columns fkc
JOIN sys.index_columns ic ON ic.object_id = fkc.parent_object_id
    AND ic.column_id = fkc.parent_column_id
JOIN sys.indexes i ON i.index_id = ic.index_id
    AND i.object_id = ic.object_id
JOIN sys.columns c ON c.object_id = ic.object_id
    AND c.column_id = ic.column_id  
JOIN sys.tables t ON t.object_id = c.object_id
JOIN sys.schemas sc ON sc.schema_id = t.schema_id
where t.is_ms_shipped = 0
ORDER BY tableName, indexName, columnName

答案 1 :(得分:2)

也许第一个答案的扭曲可以为你做到这一点?:

SELECT 
    sc.name + '.' + t.name as tableName,
    OBJECT_NAME(fkc.constraint_object_id) AS [FKey-Name],
    OBJECT_NAME(fkc.referenced_object_id) ReferencedTable, 
c.name as ColumnName
, i.name AS ReferencedKeyName
FROM    sys.foreign_key_columns fkc
JOIN    sys.index_columns ic ON ic.object_id = fkc.parent_object_id
    AND ic.column_id = fkc.parent_column_id
JOIN    sys.indexes i ON i.index_id = ic.index_id
    AND i.object_id = ic.object_id
JOIN sys.columns c ON c.object_id = ic.object_id
    AND c.column_id = ic.column_id  
JOIN    sys.tables t ON t.object_id = c.object_id
JOIN    sys.schemas sc ON sc.schema_id = t.schema_id
WHERE   t.is_ms_shipped = 0
ORDER BY tableName, OBJECT_NAME(fkc.constraint_object_id), columnName

答案 2 :(得分:0)

SELECT fk.name, 
       OBJECT_NAME(fk.parent_object_id) AS parent_table,
       c1.name AS parent_column, 
       OBJECT_NAME(fk.referenced_object_id) AS referenced_table, 
       c2.name AS referenced_column
    FROM sys.foreign_keys fk
        INNER JOIN sys.foreign_key_columns fkc
            ON fk.object_id = fkc.constraint_object_id
        INNER JOIN sys.columns c1
            ON fkc.parent_object_id = c1.object_id
                AND fkc.parent_column_id = c1.column_id
        INNER JOIN sys.columns c2
            ON fkc.referenced_object_id = c2.object_id
                AND fkc.referenced_column_id = c2.column_id