PLSQL總結——15.DML事務

/*
create table EMPLOYEE
(
  employee_number NUMBER,
  employee_name   VARCHAR2(30),
  salary          NUMBER(7,2),
  department_id   NUMBER
)
*/
declare
  /*顯示錶記錄*/
  procedure show_rec is
    cursor c1 is
      select * from employee;
  begin
    for rec in c1
    loop
      /*假如第一條,輸出頭*/
      if c1%rowcount = 1
      then
        dbms_output.put_line('--------------------------------------------------');
        dbms_output.put_line('employee_number|employee_name|salary|department_id');
      end if;
      dbms_output.put_line(rpad(rec.employee_number, 15, ' ') || '|' ||
                           rpad(rec.employee_name, 13, ' ') || '|' ||
                           rpad(rec.salary, 6, ' ') || '|' ||
                           rpad(rec.department_id, 13, ' '));
    end loop;
    dbms_output.put_line('--------------------------------------------------');
  end show_rec;

begin

  dbms_output.put_line('before update record...');
  show_rec; --顯示錶記錄

  /*插入多條記錄,複製多一倍數據*/
  insert into employee
    select * from employee;

  savepoint a; --保存點

  /*刪除表的重複記錄*/
  delete employee
   where rowid not in
         (select max(rowid)
            from employee
           group by employee_number, employee_name, salary, department_id);

  dbms_output.put_line('delete count : ' || sql%rowcount);
  dbms_output.put_line('');

  /*更新表,讓工資變爲1000*/
  <<update_block>>
  declare
    employee_rec employee%rowtype;
    update_row   pls_integer := 0;
    cursor c1 is
      select * from employee for update;
  begin
    for rec in c1
    loop
      employee_rec        := rec;
      employee_rec.salary := 1000;
      update employee set row = employee_rec where current of c1;
      update_row := update_row + sql%rowcount;
    end loop;
    dbms_output.put_line(update_row || ' records were updated!');
    dbms_output.put_line('');
  end update_block;

  commit;

  dbms_output.put_line('after update record...');

  show_rec; --顯示錶記錄
exception
  when others then
    rollback to a; --返回保存點a
end;

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