记录两个工作中用到的存储过程

使用存储过程批量删除数据

按天删除目标表中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; --结束
/ --这个斜杠用处很大,比如好多条存储过程的话,可以写在后面一起执行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章