现在的位置: 首页 > 综合 > 正文

DBCC SHRINKFILE 为什么会运行很长时间?

2013年08月27日 ⁄ 综合 ⁄ 共 1304字 ⁄ 字号 评论关闭

今天启用数据压缩功能后,数据库空出了很大的空间,然后使用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

 

 

抱歉!评论已关闭.