Adsense

Monday, January 7, 2013

Find Fragmented Indexes in SQL Server


Identifying the most fragmented indexes in a particular database can be found by running the below query.  Only indexes in the active database will be analyzed.  The results will be ordered by the most fragmented table being listed first.


declare @table_index table (table_name sysname, table_id int, index_name sysname, index_id int, fragmentation float, pagecount int)
declare @table_id as int
declare @index_id as int
declare @fragmentation float
declare @pagecount int

insert into @table_index (table_name, table_id, index_name, index_id)
select o.name as table_name, o.object_id as table_id, isnull(i.name, 'HEAP') as index_name, i.index_id
from sys.objects o
inner join sys.indexes i on o.object_id = i.object_id
where o.type = 'u'

declare curs cursor for
select table_id, index_id
from @table_index

open curs

fetch next from curs into @table_id, @index_id

while @@FETCH_STATUS = 0
begin
      select @fragmentation = avg_fragmentation_in_percent,
      @pagecount = page_count
      from sys.dm_db_index_physical_stats (DB_ID(), @table_id, @index_id,null,'limited')

      update @table_index
      set fragmentation = @fragmentation,
      pagecount = @pagecount
      where index_id = @index_id
      and table_id = @table_id

      fetch next from curs into @table_id, @index_id

end

close curs

deallocate curs

select *
from @table_index
order by fragmentation desc

No comments:

Post a Comment