PL/SQL游标的使用

1.游标的使用语法
1).定义游标
declare
cursor 游标名 [(参数名 参数类型[,参数名 参数类型])] is select statement;
2)打开游标
if not cursor_name%isopen then
	open cursor_name;
end if;

3)使用游标读取数据
loop
	fetch cursor_name into variable;
	exit when cursor_name%notfound;
	--TODO task statements
end loop;

4)关闭游标
close cursor_name;
2.带参数的游标
    declare 
           cursor c_emp(dno number) is
                  select ename from emp where deptno=dno;
           v_name emp.ename%type;
    begin
           if not c_emp%isopen then
              open c_emp(20);
           end if;
           loop
               fetch c_emp into v_name;
               exit when c_emp%notfound;
               dbms_output.put_line(v_name);
           end loop;
    end;
3.游标属性
    isopen,游标当前打开状态;
    found,notfound,游标当前是否指向一条存在记录的数据;
    rowcount--游标影响的行数,并不是总行数。
4.隐式游标
    修改、删除操作时oracle会创建隐式游标,这些游标的定义、打开、关闭都市系统自动完成的,隐式游标名字为SQL;存放数据为与显式游标无关、最新处理一条SQL语句所包含的数据。
具体属性有:SQL%found;sql%notfound,sql%isopen;sql%rowcount;
5.游标数量限制
    Oracle游标数量:默认情况下同一个会话允许打开300个。
    查看与修改最大打开游标数:
    以sys用户登录-->
SQL> show parameter cursor;

NAME                                 TYPE        VALUE
------------------------------------ ----------- --------
cursor_sharing                       string      EXACT
cursor_space_for_time                boolean     FALSE
open_cursors                         integer     300
session_cached_cursors               integer     50
修改最大打开的游标数:
SQL> alter system set open_cursors=500 scope=both;
scope的取值可以是:both,memory(仅更改当前实例,不更改参数文件),spfile(数据库重启后即生效)。

猜你喜欢

转载自bjtale.iteye.com/blog/2229453