当前所在位置:珠峰网资料 >> 计算机 >> Oracle认证 >> 正文
ORACLE中的游标Cursor总结(一)
发布时间:2010/9/24 10:12:53 来源:www.xue.net 编辑:城市总裁吧

  游标(Cursor):用来查询数据库,获取记录集合(结果集)的指针,可以让开发者一次访问一行结果集,在每条结果集上作操作。

  游标可分为:

  1.静态游标:分为显式(explicit)游标和隐式(implicit)游标。

  2.REF游标:是一种引用类型,类似于指针。

  1、静态游标

  1.1显式游标

  定义格式:

  CURSOR 游标名 ( 参数 )  IS

  Select 语句 FOR UPDATE [OF [schema.]table.column[,[schema.]table.column]..

  [nowait]

  例子1 :无参数,打开关闭游标

  set serveroutput on size 10000000 ;

  create or replace procedure TEST is

  cursor c1 is

  select tname from tab;

  pname varchar2(32);

  begin

  open c1;

  loop

  fetch c1

  into pname;

  exit when c1%notfound;

  dbms_output.put_line(pname);

  end loop;

  close c1;

  end TEST

  exec test;

  例子2 :参数使用,参数使用方法和存储过程一样

  create or replace procedure TEST is

  cursor c1(pname in varchar2) is

  select tname from tab where tname like pname;

  pname varchar2(32);

  begin

  open c1('T%');

  loop

  fetch c1

  into pname;

  exit when c1%notfound;

  dbms_output.put_line(pname);

  end loop;

  close c1;

  end TEST;

  1.2隐式游标

  不用明确建立游标变量,分两种:

  1.在PL/SQL中使用DML语言,使用ORACLE提供的名为“SQL”的隐示游标。

  举例:

  declare

  begin

  update departments set department_name = department_name;

  --where 1=2;

  dbms_output.put_line('update ' || sql%rowcount || ' records');

  end;

  /

  2.CURSOR FOR LOOP,用于for loop 语句

  举例:

  例子1:无参数,使用循环,无须打开关闭,本人这种方式

  create or replace procedure TEST is

  cursor c1 is

  select tname from tab;

  begin

  for rr in c1 loop

  dbms_output.put_line(rr.tname);

  end loop;

  end TEST;

  例子1:有参数,使用循环,无须打开关闭,本人这种方式

  create or replace procedure TEST is

  cursor c1(pname in varchar2) is

  select tname from tab where tname like pname;

  begin

  for rr in c1('T%') loop

  dbms_output.put_line(rr.tname);

  end loop;

  end TEST;

  1.3游标常用属性:

  %FOUND:变量最后从游标中获取记录的时候,在结果集中找到了记录。

  %NOTFOUND:变量最后从游标中获取记录的时候,在结果集中没有找到记录。

  %ROWCOUNT:当前时刻已经从游标中获取的记录数量。

  %ISOPEN:是否打开。

  Declare  /* /* 定义静态游标 */ */

  Cursor emps is

  Select * from employees where rownum < 6 order by 1;

  Emp employees%rowtype;

  Row number := 1;

  Begin

  Open emps; /* ?打开静态游标 */

  Fetch emps

  into emp; /*  读取游标当前行  */

  Loop

  If emps%found then

  Dbms_output.put_line('Looping over record ' || row || ' of ' ||

  emps%rowcount);

  Fetch emps

  into emp;

  Row := row + 1;

  Elsif emps%notfound then

  Exit;

  End if;

  End loop;

  If emps%isopen then

  Close emps; /*  关闭游标  */

  End if;

  End;

  /

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved