[ORACLE] PL/SQL - 명시적 커서

privatekim·2024년 7월 14일
0

ORACLE

목록 보기
38/38

EXPLICT CURSOR(명시적 커서)

여러개의 행을 FETCH해야 할 경우 명시적 커서 사용

  • 명시적 커서는 프로그래머가 관리한다.
  1. 커서 선언 : 이름있는 SQL영역(메모리) 선언
  2. 커서 OPEN : 메모리 영역을 할당하고 해당 공간에서 (PARSE/BIND/EXECUTE)를 실행하고 ACTIVE SET을 생성한다.
  3. FETCH : ACTIVE SET을 변수에 로드한다.
  4. 커서 CLOSE : 메모리 해제
  • 커서 속성 : %notfound, %isopen, %rowcount(fetch한 건수 return)

메뉴얼 한 커서 사용법

declare
    CURSOR cur is -- 선언
        select e.last_name name, e.salary salary, d.department_name dept_name
        from hr.employees e, hr.departments d
        where e.department_id = 20 and
            d.department_id = 20;  -- 커서 생성
    res cur%rowtype; -- 커서 결과 담을 변수
begin
    if not cur%isopen then -- open
        open cur;
    end if;
    
    loop -- fetch
        fetch cur into res; -- 커서 한 행 fetch
        exit when cur%notfound; -- 탈출 조건
        dbms_output.put_line(res.name);
        dbms_output.put_line(res.salary);
        dbms_output.put_line(res.dept_name);
        dbms_output.put_line(cur%rowcount); -- 1 / 2
        dbms_output.put_line('--------');
    end loop;
    
    if cur%isopen then -- close
        close cur;
    end if;
end;
/ 

커서 축약

declare
    CURSOR cur is
        select e.last_name name, e.salary salary, d.department_name dept_name
        from hr.employees e, hr.departments d
        where e.department_id = 20 and
            d.department_id = 20; 
begin
    for res in cur loop -- 알아서 open fetch close 다함.
    -- 여기서 res는 레코드 변수임. cur는 명시적 커서 이름임.
        dbms_output.put_line(res.name);
        dbms_output.put_line(res.salary);
        dbms_output.put_line(res.dept_name);
        dbms_output.put_line('--------');
    end loop;
        
end;
/

또는

begin
    for res in (select e.last_name name, e.salary salary, e.job_id job, d.department_name dept_name
                from hr.employees e, hr.departments d
                where e.department_id = 20 and
                d.department_id = 20) loop 
        dbms_output.put_line(res.name);
        dbms_output.put_line(res.salary);
        dbms_output.put_line(res.job);
        dbms_output.put_line(res.dept_name);
        dbms_output.put_line('--------');
    end loop;        
end;
/

for 문에 select를 넣어 사용할 수 있다.

0개의 댓글