一、分支结构
1.if函数
实现双分支结构
if (表达式1,表达式2, 表达式3)
如果表达式1成立,则if函数返回表达式2的值,否则返回表达式3的值
2.case结构
- 情况1:类似于Java中的switch语句,一般用于实现等值判断
- 情况2:类似于Java中的多重if分支结构,一般用于实现区间判断
case 要判断的字段或表达式
when 常量1 要显示的值或语句;
when 常量2 要显示的值或语句;
...
else 要显示的值或语句;(相当于default)
end
case
when 条件1 要显示的值或语句;
when 条件2 要显示的值或语句;
...
else 要显示的值或语句;
end
可以作为表达式,嵌套在其它语句中使用,可以放在任何地方
3.if结构
实现多重分支,不同于if函数,只能应用在begin end中
if 条件1 then 语句1
elseif 条件2 then 语句2
...
可选【else 语句n;】
end if;
# 根据传入的成绩,来显示等级,比如传入的成绩:90-100返回A
create function test_if(score INT) returns char
begin
if score>=90 and score<=100 then return 'A'
elseif score>=80 then return 'B'
elseif score>=60 then return 'C'
else return 'D';
end if;
end $
二、循环结构
分类:
- while、loop、repeate
- iterate类似于continue,继续,结束本次循环,继续下一次
- leave类似于break,跳出,结束当前所在的循环
1.while
【标签: 】while 循环条件 do
循环体
end while【标签:】;
# 批量插入多条数据
create procedure pro_while(IN insertCount int)
begin
declare i int default 1;
while i<= insertCount do
insert into admin(username, password) values(concat('rose', i), '666')
set i = i+1
end while;
end $
2.loop
【标签: 】loop
循环体
end loop【标签:】;
# 可以用来模拟死循环
3.repeat
【标签: 】repeat
循环体
until 结束循环的条件
end repeat【标签:】;
# 类似于do while
4.使用leave
# 批量插入多条数据,如果次数大于20停止
create procedure pro_while(IN insertCount int)
begin
declare i int default 1;
a: while i<= insertCount do
insert into admin(username, password) values(concat('rose', i), '666')
if i>=20 then leave a;
set i = i+1
end while a;
end $