Oracle游标

2019-07-30  本文已影响0人  Yinawake

Oracle游标的关键子CURSOR,用来定义查询出来的数据集,把内存中的数据通过游标一条一条的循环取出。

游标种类

  1. 显示游标
    游标使用之前必须先声明,一般对查询语句结果定义游标,然后通过打开游标循环取出结果集。
  2. 隐式游标
    指PL/SQL管理,开发者不能自己控制,只能获得它的属性。

显示游标

开发中比较常用

  1. 声明游标
declare cursor cursor_name is select * from xxx;
  1. 打开游标
open cursor_name;
  1. 读取游标中的数据
fetch curos_name into record(变量)
  1. 关闭游标
close cursor_name;

实例

declare
  --定义游标
  cursor cur_xsjbxx is
    select * from stuinfo order by stuid;
  --定义记录变量  
  ls_curinfo cur_xsjbxx%rowtype;
begin
  open cur_xsjbxx;--打开游标
  loop
    FETCH cur_xsjbxx
      INTO ls_curinfo;--获取记录值
    EXIT WHEN cur_xsjbxx%NOTFOUND;
   
    dbms_output.put_line('学号:' || ls_curinfo.stuid || ',姓名:' ||
                         ls_curinfo.STUNAME);
  end loop;
  close cur_xsjbxx;--关闭游标
end;

解析:配合loop语句来循环打印结果,通过游标变量%NOTFOUND来获取游标的结束,跳出loop

显式游标的属性

  1. %NOTFOUND.表示游标获是否还能提取数据。没有数据时返回TRUE,有数据时返回FALSE
  2. %FOUND。与%NOTFOUND相反
  3. %ISOPEN。判断游标是否打开
  4. %ROWCOUNT。表示游标FETCH INTO获取了多少记录数。

实例

declare
  --定义游标
  cursor cur_xsjbxx is
    select * from stuinfo order by stuid;
  --定义记录变量  
  ls_curinfo cur_xsjbxx%rowtype;
begin
  open cur_xsjbxx;--打开游标
  loop
    FETCH cur_xsjbxx
      INTO ls_curinfo;--获取记录值
    EXIT WHEN cur_xsjbxx%NOTFOUND;
    --利用游标计数器打印学生个数
    dbms_output.put('%rowcount计数器,第'||cur_xsjbxx%rowcount||'位学生,');
    dbms_output.put_line('学号:' || ls_curinfo.stuid || ',姓名:' ||
                         ls_curinfo.STUNAME);
  end loop;
  close cur_xsjbxx;--关闭游标
end;

隐式游标

实例

declare
  ls_xsjbxx stuinfo%rowtype;
begin
  --查询学生信息
  select * into ls_xsjbxx from stuinfo t where t.stuid = 'SC201801001';
  if sql%found then
    dbms_output.put_line('学号:' || ls_xsjbxx.stuid || ',姓名:' ||
                         ls_xsjbxx.stuname);
  end if;
 
  --查询学生信息(不存在的学生)
  select * into ls_xsjbxx from stuinfo t where t.stuid = 'SC201901001';
  if sql%found then
    dbms_output.put_line('学号:' || ls_xsjbxx.stuid || ',姓名:' ||
                         ls_xsjbxx.stuname);
  end if;
exception
  when no_data_found then
    dbms_output.put_line('该学生SC201901001不存在');
end;
上一篇 下一篇

猜你喜欢

热点阅读