如何使用 DBCC WritePage 才不会破坏你的数据
如何使用 DBCC WritePage 才不会破坏你的数据
http://www.sqlnotes.info/2013/05/14/protect-yourself-from-using-dbcc-writepage/
I blogged DBCC WritePage a year ago here http://www.sqlnotes.info/2011/11/23/dbcc-writepage/. It’s an extremely dangerous command especially with the last parameter “directORbufferpool” of this command turned on. I also showed you how to fix the page checksum here http://www.sqlnotes.info/2013/05/02/fix-page-checksum/. To protect yourself, please ensure you are operating on the database that you want, not system databases. Taking a full backup before playing this command is important. Never run it in your production. Beside that, there is a simple way to rollback changes made by DBCC WritePage…
When use DBCC Page to read the data. Data will come to the buffer pool first. When the page is not valid, wrong page checksum, conceptually, data will bypass the buffer pool and directly returned to the user.
When use DBCC WritePage to write the data. Data changes will be done in the buffer pool. Buffer pool will harden the changes to disk. What will happen if the file is read only logically? Will DBCC WritePage returns error? Let’s take a look
01
use master
02
if db_id('TestDB') is not null
03
drop database TestDB
04
go
05
create database TestDB
06
GO
07
create table TestDB.dbo.t1(Field1 char(10))
08
go
09
insert into TestDB.dbo.t1 values('AAAAAAAAAA')
10
go
11
select * from TestDB.dbo.t1
12
-- Field1
13
-- ----------
14
-- AAAAAAAAAA
15
go
16
---set the database to read only
17
alter database TestDB set read_only
18
go
19
delete TestDB.dbo.t1
20
--Msg 3906, Level 16, State 1, Line 1
21
--Failed to update database "TestDB" because the database is read-only.
22
go
23
dbcc traceon(3604)
24
dbcc ind(TestDB, t1, 1)
25
26
--PageFID PagePID PageType
27
--------- ----------- --------
28
--1 150 10
29
--1 147 1
30
go
31
dbcc page(TestDB, 1, 147,3)
32
dbcc writepage(TestDB, 1, 147,105, 3, 0x424344 )
33
select * from TestDB.dbo.t1 -- data get changed without any error
34
--Field1
35
------------
36
--AAAAABCDAA
37
go
38
-- this change is done in the memory.
39
-- Now let's change the database state
40
alter database TestDB set read_write
41
go
42
-- Check it again. all changes done by DBCC WritePage are "rolled back"
43
select * from TestDB.dbo.t1
44
--Field1
45
------------
46
--AAAAAAAAAA
Turn your database into read-only mode can protect you from being hurt by DBCC WritePage
John Huang – SQL MCM & MVP, http://www.sqlnotes.info