以前使用过网上下载的脚本查询没有使用过的Index比如SQL SERVER – 2008 – Unused Index Script – Download,其实现在看起来这个脚本是有一些问题。
脚本如下:
-- UnusedIndex Script
-- Original Author:Pinal Dave (C) 2011
SELECTTOP 25
o.name AS ObjectName
, i.name AS IndexName
, i.index_id AS IndexID
, dm_ius.user_seeks AS UserSeek
, dm_ius.user_scans AS UserScans
, dm_ius.user_lookups AS UserLookups
, dm_ius.user_updates AS UserUpdates
, p.TableRows
,'DROP INDEX '+QUOTENAME(i.name)
+' ON '+QUOTENAME(s.name)+'.'+QUOTENAME(OBJECT_NAME(dm_ius.OBJECT_ID))AS'drop statement'
FROM sys.dm_db_index_usage_statsdm_ius
INNER JOINsys.indexes i ON i.index_id = dm_ius.index_id AND dm_ius.OBJECT_ID= i.OBJECT_ID
INNER JOINsys.objects o ON dm_ius.OBJECT_ID= o.OBJECT_ID
INNER JOINsys.schemas s ON o.schema_id= s.schema_id
INNER JOIN(SELECTSUM(p.rows) TableRows, p.index_id, p.OBJECT_ID
FROM sys.partitions p GROUPBY p.index_id, p.OBJECT_ID) p
ON p.index_id = dm_ius.index_id AND dm_ius.OBJECT_ID= p.OBJECT_ID
WHEREOBJECTPROPERTY(dm_ius.OBJECT_ID,'IsUserTable')= 1
AND dm_ius.database_id =DB_ID()
AND i.type_desc ='nonclustered'
AND i.is_primary_key = 0
AND i.is_unique_constraint = 0
ORDERBY (dm_ius.user_seeks + dm_ius.user_scans + dm_ius.user_lookups)ASC
GO
本脚本通过查询sys.dm_db_index_usage_stats获得索引的使用情况。但是如果索引没有被使用是不会出现在sys.dm_db_index_usage_stats中的。只有索引被第一次被使用才会在sys.dm_db_index_usage_stats中插入一条记录,之后索引被访问的信息会累积更新到这张表里。如果使用INNSER JOIN连接就忽略掉了这部分的数据。
当然索引被创建一次都没有使用的情况会非常少。