#条件语句 if-elseif-else与case
#注意 在某种情况下(例如 做等值判断)使用case写法更加简洁
#但是,因为case后面有列名,功能上会有一些限制
#案例一
#根据学员的成绩输出不同的评价,科目名称为'java基础'的学员成绩在
#90分以上 输出'优秀',80-90输出'良好,'60-80'输出及格,60分以下输出'不及格'
#使用if-elseif-else 案例一
drop procedure if exists proc_class1;
create procedure proc_class(in StuNo int,in subName varchar(30),out result varchar(10))
begin
declare score int;
select r.StudentResult into score from result r
where r.SubjectNo=(select SubjectNo from `subject` where SubjectName=subName)
and r.StudentNo=StuNo;
if score>=90 then set result='优秀';
elseif score>=80 then set result='良好';
elseif score>=60 then set result='及格';
else set result='不及格';
end if;
end;
#输出结果
# "@"表示用户变量
call proc_class(1002,'java基础',@examResult);
select @examResult;
#使用case案例一
drop procedure if exists proc_class2;
create procedure proc_class2(in StuNo int,in subName varchar(30),out result varchar(10))
begin
declare score int;
select r.StudentResult into score from result r
where r.SubjectNo=(select SubjectNo from `subject` where SubjectName=subName)
and r.StudentNo=StuNo;
case
when score>=90 then set result='优秀';
when score>=80 then set result='良好';
when score>=60 then set result='及格';
else set result='不及格';
end case;
end;
#输出结果
call proc_class2(1002,'JAVA第一学年',@examResult);
select @examResult;
#案例二
#根据病人的家庭收入,返还补贴不同比例的医疗费用
#家庭年收入在5000元以下的返还当年总医疗费用的20%
#家庭年收入在10000元以下的返还当年总医疗费用的15%
#家庭年收入在30000元以下的返还总医疗费用的5%
#30000元以上或未登记的不享受医疗费用返还
#输入病人编号和年份,计算该患者当年的应返还的医疗费用
#使用if-elseif-else案例二
drop procedure if exists proc_calSubsidy1;
create definer=root@localhost procedure proc_calSubsidy
(in p_patientID int(4),in p_year varchar(10),out p_subsidy float)
begin
declare p_totalCost float;
declare p_income float default-1;
#三连获取查询语句
if p_income>=0 and p_income<5000 then set p_subsidy=p_totalCost*0.2;
elseif p_income>=5000 and p_income<10000 then set p_subsidy=p_totalCost*0.15;
elseif p_income>=10000 and p_income<30000 then set p_subsidy=p_totalCost*0.05;
else set p_subsidy=0;
end if;
end;
#使用case案例二
drop procedure if exists proc_calSubsidy2;
create definer=root@localhost procedure proc_calSubsidy
(in p_patientID int(4),in p_year varchar(10),out p_subsidy float)
begin
declare p_totalCost float;
declare p_income float default-1;
#三连获取查询语句
case
when p_income>=0 and p_income<5000 then set p_subsidy=p_totalCost*0.2;
when p_income>=5000 and p_income<10000 then set p_subsidy=p_totalCost*0.15;
when p_income>=10000 and p_income<30000 then set p_subsidy=p_totalCost*0.05;
when p_subsidy=0;
end case;
end;