一,if判断

1,语法:

if 条件 then
 			……
 elseif 条件 then	# 可选
 			……
 else				# 可选
 			……
 end if;

2,案例:
定义一个存储过程,完成如下需求:根据定义的价格price变量,判断当前价格对应的等级
price >= 10000 等级为很贵
price >= 5000 且price<10000 等级为一般
price < 5000 等级为便宜

# 定义一个存储过程,完成如下需求:根据定义的价格price变量,判断当前价格对应的等级
# 1,price >= 10000 等级为很贵
# 2,price >= 5000 且price<10000 等级为一般
# 3,price < 5000  等级为便宜
create procedure p_Lvprice()
begin
    declare cst decimal default 0;
    declare say varchar(3) ;
    select price into cst from dish where name = '辣子鸡';
    if cst < 5000 then
         set say := '便宜';
    elseif cst < 10000 then
        set say := '一般';
    else
        set say := '很贵';
    end if;
    select say;
end;
call p_Lvprice();

二,参数

mysql 存储过程 对字段值的判断 mysql存储过程条件判断_存储过程


1,用法:

create procedure 存储过程名 ([in/out/inout 参数名 参数类型])
begin
	--sql语句
end;

2,练习
①根据传入(in)的参数cst,判断当前价格对应的等级,并返回(out
price >= 10000 等级为很贵
price >= 5000 且price<10000 等级为一般
price < 5000 等级为便宜

#根据传入(`in`)的参数price,判断当前价格对应的等级,并返回(`out`)
#price >= 10000 等级为很贵
#price >= 5000 且price<10000 等级为一般
#price < 5000  等级为便宜
create procedure p_Lvprice2(in cst decimal,out say varchar(3))
begin
    if cst < 5000 then
         set say := '便宜';
    elseif cst < 10000 then
        set say := '一般';
    else
        set say := '很贵';
    end if;
end;

call p_Lvprice2(15000,@print);
select @print;

②将传入的200分制的分数,进行换算成百分制,然后返回 inout

# 将传入的200分制的分数,进行换算成百分制,然后返回 inout
create procedure p3(inout score double)
begin
    set score := score * 0.5;
end;

set @res = 198; # 赋值
call p3(@res); # 定义变量,为了拿到返回值  调用完毕之后,存储过程p3会将计算完成的结果再次赋值给res
select @res; # 查询

三,case

语法一:

case 表达式
	when 表达式的值为它 then 执行它的sql语句
	[when 表达式的值为它 then 执行它的sql语句]...
	[else 否则执行这里的语句]
end case;

语法二:

case
	when 条件表达式 then 如果成立执行这里的sql
	[when 条件表达式 then 如果成立执行这里的sql]...
	[else 否则执行这里的语句]
end case;

练习:
根据传入的月份,判定月份所属的季节(要求采用case结构)
1-3月份 为第一季度
4-6月份 为第二季度
7-9月份 为第三季度
10-12月份 为第四季度

# 根据传入的月份,判定月份所属的季节(要求采用case结构)
# 1-3月份	为第一季度
# 4-6月份	为第二季度
# 7-9月份	为第三季度
# 10-12月份	为第四季度
create procedure p4(in month int)
begin
    declare res varchar(10);
    case
        when month >= 1 and  month <= 3 then set res := '第一季度';
        when month >= 4 and  month <= 6 then set res := '第二季度';
        when month >= 7 and  month <= 9 then set res := '第三季度';
        when month >= 10 and  month <= 12 then set res := '第四季度';
        else set res = '非法输入';
    end case;

    select concat('您输入的月份为:',month,'所属的季度为:',res);
end;

call p4(51);