Oracle数据库的应用,游标-2

157 阅读2分钟

「这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战」。

3. 动态Cursor(Ref Cursor)

运行时才产生的游标,是动态游标。 

动态关联结果集的临时对象。即在运行的时候动态决定执行查询。

REF游标的作用?

实现在程序间传递结果集的功能,利用REF CURSOR也可以实现BULK SQL,从而提高SQL性能。

静态游标和REF游标有什么区别?

  • 静态游标是静态定义,REF 游标是动态关联;
  • 使用REF 游标需REF 游标变量。
  • REF 游标能做为参数进行传递,而静态游标是不可能的。

什么是REF游标变量?

REF游标变量是一种 引用REF游标类型  的变量,指向动态关联的结果集。

Ref cursor的使用步骤:

  • Type 自定义游标类型 is ref cursor; --自定义了一个游标类型,并声明它是一个动态游标
  • 游标名称 自定义游标类型;            --声明一个游标 它是自定义类型
  • Open 游标名称 for sql语句;
  • Fetch 游标名称  into 行对象;
  • Close 游标名称

示例:

create or replace procedure sigleRowCoursor(id_p in varchar2) is

 cursor student_c is select * from student where id = id_p;

  rs student%rowType;

  type ref_cursor_type  is ref cursor;--自定义了一个游标类型,并声明它是一个动态游标

  college_c ref_cursor_type;

  rs_college college%rowType;

  v_sql varchar2(100);

 begin

   open student_c;

      fetch student_c into rs;

      dbms_output.put_line(rs.id || ' ' || rs.name);

      v_sql := 'select * from college where id = ' || rs.col_id;

      close student_c;

      open college_c for v_sql;

      fetch college_c into rs_college;

      dbms_output.put_line(rs_college.id || ' ' || rs_college.name);

      close college_c;

end;

存储过程返回游标:

create or replace procedure backParamter2 (res out sys_refcursor) is

begin

 open res for select * from student;

end;

运行:

declare

  • 声明一个系统游标类型的变量

student_cursor sys_refcursor;

  • 声明一个自定义类型(这个类型是学生表里的行对应的表)

type student_table_type is table of student%rowtype;

  • 声明一个变量为自定义类型

student_table student_table_type;

begin

  • 执行存储过程,此过程返回系统游标

  backParamter2(student_cursor);

  • 抓取系统游标(集合)里的数据到学生表里

  fetch student_cursor bulk collect into  student_table;

  • 迭代学生表

    for i  in 1..student_table.count

  loop

      --取学生表里的行对应的列的值

      dbms_output.put_line(student_table(i).id || ',' || student_table(i).name);

         end loop;

  --关闭游标

 close student_ref_cursor;

end;