今天啟用資料壓縮功能後,資料庫空出了很大的空間,然後使用DBCC SHRINKFILE收縮資料庫,花費了很長的時間。相信很多使用SQL Server的朋友都遇到過這樣的問題,為什麼SQL Server收縮檔案這麼耗時?
從MSDN上看到“DBCC SHRINKFILE is single-threaded and may take a long time tocomplete”(http://msdn.microsoft.com/en-us/library/dd894051(v=sql.100).aspx)也就是說SQL
Server是單線程運行檔案收縮,即使你有多個CPU效能也不會有協助。
這裡我做了一個測試,開啟兩個Query同時運行ShrinkFile命令,第二個語句會報錯:
File ID 1 of database ID 17 cannot be shrunk as it is eitherbeing shrunk by another process or is empty.
DBCCexecution completed. If DBCC printed error messages, contact your systemadministrator.
檔案收縮的三個步驟(可以從sys.dm_exec_request command欄位看到)
Step |
Command |
Description |
1 |
DbccSpaceReclaim |
Clean up deferred allocations and purge empty extents preparing for data moves. |
2 |
DbccFilesCompact |
Moves pages beyond the target to before the target and truncate file as required. |
3 |
DbccLOBCompact |
Compacting the LOB data. |
SQL Server執行DBCC ShrinkFile以32個PAGE作為一個Transcation.當交易中被處理的PAGE移動到Targe空間後,這個Transcation被Commit然後開始一個新的Transcation。這樣可以避免長時間的Transcation導致記錄檔增長過大。當前Transcation被Rollback/cancel之後,Shrink操作只復原當前的交易(最多32個Page)。這樣如果在維護期間內不能夠完成一次Shrink操作,可以分成多批次完成,每次處理一部分。
從網上找到了一篇如何快速收縮資料庫檔案的文章:
http://www.sqlservercentral.com/articles/SHRINKFILE/71414/
How It Works: SQL Server 2005 DBCC Shrink* May Take Longer Than SQL Server 2000:http://blogs.msdn.com/b/psssql/archive/2008/03/28/how-it-works-sql-server-2005-dbcc-shrink-may-take-longer-than-sql-server-2000.aspx