---
title: "oracle PL/SQL之隐式游标和ref游标总结"
author: "hecal"
date: "2008-05-29T18:23:00Z"
tags: []
slug: "oracle-pl-sql-ref"
draft: false
lastmod: "2011-12-07T18:09:54Z"
id: 1296518
url: "https://hecal.iteye.com/blog/1296518"
---

游标是构建在PL/SQL中，用来查询数据，获取记录集的指针。它让开发者 一次访问结果集中一行记录。 在oracle中提供了两种游标： 1 静态游标 2 ref游标 静态游标：静态游标是在编译的时候就被确定。然后把结果集复制到内存中 静态游标又分为两种：隐式游标和显示游标。 ref游标：ref游标是在运行的时候加载结果集 先来看看静态游标中的隐式游标 在PL/SQL中为所有的SQL数据操纵语句（包括返回一行的select）隐式声明游标 称为隐式游标。主要原因是用户不能直接命名和控制此类游标。当用户在PL/SQL 中使用数据操纵语句（DML）时，oracle预先定义一个名称为SQL的隐式游标，通过 检查隐式游标的属性获取与最近执行的SQL语句相关信息。 在执行DML语句之后，隐式游标属性返回信息。隐式游标属性包括： %found %notfound %rowcount %isopen 1 %found 只有DML语句影响一行或多行时，%found属性才返回true declare num number; begin update emp set empno=123 where empno=111; if sql%found then dbms\_output.put\_line('存在记录'); else dbms\_output.put\_line('不存在记录'); end if; end; 2 %notfound %notfound属性作用正好跟%found属性相反。如果DML语句没有影响任何行数 ，则%notfound属性返回true. declare begin delete from emp where empno=111; if sql%notfound then dbms\_output.put\_line('删除失败'); end if; end; 3 %rowcount %rowcount属性返回DML语句影响的行数。如果DML语句没有影响任何行数 ，则%rowcount属性将返回0。 declare num number; begin update emp set empno=123 where empno=111; if sql%rowcount=0 then dbms\_output.put\_line('不存在记录'); else dbms\_output.put\_line('存在记录'); end if; end; 4 %isopen %isopen属性判断SQL游标是否已经打开。在执行SQL语句之后，oracle自动关闭SQL 游标，所以隐式游标的%isopen属性始终为false. 在PL/SQL中向标准的select语句增加单独的into子句，就可以将从表或视图中查询 记录赋予变量或行变量。需要注意的是select ..into 语句结果必须有且只能有一行。 如果查询没有返回行，PL/SQL将抛出no\_data\_found异常。如果查询返回多行，则抛出 too\_many\_rows 异常。如果抛出异常，则停止执行，控制权转移到异常处理部分（没有 异常处理，则程序中断）。在引发异常时，将不使用属性%found,%notfound,%rowcount来查明DML语句是否 已影响了行数。 declare num number; begin select empno into num from emp where empno=111; if sql%rowcount=0 or sql%notfound then dbms\_output.put\_line('不存在记录'); else dbms\_output.put\_line('存在记录'); end if; end; --------------------------------------------- 显示游标 显示游标是由用户显示声明的游标。根据在游标中定义的查询，查询返回的行集合可以 包含零行或多行，这些行称为活动集。游标将指向活动集中的当前行。 显示游标的操作过程。使用显示游标的4个步骤： （1）声明游标 （2）打开游标 （3）从游标中获取结果集 （4）关闭游标 cursor cursor\_name \[(parameter\[,parameter])] \[return return\_type] is select\_statement; cursor\_name 指游标的名称。 parameter为游标指定输入参数。 return\_type 定义游标提取行的行类型。 select\_statement 为游标定义查询语句。 open 游标名称 fetch 从游标中提取行 close 关闭游标 1 打开游标，执行游标中定义的查询语句，绑定输入参数，将游标指针指 向结果集的BOF位置。 open cursor\_name \[parameters] 2fetch 在打开游标之后，可以从游标中提取记录 fetch cursor\_name into variable\_name; fetch 是提取结果集中一行记录存储在变量中。每次提取之后，结果集指针 就向前移动一行。 3 close 在处理游标中的所有行之后，必须关闭游标，以释放分配给游标的所有资源。 close cursor\_name 用户可以通过检查游标属性来确定游标的当前状态。显示游标的属性如下： %found：如果执行最后一条fetch语句，成功返回行，则%found属性为true。 %notfound：如果执行最后一条fetch语句，未能提取行，则%notfound属性为true。 %isopen:如果游标已经打开，则返回true，否则返回false。 %rowcount：返回到目前为止游标提取的行数。%rowcount为数字类型属性。在第一 次获取之前,%rowcount为零。当fetch语句返回一行时，则该数加1。 declare info emp%rowtype; cursor my\_cur is select * from emp where empno=111; begin open my\_cur; dbms\_output.put\_line(my\_cur%rowcount); loop if my\_cur%isopen then fetch my\_cur into info; exit when my\_cur%notfound; dbms\_output.put\_line(info.empno); dbms\_output.put\_line(my\_cur%rowcount); end if; end loop; close my\_cur; end; --------------------------------------------------- 使用显示游标删除或更新 使用游标时，如果处理过程中需要删除或更新。在定义游标查询语句时 必须使用select..for update语句，而在执行delete或update时使用 where current of 子句指定游标当前行。 cursor cursor\_name is select\_statement for update\[of column] wait/nowait 在使用for update 子句声明游标之后，可以使用以下语法更新行 update table\_name set column\_name=column\_value where current of cursor\_name; update命令中使用的列必须出现在for update of 子句中 select 语句必须只包括一个表，而且delete和update语句只有在打开游标并且提取 特定行之后才能使用。 declare cursor cur\_emp is select * from emp where sal&lt;2000 for update of sal; num emp%rowtype; begin open cur\_emp; loop fetch cur\_emp into num; exit when cur\_emp%notfound; update emp set sal=2000 where current of cur\_emp; end loop; close cur\_emp; end; ------------------------------------------- 带参数的显示游标 PL/SQL中允许显示游标接受输入参数。用于声明带参数的显示游标语法 cursor cursor\_name\[&lt;param\_name&gt; data\_type] \[return &lt;return type&gt;] is select\_statement declare dept\_num emp.deptno%type; emp\_numemp.empno%type; emp\_nam emp.ename%type; cursor emp\_cur(deptparam number) is select empno,ename from emp where deptno=deptparam; begin dept\_num :=&部门编号; open emp\_cur(dept\_num); loop fetch emp\_cur into emp\_num,emp\_nam; exit when emp\_cur%notfound; dbms\_output.put\_line(emp\_num||' '||emp\_nam); end loop; close emp\_cur; end; ----------------------------------------- 可以使用循环游标来简化显示游标。循环游标隐式打开显示游标（不需要open） 自动从结果集提取记录，然后处理完所有记录自动关闭游标。循环游标自动创建 %rowtype类型的变量并将此变量用做记录的索引。 循环游标语法如下： for record\_index in cursor\_name record\_index是PL/SQL自动创建的变量，此变量的属性声明为%rowtype类型。作用 域for循环之内。 循环游标的特性有： 从游标中提取所有记录之后自动关闭游标。 提取和处理游标中每一条记录 提取记录之后%notfound属性为true则退出循环。如果未有结果集，则不进入循环。 declare cursor emp\_cur is select * from emp; begin for temp in emp\_cur loop dbms\_output.put\_line(temp.ename); end loop; end; 循环游标自动打开，提取，关闭。只适用于静态游标 ---------------------------------------- ref游标 隐式游标和显示游标都是静态定义的。它们在编译的时候结果集就已经被确定。 如果想在运行的时候动态确定结果集，就要使用ref游标和游标变量。 创建ref游标需要两个步骤：1 声明ref cursor类型 2 声明 ref cursor类型变量。 语法如下： type ref\_cursor\_name is ref cursor \[return record\_type] 其中，return 用于指定游标提取结果集的返回类型。有return表示是强类型ref游标， 没有return表示是弱类型的游标。弱类型游标可以提取任何类型的结果集。 定义游标变量之后，就可以在PL/SQL执行部门打开游标变量 open cursor\_name for select\_statement; declare type emp\_cur is ref cursor; my\_cur emp\_cur; num number; selection varchar(2):='&请输入编号'; begin if selection='1' then dbms\_output.put\_line('员工信息'); open my\_cur for select deptno from emp; elsif selection='2' then dbms\_output.put\_line('部门信息'); open my\_cur for select deptno from dept; else dbms\_output.put\_line('请输入员工信息（1）或门部信息（2）'); end if; fetch my\_cur into num; while my\_cur%found loop dbms\_output.put\_line(num); fetch my\_cur into num; end loop; close my\_cur; end; -------------------------------------------- 在PL/SQL中可以执行动态SQL语句，execute immediate 语句只能语句处理返回单行 或没有返回的SQL语句，ref游标则可以处理返回结果集的动态SQL。ref游标的声明 方法与普通ref游标相同，只是在open时指定了动态SQL字符串。 open cursor\_name for dynamic\_select\_string \[using bind\_argument\_list] declare type sql\_cur is ref cursor; my\_cur sql\_cur; emp\_info emp%rowtype; sql\_string varchar2(100):='&请输入查询字符串'; begin open my\_cur for sql\_string; loop fetch my\_cur into emp\_info; exit when my\_cur%notfound; dbms\_output.put\_line(emp\_info.ename); end loop; close my\_cur; end; 游标变量的特点： （1）游标变量可以从不同的结果集中提取记录 （2）游标变量可以做为存储过程参数进行传递 （3）游标变量可以引用游标的所有属性 （4）游标变量可以进行赋值运算 使用游标变量也有一定的限制 （1）for update 子句不能与游标变量一起使用 （2）不允许在程序包使用游标变量（可以声明游标类型） （3）另一台服务器上的子过程不能接受游标变量参数 （4）不能将NULL值赋给游标变量。 （5）游标变量不能使用比较运算符。 （6）数据库中的列不能存储游标变量。 总结： （1）游标是使用在PL/SQL中，是用来查询数据，获取结果集的指针 （2）游标类型包括隐式游标，显示游标和ref游标。 （3）游标属性包括%found，%notfound，%rowcount，%isopen （4）PL/SQL自动定义隐式游标，以获取最近执行SQL语句信息。 （5）循环游标简化处理游标中所有行的查询。 （6）在声明ref游标时，不要将它与select 语句相关联。