随笔 - 746  文章 - 0  评论 - 39  阅读 - 79万

Sqlserver 2005+:查看索引【index】的【使用情况】:无效的索引、高成本索引

复制代码
set nocount on
go

--无效索引排序
select top 20
    db_name() as db_name
    ,schema_name(o.schema_id) as schema_name
    ,o.name as object_name
    ,i.name as index_name,i.is_unique_constraint,(case i.index_id when 1 then 'is_clustered' else '' end) as is_clustered
    ,ir.rowcnt
    ,s.user_updates
    ,(s.user_lookups + s.user_scans + s.user_seeks) as [retrieval usage] --查询使用次数
    ,s.system_seeks + s.system_scans + s.system_lookups as [system usage]
    ,'DROP INDEX ' + quotename(o.name) + '.' + quotename(i.name) as [ -- dsql]
from sys.dm_db_index_usage_stats s
    inner join sys.indexes i on s.database_id=db_id() and s.[object_id] = i.[object_id] and s.index_id = i.index_id
    inner join sys.objects o on i.object_id = o.object_id
    inner join sysindexes ir on ir.id=i.object_id and ir.indid=i.index_id
where s.database_id = db_id()
    and o.is_ms_shipped = 0
    and i.name is not null
    --and s.user_seeks = 0
    --and s.user_scans = 0
    --and s.user_lookups = 0
    and (s.user_lookups + s.user_scans + s.user_seeks)=0
order by s.user_updates desc

go

-- 维护成本 排序
select top 20
    db_name() as db_name
    ,schema_name(o.schema_id) as schema_name
    ,o.name as object_name
    ,i.name as index_name,i.is_unique_constraint,(case i.index_id when 1 then 'is_clustered' else '' end) as is_clustered
    ,ir.rowcnt
    ,s.user_updates -- as [update usage] --更新成本
    ,(s.user_seeks + s.user_scans + s.user_lookups) as [retrieval usage] --查询使用次数
    ,(s.user_updates) - (s.user_seeks + user_scans + s.user_lookups) as [maintenance cost] --用户维护成本
    ,s.system_seeks + s.system_scans + s.system_lookups as [system usage] --系统内部维护次数,--内部维护成本
    ,s.last_user_seek
    ,s.last_user_scan
    ,s.last_user_lookup
    ,'DROP INDEX ' + quotename(o.name) + '.' + quotename(i.name) as [ -- dsql]
from sys.dm_db_index_usage_stats s
    inner join sys.indexes i on s.database_id=db_id() and s.[object_id] = i.[object_id] and s.index_id = i.index_id
    inner join sys.objects o on i.object_id = o.object_id
    inner join sysindexes ir on ir.id=i.object_id and ir.indid=i.index_id
where s.database_id = db_id()
    and o.is_ms_shipped = 0
    and i.name is not null
    and (s.user_seeks + s.user_scans + s.user_lookups) > 0
order by [maintenance cost] desc
复制代码
posted on   jinzhenshui  阅读(605)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)

点击右上角即可分享
微信分享提示