測試過程:
1、建立測試表
CREATE TABLE student
(
id NUMBER,
name VARCHAR2(30),
sex VARCHAR2(10),
address VARCHAR2(100),
postcode VARCHAR2(10),
birthday DATE,
photo LONG RAW
)
/
2、建立帶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
--靜態測試,直接用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;
/
3、用pl/sql塊進行測試:
declare
w_rc pkg_test.myrctype; --定義ref cursor型變量
--定義臨時變量,用于顯示結果
w_id student.id%type;
w_name student.name%type;
w_sex student.sex%type;
w_address student.address%type;
w_postcode student.postcode%type;
w_birthday student.birthday%type;
begin
--調用函數,獲得記錄集
w_rc := pkg_test.get(1);
--fetch結果并顯示
fetch w_rc into w_id,w_name,w_sex,w_address,w_postcode,w_birthday;
dbms_output.put_line(w_name);/*此處的put_line表示輸出一行在屏幕上顯示,假如想輸出姓名和性別等,可以這樣寫dbms.output.putline(w_name||w_sex||w_address),而這樣寫dbms.output.putline(w_name||chr(10)||w_sex)則表示可以換行。*/
end;
4、測試結果:
通過。
在上述的online document中有相當多的內容,包括怎樣在pro*c傳遞動態參數給存儲過程、ref cusor的使用限制、open cursor for的4中不同方法等等。轉:http://hetingonion.spaces.live.com/blog/cns!DA3BAE0FAC0FE44F!115.entry