Oracle利用Logmnr找回誤刪除資料

來源:互聯網
上載者:User

Logmnr在Oracle 9i以後做了眾多的改進,如可以不需要build flat文字檔就可以分析日誌了,也就表示可以不需要修改參數utl_file_dir就可以分析日誌了,避免了修改參數utl_file_dir導致的重起資料庫問題。另外也開始支援把字典資訊build到聯機日誌中,在異地分析歸檔日誌。

在flashback也不能幫上忙的時候,logmnr卻是非常有用的。因為只要誤操作時期的歸檔日誌存在,就可以通過歸檔日誌來恢複誤刪除(delete)的資料。

如果在Oracle 9i以上,採用在本地的線上資料字典分析歸檔日誌,就這麼簡單:

Piner@9iR2>exec -
           sys.dbms_logmnr.add_logfile(LogFileName=>'/archive_log/archive/1_9.arc',-
           options => dbms_logmnr.new);
PL/SQL procedure successfully completed.

Piner@9iR2>exec sys.dbms_logmnr.start_logmnr( -
           Options => sys.dbms_logmnr.dict_from_online_catalog);
PL/SQL procedure successfully completed.
可以看到,線上分析其實就只需要這兩步,添加日誌並分析日誌。注意以上OPTIONS => DBMS_LOGMNR.NEW,表示添加第一個日誌,如需要另外添加更多的日誌,可以用如下方式即可。

Piner@9iR2>exec sys.dbms_logmnr.add_logfile(LogFileName=>'/archive_log/archive/1_10.arc');
如果日誌分析完成,可以把需要的資訊儲存到暫存資料表,如

Piner@9iR2>create table tmp_logmnr as
     2  select operation,sql_redo,sql_undo from v$logmnr_contents
     3  where seg_name='TEST';
然後,終止日誌分析過程。

Piner@9iR2>exec sys.dbms_logmnr.end_logmnr
對於暫存資料表中的SQL_UNDO,可以選擇性的恢複,如採用如下的指令碼來恢複,這裡為了減少阻塞,每1000條提交一次。另外,需要注意的是,SQL_UNDO中的分號,如果想用動態SQL來執行的話,是需要去掉的。【LINUX公社 www.LinuxIDC.com 】

declare
  mysql varchar2(4000);
  num number :=0;
begin
  for c_tmp in (select sql_undo from tmp_logmnr where operation = 'DELETE') loop
  --去掉語句中的分號,這裡假定只有語句結尾有分號,語句中間並沒有分號。
  --如果語句中也有分號,則可以考慮替換語句結尾的;'(分號單引號)為'(單引號)。
    mysql := replace(c_tmp.sql_undo,';','');
    execute immediate mysql;
    num := num + 1;
    if mod(num,1000)=0 then
      commit;
    end if;
  end loop;
  commit;
exception
  when others then
   --異常處理
end;
/
以上的PL/SQL代碼其實還可以加強,如恢複成功一條,就設定狀態值為1,否則,設定狀態值為-1,方便跟蹤那些記錄恢複成功,哪些記錄恢複失敗了。

另外,需要注意的是,在Oracle 10g以下,LOGMNR的暫存資料表v$logmnr_contents,使用的是system資料表空間,在Oracle 10g以後改為sysaux資料表空間。可以使用如下的命令,更改logmnr的特定資料表空間,防止system資料表空間出現空間不夠。

Piner@9iR2>exec  sys.dbms_logmnr_d.set_tablespace('USERS');

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.