测试过程:
1、建立测试表
CREATE TABLE student
(
id NUMBER,
name VARCHAR2(30)
)
/
2、建立带ref cursor定义的包和包体及函数:
CREATE OR REPLACE package pkg_test as
/* 定义ref cursor类型
不加return类型,为弱类型,允许动态sql查询,
否则为强类型,无法使用动态sql查询;
*/
type myrctype is ref cursor;
--函数申明
function get return myrctype;
end pkg_test;
/
CREATE OR REPLACE package body pkg_test as
--函数体
function get return myrctype is
rc myrctype; --定义ref cursor变量
sqlstr varchar2(500);
begin
--静态测试,直接用select语句直接返回结果
open rc for select id,name from student;
--动态sql赋值,用:w_id来申明该变量从外部获得
--sqlstr := 'select id,name,sex,address,postcode,birthday from student --where id=:w_id';
--动态测试,用sqlstr字符串返回结果,用using关键词传递参数
--open rc for sqlstr using intid;
return rc;
end get;
end pkg_test;
/
3、用pl/sql块进行测试:
declare
w_rc pkg_test.myrctype; --定义ref cursor型变量
--定义临时变量,用于显示结果
w_id student.id%type;
w_name student.name%type;
begin
--调用函数,获得记录集
w_rc := pkg_test.get;
--fetch结果并显示
fetch w_rc into w_id,w_name;
while w_rc%Found loop
dbms_output.put_line(w_name);
fetch w_rc into w_id,w_name;
end loop;
end;
/