游标表达式:
用cursor操作符表示,返回的是一个嵌套在查询语句中游标。
语法: cursor (subquery子查询)
(Oracle9i后才能使用,不过用的很少,而且不够清晰简洁,尽量别使用)
使用场合:
1. 显示游标声明
2. 动态sql查询
3. Ref cursor声明和变量。
但是不能把游标表达式用于隐式查询。
二种使用方式:
1. 要把子查询作为外层查询的一列
2. 要把一个查询转换成一个结果集。
例子:如何用嵌套的游标表达式把一个子查询作为外层查询的一列。
好处:所有的处理都是在sql语句执行,减少了sql和PL/SQL引擎切换。
procedure emp_report(p_locid number)
is
type refcursor is ref cursor;
cursor all_in_one_cur is
select l.city,
cursor (
select d.department_name,
cursor(
select e.last_name from employees e
where e.department_id = d.department_id
) as ename
from departments d
where l.location_id = d.location_id
) as dname
from locations l
where l.location_id = p_locid;
departments_cur refcursor;
employees_cur refcursor;
v_city locations.city%type;
v_dname departments.department_name%type;
v_ename employees.last_name%type;
begin
open all_in_one_cur;
loop
fetch all_in_one_cur into v_city,departments_cur;
exit when all_in_one_cur%notfound;
loop
fetch employees_cur into v_ename;
exit when employees_cur%notfound;
dbms_output.put_line(
v_city||' '||v_dname||' '||v_ename
);
end loop;
end loop;
close all_in_one_cur;
end;