索引定义查询

问题描述 投票:0回答:1

我想使用 SQL 查询获取索引定义以及索引中所有包含的列。

以下查询似乎不起作用,任何帮助将不胜感激。

WITH IndexInfo AS (
    SELECT 
        t.name AS TableName,
        i.name AS IndexName,
        i.index_id,
        STUFF((
            SELECT ',' + c.name
            FROM sys.index_columns ic
            JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
            WHERE ic.object_id = i.object_id 
            AND ic.index_id = i.index_id 
            AND ic.is_included_column = 0  -- Key columns only
            ORDER BY ic.key_ordinal
            FOR XML PATH('')), 1, 1, '') AS KeyColumns,
        STUFF((
            SELECT ',' + c.name
            FROM sys.index_columns ic
            JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
            WHERE ic.object_id = i.object_id 
            AND ic.index_id = i.index_id 
            AND ic.is_included_column = 1  -- Included columns only
            FOR XML PATH('')), 1, 1, '') AS IncludedColumns
    FROM 
        sys.indexes i
    JOIN 
        sys.tables t ON i.object_id = t.object_id
    WHERE 
        i.is_primary_key = 0  -- Exclude primary key indexes
        AND i.is_unique = 0    -- Exclude unique indexes
)

SELECT 
    TableName, 
    IndexName, 
    KeyColumns, 
    IncludedColumns
FROM 
    IndexInfo
WHERE 
    EXISTS (
        SELECT 1
        FROM IndexInfo ii
        WHERE ii.TableName = IndexInfo.TableName
        AND ii.KeyColumns = IndexInfo.KeyColumns
        AND ii.IncludedColumns = IndexInfo.IncludedColumns
        AND ii.IndexName <> IndexInfo.IndexName  -- Find duplicate but different indexes
    )
ORDER BY 
    TableName, KeyColumns, IncludedColumns;

我想使用 SQL 查询获取索引定义以及索引中所有包含的列。

indexing
1个回答
0
投票
SELECT 
i.name AS index_name,
COL_NAME(ic.object_id, ic.column_id) AS column_name,
ic.is_included_column

来自 系统索引 i 内连接 sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id 在哪里 i.object_id = OBJECT_ID('your_table_name');

© www.soinside.com 2019 - 2024. All rights reserved.