欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL语句实现查询Index使用状况

程序员文章站 2023-01-03 15:47:42
select sch.name + '.' + t.name as [table name], i.name as[index name],...
select
   sch.name + '.' + t.name as [table name],
   i.name as[index name],
   i.type_desc, 
   isnull(user_updates,0) as [total writes],
   isnull(user_seeks +user_scans + user_lookups,0) as [total reads],
   s.last_user_seek,
   s.last_user_scan ,
   s.last_user_lookup,
   isnull(user_updates,0) - isnull((user_seeks+ user_scans +user_lookups),0)as [difference], 
   p.reserved_page_count * 8.0 / 1024 as spaceinmb
from sys.indexes as i with (nolock) 
   left outerjoin sys.dm_db_index_usage_statsas s   with (nolock) on s.object_id = i.object_id and i.index_id = s.index_id and s.database_id=db_id() and objectproperty(s.object_id,'isusertable') = 1 
   inner join    sys.tables             as t with (nolock) on i.object_id = t.object_id 
   inner join    sys.schemas             as sch   with (nolock) on t.schema_id = sch.schema_id 
   left outerjoin sys.dm_db_partition_stats as p with (nolock) on i.index_id = p.index_id and i.object_id = p.object_id
where (1=1)
   --and isnull(user_updates,0) >=isnull((user_seeks + user_scans + user_lookups),0) --shows all indexesincluding those that have not been used 
   --and isnull(user_updates,0) -isnull((user_seeks + user_scans + user_lookups),0)>0 --only shows thoseindexes which have been used 
   --and i.index_id > 1        -- only non-first indexes (i.e.non-primary key)
   --and i.is_primary_key<>1     -- only those that are not defined asa primary key)
   --and i.is_unique_constraint<>1-- only those that are not classed as "uniqueconstraints". 
order by [table name],[index name]