检查表列上是否存在索引

时间:2014-06-09 08:29:29

标签: sql sql-server

我在表的一个列上定义了一个索引。我使用以下查询来确定索引是否存在于一列上。这似乎有效,但有更好的方法吗?我在stackoverflow上查看了其他解决方案,但这似乎不能很好地工作。

    SELECT MIN(ColumnsCount) FROM 
    (
    SELECT COUNT(*)  AS ColumnsCount, 
            SysIndex.name
    FROM sys.indexes As SysIndex
        Inner Join sys.index_columns As SysIndexCol On SysIndex.object_id = SysIndexCol.object_id And SysIndex.index_id = SysIndexCol.index_id 
        Inner Join sys.columns As SysCols On SysIndexCol.column_id = SysCols.column_id And SysIndexCol.object_id = SysCols.object_id  
    WHERE SysIndex.name 
    in 
    (
     Select 
        SysIndex.name
    From 
        sys.indexes As SysIndex
        Inner Join sys.index_columns As SysIndexCol On SysIndex.object_id = SysIndexCol.object_id And SysIndex.index_id = SysIndexCol.index_id 
        Inner Join sys.columns As SysCols On SysIndexCol.column_id = SysCols.column_id And SysIndexCol.object_id = SysCols.object_id 
    Where 
        type <> 0 
        And SysIndex.object_id in (Select systbl.object_id from sys.tables as systbl Where SysTbl.name = 'TableName')
        And SysCols.name = 'ColName'
    ) 
    GROUP BY SysIndex.name) A

4 个答案:

答案 0 :(得分:3)

您要检索的是给定表上索引中使用的最低列数,其中索引包含给定列。您的查询可以简化为:

    SELECT  TOP 1 ColumnsCount = COUNT(*)
    FROM    sys.index_columns AS ic
            INNER JOIN sys.indexes AS i
                ON ic.[object_id] = i.[object_id]
                AND ic.index_id = i.index_id
            INNER JOIN sys.columns AS c
                ON ic.[object_id] = c.[object_id]
                AND ic.column_id = c.column_id
    WHERE   ic.[object_id] = OBJECT_ID(N'dbo.YourTableName')
    AND     i.[type] != 0
    AND     ic.is_included_column = 0
    GROUP BY i.index_id
    HAVING  COUNT(CASE WHEN c.Name = 'YourColumnName' THEN 1 END) > 0
    ORDER BY ColumnsCount;

我在ic.is_included_column = 0中添加了条件,假设您不希望在帐户中包含非键列,也不想对给定列不是键列的索引感兴趣。如果此假设不正确,则删除此谓词。

但是,如果您当前的查询有效,我没有看到优化系统目录上的查询有很多好处。他们不太可能是性能杀手。

答案 1 :(得分:2)

这很简单,您不必成为root用户

SHOW INDEXES FROM %TABLE_NAME_% WHERE Column_name = %COLUMN_NAME%;

答案 2 :(得分:1)

不确定为什么这么大的查询,但如果我已经正确理解,您正在尝试查找表idx中是否存在特定索引X。如果是这种情况,那么您可以直接查询sys.indexes表,如下所示(假设您的索引名称为idx123且您的表名为table1

SELECT * 
FROM sys.indexes 
WHERE name='idx123' 
AND object_id = OBJECT_ID('table1')

答案 3 :(得分:0)

这对我有用:

select count(*) from sys.tables as t
inner join sys.columns as c
    on  t.object_id = c.object_id
inner join sys.index_columns as ic 
    on c.column_id = ic.column_id and c.object_id = ic.object_id
inner join sys.indexes as i
    on ic.index_id = i.index_id and ic.object_id = i.object_id

其中t.name ='table_name'和c.name ='column_name'