여러개의 행을 FETCH해야 할 경우 명시적 커서 사용
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를 넣어 사용할 수 있다.