加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 用于查找冗余索引的T-SQL

发布时间:2020-12-12 07:49:34 所属栏目:MsSql教程 来源:网络整理
导读:是否有人知道可以检测整个数据库中的冗余索引的T-SQL脚本?表中冗余索引的示例如下: Index 1: 'ColumnA','ColumnB','ColumnC'Index 2: 'ColumnA','ColumnB' 忽略其他注意事项,例如列的宽度和覆盖索引,索引2将是多余的. 谢谢. 解决方法 有些情况下冗余不成立.
是否有人知道可以检测整个数据库中的冗余索引的T-SQL脚本?表中冗余索引的示例如下:
Index 1: 'ColumnA','ColumnB','ColumnC'
Index 2: 'ColumnA','ColumnB'

忽略其他注意事项,例如列的宽度和覆盖索引,索引2将是多余的.

谢谢.

解决方法

有些情况下冗余不成立.例如,假设ColumnC是一个huuge字段,但有时您必须快速检索它.您的索引1不需要键查找:
select ColumnC from YourTable where ColumnnA = 12

另一方面,索引2要小得多,因此可以在内存中读取需要索引扫描的查询:

select * from YourTable where ColumnnA like '%hello%'

所以他们并不是多余的.

如果您不相信我的上述论点,您可以找到“冗余”索引,例如:

;with ind as (
    select  a.object_id,a.index_id,cast(col_list.list as varchar(max)) as list
    from    (
            select  distinct object_id,index_id
            from    sys.index_columns
            ) a
    cross apply
            (
            select  cast(column_id as varchar(16)) + ',' as [text()]
            from    sys.index_columns b
            where   a.object_id = b.object_id
                    and a.index_id = b.index_id
            for xml path(''),type
            ) col_list (list)
)
select  object_name(a.object_id) as TableName,asi.name as FatherIndex,bsi.name as RedundantIndex
from    ind a
join    sys.sysindexes asi
on      asi.id = a.object_id
        and asi.indid = a.index_id
join    ind b
on      a.object_id = b.object_id
        and a.object_id = b.object_id
        and len(a.list) > len(b.list)
        and left(a.list,LEN(b.list)) = b.list
join    sys.sysindexes bsi
on      bsi.id = b.object_id
        and bsi.indid = b.index_id

为您的用户带来蛋糕,以防性能“意外”降低:-)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读