본문 바로가기

Database/PLSQL

076 - [Oracle PL/SQL] Bulk collect & cursor

  • 각 단계별 차이점 비교한 샘플 코드
--------without bulk-------------
declare
    type emp_t is table of employees%rowtype;
    emp_table emp_t;
    cursor emp_c is select * from employees;
    c number:=0;
begin
    emp_table:=emp_t();

    open emp_c;
    loop
        emp_table.extend;
        c:=c+1;
        fetch emp_c into emp_table(c);
        exit when emp_c%notfound;
        dbms_output.put_line(emp_table(c).first_name);
    end loop;
    close emp_c;
end;
--------------------------------
Donald
Douglas
Jennifer
Michael
....

-----------with bulk collect-----------
declare
    type emp_t is table of employees%rowtype;
    emp_table emp_t;
    cursor emp_c is select * from employees;
begin
    open emp_c;
    fetch emp_c bulk collect into emp_table;
    -- 패치 이후에 close 할 필요가 없음.

    for i in emp_table.first..emp_table.last
    loop
        dbms_output.put_line(emp_table(i).first_name);
    end loop;

end;
------------------------------------
Donald
Douglas
Jennifer
Michael
....



---------with bulk and limit------------------
declare
    type emp_t is table of employees%rowtype;
    emp_table emp_t;
    cursor emp_c is select * from employees;
begin
    open emp_c;
    fetch emp_c bulk collect into emp_table limit 5;

    for i in emp_table.first..emp_table.last
    loop
        dbms_output.put_line(emp_table(i).first_name);
    end loop;

end;
----------------------------
Donald
Douglas
Jennifer
Michael
Pat