oracle的閃回查詢、閃回表、閃回資料庫(轉)
阿新 • • 發佈:2018-12-09
/* 一、 要使用閃回查詢,資料庫必須開啟automatic undo management,必須有undo表空間,必須設定好回滾段的保留時間 */ -- 在sqlplus中檢視undo_management引數值是否為AUTO,如果是“MANUAL”手動,需要修改為“AUTO”; -- 查看回滾段的保留時間undo_retention,預設900秒(15分鐘) show parameter undo -- 檢視所有的回滾段 select SEGMENT_ID ,SEGMENT_NAME from dba_rollback_segs; -- 指定事務使用某個回滾段,如果不人為的指定回滾段,則資料庫會根據回滾段中事務來權衡,以使得所有回滾段中事務壓力盡可能平均。 set transaction use rollback segment rbs6; -- 修改undo_management引數值為AUTO /* Oracle有個spfile動態引數檔案,裡面設定了Oracle的各種引數。所謂的動態,就是說你可以在不關閉資料庫的情況下,更改資料庫引數,記錄在spfile裡面。 更改引數的時候,有4種scope選項,scope就是範圍。 scope=spfile 僅僅更改spfile裡面的記載,不更改記憶體,也就是不立即生效,而是等下次資料庫啟動生效,有一些引數只允許用這種方法更改; scope=memory 僅僅更改記憶體,不改spfile,也就是下次啟動就失效了; scope=both 記憶體和spfile都更改; 不指定scope引數,等同於scope=both。 */ alter system set undo_management='AUTO' scope=spfile; -- 修改undo_retention為1小時 alter system set undo_retention=3600 scope=both; -- 檢視修改是否立即生效 show parameter undo select name,value from v$spparameter where name='undo_management'; -- 重啟資料庫,使修改生效 shutdown immediate startup show parameter undo /* 測試閃回查詢 */ select * from t1 where id<10; delete from t1 where id<10; commit; -- 查詢15分鐘之前的表資料 select * from t1 as of timestamp(sysdate - 15/1440) where id<10; -- 將資料恢復 insert into t1 select * from t1 as of timestamp(sysdate - 15/1440) where id<10; commit; /* 根據時間的閃回本質上是基於scn的閃回 */ -- 將dbms_flashback的執行許可權授權給scott使用者 grant execute on dbms_flashback to scott; -- 查詢當前的系統改變號scn,並記錄下來,2363533 select dbms_flashback.get_system_change_number from dual; -- 刪除資料 delete from t1 where id<10; commit; -- 根據刪除資料時間點前的scn來查詢刪除前的資料 select * from t1 as of scn(2363533) where id<10; -- 將資料恢復 insert into t1 select * from t1 as of scn(2363533) where id<10; commit; -- 使用ora_rowscn偽列來檢視與每一行關聯的scn select ora_rowscn,t1.* from t1 -- 檢視scn對映的事務提交時間 select scn_to_timestamp(2363533) from dual; -- 檢視每行資料的最新事務提交時間 select scn_to_timestamp(ora_rowscn), t1.* from t1; /* 二、閃回表 */ drop table t1; select * from t1; -- 刪除t1表後,該表的block還在表空間中,查詢回收站可以看到被刪除的物件 select * from recyclebin; -- 閃回表到刪除之前 flashback table t1 to before drop; /* 閃回表到某個時間點 */ update t1 set contents='abc'; commit; -- 必須啟用表的行移動功能 alter table t1 enable row movement; flashback table t1 to timestamp(systimestamp - 5/1440); /* 三、閃回資料庫 */ -- 需要有sysdba許可權,才能使用flashback database命令,必須以獨佔模式裝載資料庫,但不開啟資料庫。 -- 同時將資料庫置於閃回模式,執行閃回。 startup mount exclusive; alter database archivelog; alter database flashback on; alter database open; -- 檢視閃回模式是否開啟 select current_scn, flashback_on from v$database; shutdown; startup mount exclusive; -- 閃回資料庫到1小時之前 flashback database to timestamp sysdate-1/24; -- 閃回成功後,開啟資料庫,同時resetlogs開啟對資料庫的寫訪問許可權 alter database open resetlogs; startup mount exclusive; alter database flashback off; alter database open;