最近在研究《Microsoft SQL Server 2012 Internals》这本书,考虑到如何快速恢复误操作数据,如UPDATE、DELETE、TRUNCATE、DROP等操作。当数据库特别大的时候,通过还原数据库恢复误操作数据就会变得非常吃力。
那么如何在不restore database的情况下,快速进行数据恢复呢。这也将是本文将要提到的内容。
首先,简单了解下DROP TABLE操作的原理
1. 删除表的DDL
2. 删除数据页数据
通过分析Transaction Log可知,drop table并不会记录删除每一行数据的日志,drop table最终是通过标记该表数据页为可重写以表示释放空间,
当数据库空间不足时,SQL Server可对这部分空间进行数据写入。
因此,我们想要在不restore database情况下恢复数据,就得确保drop table后表的数据页没有被重写覆盖。一旦数据页被覆盖,那么只能通过restore database方式进行恢复。
以下为恢复表结构语句的实例
1. 建表
create table test_drop(col1 tinyint,col2 smallint,col3 int identity(1,1),col4 bigint,col5 varchar(20),col6 char(20),col7 nvarchar(20),col8 nchar(20),col9 datetime,col10 timestamp,col11 uniqueidentifier,col12 sysname,col13 numeric(10,2),col14 xml,col15 money,col16 text)
2. 删除表
drop table test_drop
3. 恢复被删除的表结构语句
exec Recover_Dropped_Table_DDL_Porc 'test_drop'
生成恢复语句如下:
if object_id('dbo.test_drop') is not null print 'dbo.test_drop is existed'create table dbo.test_drop(col1 tinyint null ,col2 smallint null ,col3 int identity ,col4 bigint null ,col5 varchar(20) collate SQL_Latin1_General_CP1_CI_AS null ,col6 char(20) collate SQL_Latin1_General_CP1_CI_AS null ,col7 nvarchar(20) collate SQL_Latin1_General_CP1_CI_AS null ,col8 nchar(20) collate SQL_Latin1_General_CP1_CI_AS null ,col9 datetime null ,col10 timestamp not null ,col11 uniqueidentifier null ,col12 sysname collate SQL_Latin1_General_CP1_CI_AS not null ,col13 numeric(10,2) null ,col14 xml null ,col15 money null ,col16 text collate SQL_Latin1_General_CP1_CI_AS null )