MySQL流程控制:根据条件控制SQL代码的执行
1、分支流程语句: if、case 其中case有2种语法形式
2、循环流程语句: while/ loop/ repeat
1.1 分支语句 if
if condition then statement_list;
[elseif condition then statement_list...;]
[else statement_list;]
end if;
根据判断条件 true 执行相应语句:
首先判断if,若成立则执行分支; 不成立则向下执行;
if或elseif都不成立,则执行else;
案例A
查询读者信息表:根据用户余额判断用户的会员等级
要求:根据身份证号查询用户余额:
1、余额>=500 金牌会员;
2、余额>=300 高级会员;
3、余额>=200 普通会员;
4、余额<200 不能借书,显示:余额不足
/* if 示例代码: 定义 level_if() */
delimiter //
create function level_if(cid char(18))
returns varchar(10)
begin
declare lev varchar(10);
declare money decimal(7,3);
select balance into money from readerinfo where card_id=cid;
if money<200 then set lev='余额不足';
elseif money<300 then set lev='普通会员';
elseif money<500 then set lev='高级会员';
else set lev='金牌会员';
end if;
return lev;
end