重建索引是为了减少数据碎片。数据碎片会导致 SQL Server 进行不必要的数据读,降低 SQL Server 的性能。重建索引也会同时更新列统计,而如果查询所使用的列缺少或遗漏统计信息,这可能导致 SQL Server 内部的优化器选择比预期效率低的查询计划。
如果您重建了某张表上的聚集索引,该表上的非聚集索引也同时会被更新。
要更新索引,您可以使用 Maintenance Wizard (相关内容您可以参考 http://msdn.microsoft.com/en-us/library/ms180074.aspx ),或在 SQL Server 代理( Agent )中运行如下的自定义代码来更新某个数据库中所有表上的索引:
USE DatabaseName --Enter the name of the database you want to reindex
DECLARE @TableName varchar ( 255)
DECLARE TableCursor CURSOR FOR
SELECT table_name FROM information_schema . tables
WHERE table_type = 'base table'
OPEN TableCursor
FETCH