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

前端之家收集整理的这篇文章主要介绍了sql-server – 用于查找冗余索引的T-SQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有人知道可以检测整个数据库中的冗余索引的T-sql脚本?表中冗余索引的示例如下:
  1. Index 1: 'ColumnA','ColumnB','ColumnC'
  2. Index 2: 'ColumnA','ColumnB'

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

谢谢.

解决方法

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

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

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

所以他们并不是多余的.

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

  1. ;with ind as (
  2. select a.object_id,a.index_id,cast(col_list.list as varchar(max)) as list
  3. from (
  4. select distinct object_id,index_id
  5. from sys.index_columns
  6. ) a
  7. cross apply
  8. (
  9. select cast(column_id as varchar(16)) + ',' as [text()]
  10. from sys.index_columns b
  11. where a.object_id = b.object_id
  12. and a.index_id = b.index_id
  13. for xml path(''),type
  14. ) col_list (list)
  15. )
  16. select object_name(a.object_id) as TableName,asi.name as FatherIndex,bsi.name as RedundantIndex
  17. from ind a
  18. join sys.sysindexes asi
  19. on asi.id = a.object_id
  20. and asi.indid = a.index_id
  21. join ind b
  22. on a.object_id = b.object_id
  23. and a.object_id = b.object_id
  24. and len(a.list) > len(b.list)
  25. and left(a.list,LEN(b.list)) = b.list
  26. join sys.sysindexes bsi
  27. on bsi.id = b.object_id
  28. and bsi.indid = b.index_id

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

猜你在找的MsSQL相关文章