一、網絡上關於Oracle存儲過程的一般教程:
存儲過程(Procedure)
create [or replace] procedure pro_name
[(parameter1 [mode] datatype,parameter2 [mode] datatype, ...)]
is/as
.....//聲明部分
begin
....//函數主題
exception
....//異常處理
end;
從上面的代碼段可以看見,存儲過程是支持參數傳遞的,而且參數還不止一個 ,下面是幾種參數類型的解釋。
1、in 傳入(形參)默認,可以有默認值(就行編程中的函數參數一樣,in代表的是進行輸入的參數);
2、out(實參)先將初始值傳入經過處理後在傳出,必須定義名稱(out參數就像編程函數中的輸出,也可以理解爲return的數據);
3、in out 類型參數(既可以作爲參數輸入,也可以作爲參數輸出),可以直接賦予默認值;
二、自己學着編寫的存儲過程:
create or replace procedure procedure1 (id in integer,age out Date)
as
begin
select Sage into age from Student where Sid = id;
DBMS_OUTPUT.put_line('年齡:'|| age);
end procedure1;
這是我編寫的一個包含輸入、輸出參數的簡單的存儲過程。這個簡單的存儲過程相信大家看一下基本概念就能使用了,然後注意一下,在輸出填充的時候需要用到into關鍵字。(
定義多參數輸出時參數類型中的類型SIZE問題。問題屬於入參類型錯誤:plsql中procedure的入參類型,如果是number或varchar2的話不需要定義長度。否則編譯不能通過。
)
三、需要返回多個結果得存儲過程
下面,是自己寫的一個示例,我們先看代碼:
create or replace procedure test60(cnumber in integer)
is
cursor student_cursor is select distinct S.* from Student S,sc where S.sid = sc.sid and sc.score < 60 and sc.cid = cnumber;
T_Student student_cursor%ROWTYPE;
//定義的是結果集中的每一行的數據類型,在後續的結果提取當中,這個會成提取出來的對象。
begin
open student_cursor;
loop
fetch student_cursor into T_Student;
exit when student_cursor%notfound;
dbms_output.put(T_Student.Sid);
dbms_output.put(T_Student.Sname);
dbms_output.put(T_Student.Sage);
dbms_output.put_line(T_Student.Ssex);
end loop;
close student_cursor;
end test60;
首先,基本的語法大家是沒有問題的了。主要的問題就是集中在Cursor的定義當中。遊標定義還是有幾種方法的,這裏我就使用自己學習了的一種定義方式。
cursor student_cursor is select distinct S.* from Student S,sc where S.sid = sc.sid and sc.score < 60 and sc.cid = cnumber;
(需要注意的是,在你定義遊標的時候,需要使用的是IS關鍵字)。在我的理解中,cursor就有些類似於Android數據庫開發中的結果集。
然後,需要理解的是,cursor返回的是一行一行的數據(因爲我的數據庫是這樣設計的),所以,你還需要定義出每行返回的數據的類型,也就是給它一個名分。(具體過程數據庫將會爲你執行)。
T_Student student_cursor%ROWTYPE;定義行返回類型。
最後,就是需要打開遊標,將其中的數據一個個輸出出來。
begin
open student_cursor;
loop
fetch student_cursor into T_Student;
exit when student_cursor%notfound;
dbms_output.put(T_Student.Sid);
dbms_output.put(T_Student.Sname);
dbms_output.put(T_Student.Sage);
dbms_output.put_line(T_Student.Ssex);
end loop;
close student_cursor;
end test60;
其中比較重要的一點是,你需要爲你的循環設定跳出事件。最後,將你的cursor關閉。(fetch的作用是循環從cursor當中取出結果,填充到定義的數據類型當中。我理解的是內部就是一個循環,通過的exit的判斷,不斷的提取出結果。(類似Java當中的rs.next,不斷地取出結果。))
好了,今天的學習就到這裏,以後遇到問題再來進行補充。