http://technet.microsoft.com/en-us/library/ms188388.aspxjavascript
本文主要讲解如何使用alter index来rebuild和reorganize索引来清除碎片,rebuild可以彻底清除碎片,可是reorganize却不能。java
--1.准备实验数据 select * into Employee from AdventureWorks2008R2.HumanResources.Employee; --2.查看使用空间:Employee 290 72 KB 56 KB 8 KB 8 KB sp_spaceused Employee --3.建立汇集索引 create clustered index IX_BusinessEntityID on Employee(BusinessEntityID); --4.查看使用空间:Employee 290 80 KB 56 KB 16 KB 8 KB sp_spaceused Employee --5.索引重建,清除fragment,并设定fillfactor为60 ALTER INDEX ALL ON Employee REBUILD WITH (FILLFACTOR = 60, SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = ON); --6.查看使用空间:Employee 290 144 KB 88 KB 16 KB 40 KB sp_spaceused Employee
结论node
ALTER INDEX ALL ON Employee REORGANIZE GO
Rebuilding an index drops and re-creates the index. This removes fragmentation, reclaims disk space by compacting the pages based on the specified or existing fill factor setting, and reorders the index rows in contiguous pages. When ALL is specified, all indexes on the table are dropped and rebuilt in a single transaction. sql
从新生成索引将会删除并从新建立索引。 这将根据指定的或现有的填充因子设置压缩页来删除碎片、回收磁盘空间,而后对连续页中的索引行从新排序。 若是指定 ALL,将删除表中的全部索引,而后在单个事务中从新生成。测试
Reorganizing an index uses minimal system resources. It defragments the leaf level of clustered and nonclustered indexes on tables and views by physically reordering the leaf-level pages to match the logical, left to right, order of the leaf nodes. Reorganizing also compacts the index pages. Compaction is based on the existing fill factor value.ui
从新组织索引使用最少系统资源从新组织索引。 经过对叶级页以物理方式从新排序,使之与叶节点的从左到右的逻辑顺序相匹配,进而对表和视图中的汇集索引和非汇集索引的叶级进行碎片整理。 从新组织还会压缩索引页。 压缩基于现有的填充因子值。this
Rebuilding an index can be executed online or offline. Reorganizing an index is always executed online. To achieve availability similar to the reorganize option, you should rebuild indexes online.spa
rebulid index既能够在online又能够在offline下执行,而reorganize index只能在online下执行的。code
既然rebuild index既能够是online模式,也能够是offline模式,那么二者有什么区别呢。这个咱们能够参考stackoverflow上面的一篇文章:What is the difference between OFFLINE and ONLINE index rebuild in SQL Server? 在这里我仍是简要总结一下:server
rebuild index会复制旧索引来新建索引,此时旧的索引依然能够被读取和修改,可是因此在旧索引上的修改都会同步更新到新索引下。中间会有一些冲突解决机制,具体参考Online Index Operations 里面的Build Phase这一章节。而后在rebuild这个过程完整的时候,会对table上锁一段时间,在这段时间里会用新索引来替换旧索引,当这个过程完成之后再释放table上面的锁。若是索引列包含 LOB对象的话,在SQL Server 2005/2008/R2中rebuild index online会失败。在sql server 2012中,即便索引列包含LOB对象,也能够rebuild index online了,能够参考 Online Index Operations for indexes containing LOB columns.
rebuilde index会对table上锁,全部对这个table的读写操做都会被阻塞,在这期间新索引根据旧索引来建立,其实就是一个复制的过程,可是新索引没有碎片,最后使用新索引替换旧索引。当rebuild整个过程完成之后,table上面的锁才会被释放。