当使用游标for循环时,Oracle会隐含地打开游标,提取数据并关闭游标.
游标for循环的语法:
for record_name in cursor_name loop
statement;
end loop;
实例1:查询所有员工的员工号,姓名和职位信息.
declare
cursor emp_cursor is select empno,ename,job from emp;
begin
for emp_record in emp_cursor loop
dbms_output.put_line('员工号:' || emp_record.empno || ',姓名:' || emp_record.ename || ',职位:' || emp_record.job);
end loop;
end;
结果:
员工号:7369,姓名:SMITH,职位:CLERK
员工号:7499,姓名:ALLEN,职位:SALESMAN
员工号:7521,姓名:WARD,职位:SALESMAN
员工号:7566,姓名:JONES,职位:MANAGER
员工号:7654,姓名:MARTIN,职位:SALESMAN
员工号:7698,姓名:BLAKE,职位:MANAGER
员工号:7782,姓名:CLARK,职位:MANAGER
员工号:7788,姓名:SCOTT,职位:ANALYST
员工号:7839,姓名:KING,职位:PRESIDENT
员工号:7844,姓名:TURNER,职位:SALESMAN
员工号:7876,姓名:ADAMS,职位:CLERK
员工号:7900,姓名:JAMES,职位:CLERK
员工号:7902,姓名:FORD,职位:ANALYST
员工号:7934,姓名:MILLER,职位:CLERK
对于上面的sql语句,可以在游标for循环中直接引用子查询进行简化:
begin
for emp_record in (select empno,ename,job from emp) loop
dbms_output.put_line('员工号:' || emp_record.empno || ',姓名:' || emp_record.ename || ',职位:' || emp_record.job);
end loop;
end;
输出结果和上面一样.