Oracle 動態遊標的使用

lishiran發表於2007-03-04

create or replace procedure proc_XXX(
p_iBillMonth in number,
p_tab in number,
p_nStatus out number,

[@more@]

一、
create or replace procedure proc_XXX(
p_iBillMonth in number,
p_tab in number,
p_nStatus out number,
p_szErrorMsg out varchar2
)
is
type t_cur is ref cursor;
v_ser t_cur;
TYPE detail_param IS RECORD
(
acc_code number(7),
fee number(9),
time number(1),
cout number(7),
unit number(12)
);
TYPE detail_param_list IS TABLE OF detail_param INDEX BY BINARY_INTEGER;
v_noowner_detail_param_list detail_param_list;
v_owner_detail_param_list detail_param_list;
begin
v_strSql:=' select acc_id,sub_id,to_char(begin_date,''yyyymmddhh24miss''),'
||' to_char(end_date,''yyyymmddhh24miss''),detail_data,rowid from sum_noowner_'||p_iBillMonth
||' where mod(acc_id,10)='||p_tab;
open v_ser for v_strSql;
loop
<>
fetch v_ser into v_iAccId,v_iSubId,v_BeginDate,v_EndDate,v_noDetail,v_RowId;
exit when v_ser%notfound;
end loop;
close v_ser;
p_nStatus:=0;
p_szErrorMsg:='Succeed to finish proc_no2ower.';
return;
exception
when others then
p_nStatus:=-1;
p_szErrormsg:='encounter a exception,sqlcode:'||sqlcode
||',sqlerrm:'||sqlerrm||'v_sql:'||v_strSql;
return;
end proc_XXX;
------------------------------------------------------------------------------------------------------------
關於oracle中用儲存過程返回動態記錄集的學習
測試過程:
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);
end;

4、測試結果:
透過。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9099175/viewspace-902668/,如需轉載,請註明出處,否則將追究法律責任。

相關文章