误区 #14.清除日志后会将相关的LSN填零初始化
错误
当日志文件在手动增长,自动增长和创建时都会进行填零初始化操作。但是请不要把这个过程和定期清除日志的过程搞混。日志截断仅仅意味着将一个或多个VLF标记为不活动以便被重复使用。在日志清除的过程中,并没有任何日志被清除或是填0。“清除日志”和”截断日志”意思是一样的,但都属于用词不当,因为在这个过程中日志的大小不会有任何改变。
你可以在我的博客中看到有关日志文件填零初始化的博文:Search Engine Q&A #24: Why can't the transaction log use instant initialization?。以及我发布在TechNet杂志的文章:Understanding Logging and Recovery in SQL Server。
你可以通过跟踪标记3004来查看SQL Server对日志文件进行填零初始化的过程。将这个追踪标记打开当日志文件增长时,你就可以在SQL Server日志中看到相关信息,下面是测试代码:
复制代码 代码如下:
DBCC TRACEON (3004, 3605);
GO
-- Create database and put in SIMPLE recovery model so the log will clear on checkpoint
CREATE DATABASE LogClearTest ON PRIMARY (
NAME = 'LogClearTest_data',
FILENAME = N'D:\SQLskills\LogClearTest_data.mdf')
LOG ON (
NAME = 'LogClearTest_log',
FILENAME = N'D:\SQLskills\LogClearTest_log.ldf',
SIZE = 20MB);
GO
-- Error log mark 1
ALTER DATABASE LogClearTest SET RECOVERY SIMPLE;
GO
USE LogClearTest;
GO
-- Create table and fill with 10MB - so 10MB in the log
CREATE TABLE t1 (c1 INT IDENTITY, c2 CHAR (8000) DEFAULT 'a');
GO
INSERT INTO t1 DEFAULT VALUES;
GO 1280
-- Clear the log
CHECKPOINT;
GO
-- Error log mark 2
ALTER DATABASE LogClearTest SET RECOVERY SIMPLE;
GO
相应的,在日志中你可以看到:
复制代码 代码如下:
2010-04-13 13:20:27.55 spid53 DBCC TRACEON 3004, server process ID (SPID) 53. This is an informational message only; no user action is required.
2010-04-13 13:20:27.55 spid53 DBCC TRACEON 3605, server process ID (SPID) 53. This is an informational message only; no user action is required.
2010-04-13 13:20:27.63 spid53 Zeroing D:\SQLskills\LogClearTest_log.ldf from page 0 to 2560 (0x0 to 0x1400000)
2010-04-13 13:20:28.01 spid53 Zeroing completed on D:\SQLskills\LogClearTest_log.ldf
2010-04-13 13:20:28.11 spid53 Starting up database 'LogClearTest'.
2010-04-13 13:20:28.12 spid53 FixupLogTail() zeroing D:\SQLskills\LogClearTest_log.ldf from 0x5000 to 0x6000.
2010-04-13 13:20:28.12 spid53 Zeroing D:\SQLskills\LogClearTest_log.ldf from page 3 to 63 (0x6000 to 0x7e000)
2010-04-13 13:20:28.14 spid53 Zeroing completed on D:\SQLskills\LogClearTest_log.ldf
2010-04-13 13:20:28.16 spid53 Setting database option RECOVERY to SIMPLE for database LogClearTest.
2010-04-13 13:20:29.49 spid53 Setting database option RECOVERY to SIMPLE for database LogClearTest.
上面测试代码中ALTER DATABASE是作为日志中这部分的开始和结束标记。在两个Alter Database命令中的CheckPoint并不会引起填0操作。如果你需要进一步验证这点,在Checkpoint之前和之后分别使用DBCC SQLPERF (LOGSPACE)来查看日志文件的大小,你会发现虽然日志文件大小没有变,但是日志的使用空间百分比会大大减少。
(下图是译者测试的结果):