create or replace PROCEDURE PROC_STU3 AS BEGIN --显示游标使用,使用for循环 declare --定义游标,名称为cur_stu cursor cur_stu is select stuno,stuname from student order by stuno; begin for stu in cur_stu loop dbms_output.PUT_LINE(stu.stuno||'->'||stu.stuname); --循环做隐含检查 %notfound end loop; --自动关闭游标 end; END PROC_STU3; proc_1: create or replace procedure proc_1 as BEGIN DECLARE emp_id employees.employee_id%type; CURSOR cur IS SELECT b.employee_id, b.ROWID ROW_ID FROM employees b ORDER BY b.ROWID; BEGIN FOR row IN cur LOOP DBMS_OUTPUT.PUT_LINE('last name: '||row.employee_id||'--'||row.ROW_ID); END LOOP; END; end proc_1; proc_2: create or replace procedure proc_2 as BEGIN declare cursor emp_cursor is select ename,sal from emp where deptno=10;--定义游标,指定游标所对应的 v_ename emp.ename%type; ---定义接收游标数据的变量 v_sal emp.sal%type; ---定义接收游标数据的变量 begin open emp_cursor; ----打开游标 loop ---取多条数据,循环题 fetch emp_cursor into v_ename,v_sal; ----提取数据 exit when emp_cursor%notfound; -----当没去取到数据的时候退出 dbms_output.put_line(v_ename||': '||v_sal); end loop; ----退出 close emp_cursor; ----关闭 end; end proc_2; 那么不关闭游标有什么影响呢? 按oracle文档的要求和编写数据库代码的好的习惯, 绝对要对一个已经用完的游标关闭掉, 如果不想写这些语句你可以用for loop游标的方法! 用完就得关闭,否则就会占用资源。 SESSION关闭的时候游标会自动释放。 循环外关闭cursor: create or replace procedure proc_100 as BEGIN declare cursor emp_cursor is select ename,sal from emp where deptno=10; v_ename emp.ename%type; v_sal emp.sal%type; begin open emp_cursor; loop fetch emp_cursor into v_ename,v_sal; exit when emp_cursor%notfound; dbms_output.put_line(v_ename||': '||v_sal); close emp_cursor; end loop; close emp_cursor; end; end proc_100; 可以 SQL> create or replace procedure proc_100 as BEGIN declare cursor emp_cursor is select ename,sal from emp where deptno=10; v_ename emp.ename%type; v_sal emp.sal%type; begin open emp_cursor; loop fetch emp_cursor into v_ename,v_sal; exit when emp_cursor%notfound; dbms_output.put_line(v_ename||': '||v_sal); close emp_cursor; end loop; close emp_cursor; end; close emp_cursor; end proc_100; 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 / Warning: Procedure created with compilation errors. SQL> show err Errors for PROCEDURE PROC_100: LINE/COL ERROR -------- ----------------------------------------------------------------- 17/5 PL/SQL: SQL Statement ignored 17/11 PLS-00201: identifier 'EMP_CURSOR' must be declared 报错 关闭游标有,必须重新定义