查看当前数据库中没用的索引(sys.dm_db_index_usage_stats)

来源:互联网 发布:windows解压mac zip 编辑:程序博客网 时间:2024/05/14 01:43
 数据库经过一段时间的使用后,可能会沉积着一些建立后从没使用过的索引,继续维护这些索引就是浪费资源了,很有必要定期找出来分析处理。
SQL2005 有一个非常有用的管理视图:sys.dm_db_index_usage_stats,可以用它找出数据库中不被使用的索引。


---------------------------------------------------------------------------------------
为方便工作,写了一个通用存储过程:

create proc pChkidx
as

select tb_name=object_name(a.object_id)
,idx_name=b.name
,last_user_update
,c.colid,c.keyno
,col_name=d.name
into #tmp
from sys.dm_db_index_usage_stats a left join sys.indexes b on a.object_id=b.object_id and a.index_id=b.index_id
left join sys.sysindexkeys c on c.id=a.object_id and c.indid=a.index_id
left join syscolumns d on d.id=c.id and d.colid=c.colid
where database_id=db_id()
and last_user_seek is null
and last_user_scan is null
and last_user_lookup is null
and last_user_update is not null

order by tb_name,idx_name,keyno


select tb_name,idx_name,last_user_update
,keywords= stuff(
(select '+'+ col_name
FROM #tmp
where tb_name=a.tb_name and idx_name=a.idx_name
order by tb_name,idx_name,keyno
for xml path('') )
,1,1,'')
from #tmp a
group by tb_name,idx_name,last_user_update
原创粉丝点击