您好,欢迎访问一九零五行业门户网

Oracle Cursor详解与实例

游标是sql的一个内存工作区,由系统或用户以变量的形式定义。游标的作用就是用于临时存储从数据库中提取的数据块。在某些情况下,
摘要:详细介绍oracle数据库中关于游标的定义和使用。通过实例操作来深入了解cursor的用法和用处。
一:相关概念 1、concept when oracle database executes asql statement , it stores the result set and processing information in anunnamed private sql area . a pointer to this unnamed area , called a cursor ,let you retrieve the rows of the result set one at a time . cursor attributesreturn information about the state of the cursor . 
2、概念:  
二:具体类型及使用 1、implicit cursor 3)示例:
begin
  update student set sname='chy' where sno='1';
  if sql%isopen then
    dbms_output.put_line('cursor is opening !');
  else
    dbms_output.put_line('cursor is closed !');
  end if;
  if sql%found then
    dbms_output.put_line('dml is successed !');
  else
    dbms_output.put_line('dml is failed !');
  end if;
  if sql%notfound then
    dbms_output.put_line('dml is failed !');
  else
    dbms_output.put_line('dml is successed !');
  end if;
      dbms_output.put_line(sql%rowcount||' is the number of result !');
  exception
      when no_data_found then
          dbms_output.put_line('sorry no data');
      when too_many_rows then
          dbms_output.put_line('too many rows');
end;
2、explicit cursor
很直白的说明了显示游标的用处、以及用法。
] is select xxx from xxxwhere xxx;
] ;
a)使用显示游标
v、关闭游标:将游标放入缓冲池中,没有完全释放资源。可重新打开。
close 游标名;
b)遍历循环游标
循环游标隐式打开游标,,自动滚动获取一条记录,并自动创建临时记录类型变量存储记录。处理完后自动关闭游标。
……
loop
数据处理语句;
end loop;
……
loop
end loop;
……
open 游标名
-- do something
end loop;
……
close 游标名
declare
  cursor cur is select * from t_user where age = 22;
  userinfo t_user%rowtype;
begin
  for userinfo in cur loop
    exit when cur%notfound;
    dbms_output.put_line('user id : ' || userinfo.id || '-' || 'user name : ' || userinfo.username);
  end loop;
  exception
    when others then
      dbms_output.put_line(sqlerrm);
end;     
ii
declare
  cursor cur is select * from t_user where age = 22;
  userinfo t_user%rowtype;
begin
  open cur;
  loop
    exit when cur%notfound;
    fetch cur into userinfo;
    dbms_output.put_line('user id : ' || userinfo.id || '-' || 'user name : ' || userinfo.username);
  end loop;
  exception
    when others then
          dbms_output.put_line(sqlerrm);
 close cur;
end;
其它类似信息

推荐信息