1. 程式人生 > >Oracle 儲存過程中自定義異常

Oracle 儲存過程中自定義異常

參考:

1.進入pl/sql測試視窗

這裡寫圖片描述

2.執行語句

declare
  empname varchar2(255);
  customize_exp EXCEPTION; --自定義異常
begin
  FOR c IN (select d.* from scott.dept d) LOOP
    begin
      dbms_output.put_line('dept: ' || c.deptno || '=' || c.dname);

      --當部門ID為40時丟擲異常
      if (c.deptno = 40) then
        RAISE customize_exp; -- 丟擲自定義異常      
end if; --當部門ID為10、20、30時,會執行下面的查詢,由於出現多行所以會報 Too many rows round! --當部門ID為40時,這裡不再執行,控制轉向 select e.ename into empname from scott.emp e where e.deptno = c.deptno; exception when customize_exp then dbms_output.put_line('customize error!'); when no_data_found then
dbms_output.put_line('Data is not found!'); when too_many_rows then dbms_output.put_line('Too many rows round!'); when OTHERS then dbms_output.put_line('others error'); end; END LOOP; end;

3.結果

這裡寫圖片描述

4. IF巢狀

** 注意是 elsif 不是 else if

declare
  empname varchar2(255
); begin FOR c IN (select d.* from scott.dept d) LOOP begin dbms_output.put_line('dept: ' || c.deptno || '=' || c.dname); if c.deptno = 10 then dbms_output.put_line('deptno= ' || c.deptno); select e.ename into empname from scott.emp e where e.empno = 7782; if empname = 'CLARK' then dbms_output.put_line('ename= ' || empname); elsif empname = 'KING' then dbms_output.put_line('ename= ' || empname); end if; end if; exception when no_data_found then dbms_output.put_line('Data is not found!'); when too_many_rows then dbms_output.put_line('Too many rows round!'); when OTHERS then dbms_output.put_line('others error'); end; END LOOP; exception when OTHERS then dbms_output.put_line('others error'); end;
  1. 並列for迴圈與區域性變數
declare
  empname varchar2(255);
begin
  FOR c IN (select d.* from scott.dept d) LOOP
    begin

      dbms_output.put_line('dept: ' || c.deptno || '=' || c.dname);

    exception
      when no_data_found then
        dbms_output.put_line('Data is not found!');
      when too_many_rows then
        dbms_output.put_line('Too many rows round!');
      when OTHERS then
        dbms_output.put_line('others error');
    end;

  END LOOP;

  FOR c IN (select e.* from scott.emp e) LOOP
    --區域性變數
    declare
      v_ename varchar2(255);
    begin
      v_ename := c.ename;
      dbms_output.put_line('emp: ' || v_ename);

    exception
      when no_data_found then
        dbms_output.put_line('Data is not found!');
      when too_many_rows then
        dbms_output.put_line('Too many rows round!');
      when OTHERS then
        dbms_output.put_line('others error');
    end;

  END LOOP;
exception
  when OTHERS then
    dbms_output.put_line('others error');
end;