SQLServer無需Restore恢復誤刪表(一):恢復表結構

最近在研究《Microsoft SQL Server 2012 Internals》這本書,考慮到如何快速恢復誤操作數據,如UPDATE、DELETE、TRUNCATE、DROP等操作。當數據庫特別大的時候,通過還原數據庫恢復誤操作數據就會變得非常吃力。

那麼如何在不restore database的情況下,快速進行數據恢復呢。這也將是本文將要提到的內容。


首先,簡單瞭解下DROP TABLE操作的原理

1. 刪除表的DDL

2. 刪除數據頁數據


通過分析Transaction Log可知,drop table並不會記錄刪除每一行數據的日誌,drop table最終是通過標記該表數據頁爲可重寫以表示釋放空間(當空間不夠時,會format掉這些數據頁),

當數據庫空間不足時,SQL Server可對這部分空間進行數據寫入。


因此,我們想要在不restore database情況下恢復數據,就得確保drop table後表的數據頁沒有被format。一旦數據頁被format,那麼只能通過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'

blob.png


生成恢復語句如下:

if object_id('dbo.test_drop') is not null
    print  'dbo.test_drop is existed'
else
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 
)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章