mysql存储过程简单实例 变量赋值 游标遍历
时间:2019-02-18 11:56 来源:未知 作者:IT
应用场景:
有两张表,学生表和对应的各科成绩表。
学生表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
(责任编辑:IT)
应用场景: 有两张表,学生表和对应的各科成绩表。 学生表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 (责任编辑:IT) |