分支结构
if 函数
效果参考三元运算符
select if(5<10, '大', '小'); -- 大
case 结构
- 作为表达式 → 嵌套在其他语句中使用 → 可以放在任何地方
- 作为独立的语句去使用 → 只能放在
begin
end
中
方法1:效果参考 switch case 语句
case 字段|表达式|变量
when 常量1 then 返回值1 【语句1;】
when 常量2 then 返回值2 【语句2;】
else 默认返回值 【语句n;】 -- else 可以省略
end 【case;】 -- 没有满足的条件则返回 null
eg:查询各部门的总工资
select salary, departmentId,
case departmentId
when 1 then salary*1.1
when 2 then salary*1.2
when 3 then salary*1.3
else salary
end as '总工资'
from `employees`;
方法2:效果参考 if … else if … else 语句
case
when 条件1 then 返回值1 【语句1;】
when 条件2 then 返回值2 【语句2;】
else 默认返回值 【语句n;】 -- else 可以省略
end 【case;】 -- 没有满足的条件则返回 null
eg:查询员工的工资情况
select salary,
case
when salary>20000 then 'A'
when salary>15000 then 'B'
when salary>10000 then 'C'
else 'D'
end as '工资等级'
from `employees`;
eg:创建存储过程,根据传入的成绩来显示等级
delimiter $
create procedure testCase(in score int)
begin
case
when score>=90 then select 'a';
when score>=80 then select 'b';
when score>=60 then select 'c';
else select 'd';
end case;
end $
call testCase(95) $ -- a
if 结构
只能应用在 begin
end
中
if 条件1 then 语句1;
elseif 条件2 then 语句2;
...
[else 语句n;]
end if;
eg:创建函数,根据传入的成绩来显示等级
create function testIf(score int) returns char
begin
if score>=90 then return 'a';
elseif score>=80 then return 'b';
elseif score>=60 then return 'c';
else return 'd';
end if;
end $
select testIf(66)$ -- c
循环结构
注意:只能放在 begin end
语句中
循环控制
iterate
→continue
leave
→break
while
先判断,后执行
while 循环条件 do
循环体;
end while;
如果要搭配循环控制,要给循环语句起标签名
标签: while 循环条件 do
循环体;
end while 标签;
loop
[标签:] loop
循环体;
end loop [标签];
loop
没有 循环条件
,所以要搭配 循环控制
使用;否则就是死循环
repeat
先执行后判断
[标签:] repeat
循环体;
until 结束循环的条件
end repeat [标签];
类比
do ... while ...
案例
eg:批量插入,根据次数插入到 employees 表中多条记录
delimiter $
create procedure pro_while(in insertCount int)
begin
declare i int default 1; -- 定义局部变量并初始化
while i <= insertCount do
insert into `employees`(`eName`, `id`) values(concat('rose', i), '666');
set i = i + 1; -- 循环变量更新
end while;
end $
call pro_while(100)$
eg:批量插入,根据次数插入到 employees 表中多条记录,如果次数 >20 则停止
delimiter $
create procedure pro_while(in insertCount int)
begin
declare i int default 1;
a: while i <= insertCount do
insert into `employees`(`eName`, `id`) values(concat('rose', i), '666');
if i >= 20 then leave a; -- leave 控制语句
end if;
set i = i + 1; -- 循环变量更新
end while a;
end $