游标的使用:
n 作用:
q 我们的select语句的结果集中只能有一条记录,这给程序带来了很大的限制,比如说,我们现在想把emp表中的每一条记录,按照一些复杂的逻辑取出来进行显示或更新,这个时候需要某种机制在表中的多条记录之间进行循环,这种机制就是游标。游标就是指在某个结果集上的指针,通过这个指针的移动,我们得以遍历整个结果集,这样我们就可以一次取出多条记录,然后按照程序的逻辑一条一条地进行处理。
n 典型的游标使用的步骤包括以下几步:
q 声明游标
q 打开游标
q 处理游标中的数据
q 关闭游标
n 典型示例:
declare
cursor c is select * from emp;
v_emp c%rowtype;
begin
open c;
fetch c into v_emp;
dbms_output.put_line(v_emp.ename);
close c;
end;
n 最常用的游标属性有以下四个:
q %isopen,boolean类型变量,用来代表游标是否打开。
q %notfound,boolean类型变量,如果最近的fetch语句没有返回一条记录,取true。
q %found,boolean类型变量,如果最近的fetch语句取到了记录,取true。
q %rowcount,number类型变量,用来代表目前fetch到的记录的总行数。
q loop循环遍历游标
n While循环遍历游标
n For循环遍历游标
n 带参数的游标
n 使用游标更新结果集
游标的简单使用: declare cursor c is select * from emp order by ename desc; v_emp c%rowtype; begin open c; fetch c into v_emp; dbms_output.put_line(v_emp.ename); close c; end; |
利用loop循环和%notfound属性,我们可以实现游标的遍历,下面给出一个例子: declare cursor c is select * from emp; v_emp emp%rowtype; begin open c; loop fetch c into v_emp; exit when (c%notfound); dbms_output.put_line(v_emp.ename); end loop; close c; end;
|
利用while循环配合%found属性,我们也可以遍历游标,例: declare cursor c is select * from emp; v_emp emp%rowtype; begin open c; fetch c into v_emp; while (c%found) loop dbms_output.put_line(v_emp.ename); fetch c into v_emp; end loop; close c; end;
|
利用for循环遍历游标最简单,例如: declare cursor c is select * from emp; begin for v_emp in c loop dbms_output.put_line(v_emp.ename); end loop; end;
这个时候,我们不需要打开游标,也不需要关闭,甚至不用声明循环变量v_emp,这一切都在for循环内部自动完成,正因为for循环处理游标是如此简单,因此大多数时候我们所使用的都是for循环。
|