記錄兩個工作中用到的存儲過程

使用存儲過程批量刪除數據

按天刪除目標表中xxx_no重複的數據, 只保留最近的一條。

declare
  pragma autonomous_transaction;
  n_delete number := 0;
begin
  while 1 = 1 loop
    EXECUTE IMMEDIATE 'delete from xxx_log t where t.rowid not in (select max(rowid) from xxx_log t1 group by t1.xxx_no, to_char(create_time,''yyyy/MM/dd'')) and rownum <= :rn'
      USING 1000; --提交行數
    if SQL%NOTFOUND then
      exit;
    else
      n_delete := n_delete + SQL%ROWCOUNT;
    end if;
    commit;
  end loop;
  commit;
end;
/

使用存儲過程批量更新數據

將頭表中的創建時間同步更新到行表

declare
  --聲明兩個變量
  v_id          number;
  v_header_id   number;
  v_int         number;
  v_create_time timestamp(6);
  cursor yb is
    select a.id, a.header_id from xxx_lines a;
begin
  v_int := 1; --變量賦值
  open yb; --打開遊標
  loop
    --開始標記
    fetch yb
      into v_id, v_header_id; --遊標賦值  當然這邊可以賦值多個值
    exit when yb%notfound; --遊標一條一條地遍歷記錄,當找不到記錄時退出
    begin
      update xxx_lines
         set create_time =
             (select create_time
                from xxx_headers
               where id = v_header_id)
       where id = v_id;
    exception
      --異常拋出
      when others then
        dbms_output.put_line(v_id);
    end;
    v_int := v_int + 1;
    if (v_int >= 1000) then
      commit; --1000條提交一次 分擔系統壓力,提高上傳的效率
      v_int := 0;
    end if;
  end loop; --結束標記
  commit;
  close yb; --關閉遊標
end; --結束
/ --這個斜槓用處很大,比如好多條存儲過程的話,可以寫在後面一起執行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章