-- if 条件
-- score >= 85分 优秀
-- score >= 60分 且 score < 85分 及格
-- score < 60分 不及格
create procedure p3()
begin
declare score int default 58;
declare result varchar(10);
if score >= 85 then
set result := '优秀';
elseif score >= 60 then
set result := '及格';
else
set result := '不及格';
end if;
select result;
end;
drop procedure if exists p3;
call p3();
-- in/out/inout参数
-- 传入in参数 判定等级 并返回out
-- score >= 85分 优秀
-- score >= 60分 且 score < 85分 及格
-- score < 60分 不及格
create procedure p4(in score int, out result varchar(10))
begin
if score >= 85 then
set result := '优秀';
elseif score >= 60 then
set result := '及格';
else
set result := '不及格';
end if;
end;
call p4(98, @result);
select @result;
-- 将传入 200分制的分数 换算 成百分制 返回分数 inout
create procedure p5(inout score double)
begin
set score := score * 0.5;
end;
set @score = 198;
call p5(@score);
select @score;
-- 根据传入的月份,判定月份所属的季节(要求采用case结构)。
-- 1-3月份,为第一季度
-- 4-6月份,为第二季度
-- 7-9月份,为第三季度
-- 10-12月份,为第四季度
create procedure p6(in month int)
begin
declare result varchar(10);
case
when month >= 1 and month <= 3 then
set result := '第一季度';
when month >= 4 and month <= 6 then
set result := '第二季度';
when month >= 7 and month <= 9 then
set result := '第三季度';
when month >= 10 and month <= 12 then
set result := '第四季度';
else
set result := '非法参数';
end case ;
select concat('您输入的月份:',month,',所属季度:',result);
end;
call p6(19);
-- while 循环 满足条件进入循环
-- 计算从1累加到n的值,n为传入的参数值。
-- 定于局部变量 记录累加之后的值
-- 每循环一次 n减1 n减到0 退出循环
create procedure p7(in n int)
begin
declare total int default 0;
while n>0 do
set total := total + n;
set n := n - 1;
end while;
select total;
end;
call p7(100);
-- repeat 循环 满足条件退出循环
-- 计算从1累加到n的值,n为传入的参数值。(使用repeat实现)
create procedure p8(in n int)
begin
declare total int default 0;
repeat
set total := total + n;
set n := n -1;
until n <= 0
end repeat;
select total;
end;
call p8(100);
-- loop
-- LEAVE ; -- 退出指定标记的循环体
-- ITERATE ; -- 直接进入下一次循环
-- 计算从1累加到n的值,n为传入的参数值
create procedure p9(in n int)
begin
declare total int default 0;
sum:loop
if n <= 0 then
leave sum;
end if;
set total := total + n;
set n := n - 1;
end loop sum;
select total;
end;
call p9(10);
-- 计算从1到n之间的偶数累加的值,n为传入的参数值
create procedure p10(in n int)
begin
declare total int default 0;
sum: loop
if n<= 0 then
leave sum;
end if;
if n%2 = 1 then
set n := n - 1;
iterate sum;
end if;
set total := total + n;
set n := n - 1;
end loop sum;
select total;
end;
call p10(100);
07-24
3万+
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交