1. 程式人生 > >mysql儲存過程簡單例項 變數賦值 遊標遍歷

mysql儲存過程簡單例項 變數賦值 遊標遍歷

應用場景:
有兩張表,學生表和對應的各科成績表。
學生表student
欄位:id int, name varchar(20)

數值:

             1             A

             2             B 
成績表score
欄位:id int       studentid int        subjectid int         score int

數值:

             1            1                             1           80

             2            1                             2           90
             3            1                             3          100
             4            2                             1          60
             5            2                             2          70
用儲存過程來通過名字獲取對應學生的成績最大值的科目名稱。本例的邏輯比較簡單,用一句sql就可以實現,這裡只是演示儲存過程的基本語法。


建立儲存過程:
delimiter //
create procedure getMaxScore(IN `xname` varchar(20))
begin
declare max_score INT default 0;
declare cur_score INT;
declare b int default 0;
DECLARE cur_1 CURSOR FOR select score from score where studentid=(select studentid from student where name = xname);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;
OPEN cur_1;
FETCH cur_1 INTO cur_score;
while b<>1 do
if (cur_score > max_score) then
set max_score = cur_score;
end if;
FETCH cur_1 INTO cur_score;
end while;
close cur_1;       
select max_score;
end


呼叫儲存過程:
call getMaxDataPrivilege('A')


輸出結果:
100