当SQLServer的数据积累到一定的数量,查询效率往往急剧下降,常常让人无法忍受,DBREINDEX经常用到,它可以帮助我们重建指定表的索引,以提高查询的速度。使用下面语句可以检索出碎片:
select o.name AS TableName,i.name AS IndexName,ips.index_type_desc, ips.avg_fragmentation_in_percent,ips.page_count,ips.fragment_count, ips.avg_page_space_used_in_percent from sys.dm_db_index_physical_stats(null,null,null,null,'Sampled') ips JOIN sys.objects o ON ips.object_id = o.object_id JOIN sys.indexes i ON (ips.object_id = i.object_id) AND (ips.index_id = i.index_id) WHERE (ips.page_count >= 7) AND (ips.avg_fragmentation_in_percent > 20) ORDER BY o.name,i.name
再使用下面语句重建索引:
DECLARE @tablename varchar(100) DECLARE authors_cursor CURSOR FOR SELECT DISTINCT o.name AS tablename from sys.dm_db_index_physical_stats(null,null,null,null,'Sampled') ips JOIN sys.objects o ON ips.object_id = o.object_id JOIN sys.indexes i ON (ips.object_id = i.object_id) AND (ips.index_id = i.index_id) WHERE (ips.page_count >= 7) AND (ips.avg_fragmentation_in_percent > 20) OPEN authors_cursor FETCH NEXT FROM authors_cursor INTO @tablename WHILE @@FETCH_STATUS = 0 BEGIN DBCC DBREINDEX (@tablename, '', 90) PRINT @tablename FETCH NEXT FROM authors_cursor INTO @tablename END close authors_cursor deallocate authors_cursor