Oracle存储过程or函数返回结果集
不像 那样在存储过程中⽤Select就可以返回结果集,⽽是通过Out型的参数进⾏结果集返回的。实际上是利⽤REF CURSOR
--procedure返回记录集:
----------------------声明⼀个Package--------------
CREATE OR REPLACE PACKAGE pkg_test
AS
TYPE myrctype IS REF CURSOR;
PROCEDURE get (p_id NUMBER, p_rc OUT myrctype); --Package中声明名为get 的Procedure(只有接⼝没内容)
END pkg_test;
--------------------------------------------------------
-----------------声明Package Body,即上⾯Package中的内容,包括Procedure get---------------------
CREATE OR REPLACE PACKAGE BODY pkg_test
AS
PROCEDURE get (p_id NUMBER, p_rc OUT myrctype)
IS
sqlstr VARCHAR2 (500);
BEGIN
IF p_id = 0 THEN
OPEN p_rc FOR
SELECT ID, NAME, x, address, postcode, birthday
FROM student;
ELSE
sqlstr :=
'lect id,name,x,address,postcode,birthday
from student where id=:w_id'; --w_id是个参数,
--以下 p_rc是个REF CURSOR游标类型,⽽且是OUT型参数,即可返回⼀个记录集了。USING p_id就是替换上⾯SQL中:w_id值拉:) OPEN p_rc FOR sqlstr USING p_id;
END IF;
END get;
END pkg_test;
--function返回记录集的例⼦,原理和上⾯相同,⽽是⽤function的return值来返回记录集。
函数返回记录集:
建⽴带ref cursor定义的包和包体及函数:
CREATE OR REPLACE
package pkg_test as
/* 定义ref cursor类型
不加return类型,为弱类型,允许动态sql查询,
否则为强类型,⽆法使⽤动态sql查询;
*/
type myrctype is ref cursor;
function get(intID number) return myrctype;
end pkg_test;
/
CREATE OR REPLACE
package body pkg_test as
--函数体
function get(intID number) return myrctype is
rc myrctype; --定义ref cursor变量
sqlstr varchar2(500);
begin
if intID=0 then
--静态测试,直接⽤lect语句直接返回结果
open rc for lect id,name,x,address,postcode,birthday from student;
el
--动态sql赋值,⽤:w_id来申明该变量从外部获得
sqlstr := 'lect id,name,x,address,postcode,birthday from student where id=:w_id'; --动态测试,⽤sqlstr字符串返回结果,⽤using关键词传递参数
open rc for sqlstr using intid;
end if;
return rc;
end get;
end pkg_test;