例子:
--利用游标式的FOR循环依次检索EMP表中信息。
declare
-- Local variables here
i integer;
cursor emp_cursor is
select ename,deptno from emp;
begin
-- Test statements here
for emp_record in emp_cursor loop
--隐式地打开游标并对游标进行提取
if emp_record.deptno=30 then
dbms_output.put_line('ename is '||emp_record.ename);
end if;
end loop;
end;
--在游标式的FOR循环中,可以直接使用SELECT语句,而不需要预先定义一个游标。
declare
-- Local variables here
i integer;
begin
-- Test statements here
for emp_record in (select ename,deptno from emp) loop
if emp_record.deptno=30 then
dbms_output.put_line('ename is '||emp_record.ename);
end if;
end loop;
end;
参数化的游标
游标参数可以在查询中常量出现的任何位置上出现,可以在OPEN语句或游标FOR循环中提供参数值。
在游标处于打开状态时,执行查询语句,可将参数的值传递给游标。那么,在一个块中多次打开和关闭游标,每次返回不同的活动集。
在游标声明部分的形参必须与OPEN语句中的实参相对应。参数的数据类型与标量变量的数据类型相同,只是不需为参数指定大小。
语法:CURSOR cursor_name[(parameter_name datatype,...)]
IS select_statement;
例子:
--使用参数游标,按输入参数依次输出雇员的信息。
declare
-- Local variables here
i integer;
v_empno emp.empno%type;
v_ename emp.ename%type;
cursor emp_cursor(p_deptno number,p_job varchar2) is
select empno,ename from emp where deptno=p_deptno and job=P_job;
begin
-- Test statements here
open emp_cursor(30,'SALESMAN');
loop
fetch emp_cursor into v_empno,v_ename;
exit when emp_cursor%notfound OR emp_cursor%notfound is null;
dbms_output.put_line('empno is '||v_empno||' and ename is '||v_ename);
end loop;
close emp_cursor;
end;