oracle儲存過程簡單例項 變數賦值 遊標遍歷
有兩張表,學生表和對應的各科成績表。
學生表student
欄位:id int name varchar(20)
數值:1A
2B
成績表score
欄位:id int studentid int subjectid int score int
數值:
1 1 1 80
2 1 2 903 1 3 100
4 2 1 60
5 2 2 70
用儲存過程來通過名字獲取對應學生的成績最大值的科目名稱。本例的邏輯比較簡單,用一句sql就可以實現,這裡只是演示儲存過程的基本語法。
建立包package:
create or replace package max_type as
type max_cursor is ref cursor;
end;
建立儲存過程procedure:
create or replace procedure getMaxScore
(
xname in varchar,
x_cur out MAX_TYPE.max_cursor
)
as
max_score number;
cur_score number;
cursor cur_1 is select score from score where studentid=(select id from student where name=xname);
begin
max_score := 0;
for everyrow in cur_1 loop
begin
if (everyrow.score > max_score) then
max_score := everyrow.score;
end if;
end;
end loop;
open x_cur for select max_score from student where rownum=1;
end getMaxScore;
呼叫儲存過程:
SQL>var a refcursor;
SQL>call getMaxScore('A', :a);
SQL>print a
輸出結果:
100