hanlu0221 发表于 2013-1-14 08:38:54

PL/SQL4之——游标(cursor)

游标(cursor)简单来说,就是指向结果集的指针。

在PL/SQL中,一条select语句只能返回一条记录,但是通过cursor就能完成取出多条记录的任务了。

先看一个简单的小例子:
declare       cursor c is               select * from emp;      v_empc%rowtype; begin      open c;      fetch c into v_emp;      dbms_output.put_line(v_emp.ename);      close c; end;



其中有几点需要注意:
1.要在一个结果集上声明一个游标,如上,在“emp表”的查询结果集上声明了游标c;
2.“c%rowtype”相当于“v_emp”中可以存放一条结果集的记录;
3.用于游标需要“open”和“close”两个操作;
4.“fetch...into...”表示取出的结果存入。。。


那如何让我们取出多条记录呢?就可以通过“简单循环”与“游标”的结合来完成了。
继续优化上面的小例子:
declare      cursor c is                select * from emp;      v_empc%rowtype; egin      open c;       loop         fetch c into v_emp;      exit when(c%notfound);      dbms_output.put_line(v_emp.ename);          end loop;      close c; end;


这里说一下游标的几个属性:
1.isopen:即游标是否打开,很少用;
2.notfound:即最近的一个fetch语句没有返回记录;
3.found:   即fetch到记录了;
4.rowcount:即当前已经fetch到了多少条记录。


还有一个需要注意的:
其中的第10句和第11句不可以调换位置,因为当最后一次执行fetch语句的时候,没有返回记录,就去执行“dbms_output.put_line()”,则会再打印一遍上次fetch的结果。

再来2个小例子巩固一下:
declare   cursor c is             select * from emp;   v_empemp%rowtype; begin    open c;      fetch c into v_emp;    while(c%found) loop       dbms_output.put_line(v_emp.ename);       fecth c into v_emp;    end loop;    close c; end;

其中,如果把第9句和第10句调换位置,则会出现第一句没打印,最后一句打印两边的现象。
declare      cursor c is             select * from emp; begin    for v_emp in c loop       dbms_output.put_line(v_emp.ename);    end loop; end;

这里的for循环,自动提供了一些操作,所以,
1.不需要声明v_emp;
2.不需要“open”和“close”游标;
3.不需要手动“fetch”。


综上,for循环语句简单,且不容易出错,所以经常被使用。


带参数的游标,这里的游标类似函数
例子:

declare    cursor c(v_deptno emp.deptno%type, v_job emp.job%type)    is       select ename, sal from emp where deptno = v_deptno and job = v_job; begin    for v_temp in c(30, "clerk") loop       dbms_output.put_line(v_temp.ename);    end loop; end;


可更新的游标
大多数游标是用来“只读”的,但也有一种游标是用来做“更新”的。
例子:

declare    cursor c      is       select * from emp for update; begin    for v_temp in c loop       if(v_temp.sal < 2000)then         update emp set sal = sal * 2 where current of c;      elsif(v_temp.sal = 5000)then         delete from emp where current of c;      end if;    end loop;    commit;    end;
其中,“current of c”表示游标当前所指向的记录
页: [1]
查看完整版本: PL/SQL4之——游标(cursor)