1. 程式人生 > 其它 >Oracle儲存過程中loop、for迴圈的用法

Oracle儲存過程中loop、for迴圈的用法

基表資料:

 建立儲存過程:

create or replace procedure PRO_LOOP_EMP is
       --宣告遊標
       v_emp emp%rowtype;
       --讓遊標變數c_emps指向一個動態select查詢的結果集
       cursor c_emps is select * from emp where rownum <= 10;
begin
  --開啟遊標變數c_emps
  open c_emps;
       --迴圈開始
       loop
         --需要顯式宣告遊標,顯式開啟、關閉遊標
fetch c_emps into v_emp; exit when c_emps%notfound; if v_emp.ENAME = 'SMITH' then dbms_output.put_line('史密斯' || ' - ' || v_emp.JOB); elsif v_emp.ENAME = 'CLARK' then dbms_output.put_line('克拉克' || ' - ' || v_emp.JOB);
else dbms_output.put_line(v_emp.ENAME || ' - ' || v_emp.JOB); end if; --迴圈結束 end loop; --關閉遊標變數c_emps close c_emps; end PRO_LOOP_EMP;
create or replace procedure PRO_FOR_EMP is
       --讓遊標變數c_emps指向一個動態select查詢的結果集
       cursor c_emps is select * from
emp where rownum <= 10; begin --迴圈開始 for e in c_emps loop if e.ENAME = 'JACK' then dbms_output.put_line('傑克' || ' - ' || e.JOB); elsif e.ENAME = 'CLARK' then dbms_output.put_line('克拉克' || ' - ' || e.JOB); else dbms_output.put_line(e.ENAME || ' - ' || e.JOB); end if; --迴圈結束 end loop; end PRO_FOR_EMP;

呼叫儲存過程:

begin
  pro_loop_emp;
end;
begin
  PRO_FOR_EMP;
end;