在我们的SQL Server数据库中应该多久重建一次索引?
有一个普遍的共识是,一旦索引碎片超过5(有时是10%),你就应该重新组织(“碎片整理”)你的索引,当它超过30%时,你应该完全重建它们(至少这是我在很多地方听到的主张的数字)。
米歇尔·乌福德(又名"SQL Fool")有一个automated index defrag script,它使用那些精确的限制来决定何时重组或重建索引。
另请参阅Brad McGehee's tips on rebuild indexes,其中有一些关于如何处理索引重建的好想法和技巧。
我在这里使用这个脚本(不记得我是什么时候得到这个的--不管是谁:非常感谢!)非常有用的东西)来显示给定数据库中所有索引的索引碎片:
代码语言:javascript运行复制SELECT
t.NAME 'Table name',
i.NAME 'Index name',
ips.index_type_desc,
ips.alloc_unit_type_desc,
ips.index_depth,
ips.index_level,
ips.avg_fragmentation_in_percent,
ips.fragment_count,
ips.avg_fragment_size_in_pages,
ips.page_count,
ips.avg_page_space_used_in_percent,
ips.record_count,
ips.ghost_record_count,
ips.Version_ghost_record_count,
ips.min_record_size_in_bytes,
ips.max_record_size_in_bytes,
ips.avg_record_size_in_bytes,
ips.forwarded_record_count
FROM
sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'DETAILED') ips
INNER JOIN
sys.tables t ON ips.OBJECT_ID = t.Object_ID
INNER JOIN
sys.indexes i ON ips.index_id = i.index_id AND ips.OBJECT_ID = i.object_id
WHERE
AVG_FRAGMENTATION_IN_PERCENT > 0.0
ORDER BY
AVG_FRAGMENTATION_IN_PERCENT, fragment_count