Oracle不像SQLServer那樣在預存程序中用Select就可以返回結果集,而是通過Out型的參數進行結果集返回的。實際上是利用REF CURSOR
複製代碼 代碼如下:--procedure返回記錄集:
----------------------聲明一個Package--------------
CREATE OR REPLACE PACKAGE pkg_test
AS
TYPEmyrctypeIS REF CURSOR;
PROCEDURE get_r(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_r(p_id NUMBER,p_rc OUT myrctype)
IS
sqlstr VARCHAR2 (500);
BEGIN
IF p_id = 0 THEN
OPEN p_rc FOR
SELECT ID, NAME, sex, address, postcode, birthday
FROM student;
ELSE
sqlstr :=
'select id,name,sex,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
type myrctype is ref cursor;
function get_r(intID number) return myrctype;
end pkg_test;
/
CREATE OR REPLACE
package body pkg_test as
--函數體
function get_r(intID number) return myrctype is
rc myrctype; --定義ref cursor變數
sqlstr varchar2(500);
begin
if intID=0 then
--靜態測試,直接用select語句直接返回結果
open rc for select id,name,sex,address,postcode,birthday from student;
else
--動態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;
end if;
return rc;
end get;
end pkg_test;