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上面的鎖纔會被釋放。