-
9.1 分支结构
9.1.1 if 函数
语法
# 若表达式1成立,则返回表达式2的值,否则返回表达式3的值
if(表达式1, 表达式2, 表达式3)
9.1.2 if 结构
语法
# 用于begin end中 if 条件1 then 语句1; elseif 条件2 then 语句2; ... else 语句n; end if
使用 ```sql
1 创建函数,根据传入成绩确定等级
90-100 A
80-90 B
60-80 C
0-60 D
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 $
select test_if(86) $
<a name="os5FT"></a>
### 9.1.3 case 结构
- 语法
```sql
# 1 作为表达式(在begin end中/begin end 外)
# 1.1 等值判断
case 变量/表达式/字段
when 判断值 then 返回值1
when 判断值 then 返回值2
...
else 返回值n
end
# 1.2 区间判断
case
when 判断条件1 then 返回值1
when 判断条件2 then 返回值2
...
else 返回值n
end
# 2 作为独立语句(在 begin end中)
# 2.1 等值判断
case 变量/表达式/字段
when 判断值 then 语句1;
when 判断值 then 语句2;
...
else 语句n;
end case;
# 2.2 区间判断
case
when 判断条件1 then 语句1;
when 判断条件2 then 语句2;
...
else 语句n;
end case;
- 使用
```sql
1 创建存储过程,根据传入成绩确定等级
90-100 A
80-90 B
60-80 C
0-60 D
create procedure test_case(in score int) begin case when score>=90 and score<=100 then select ‘A’; when score>=80 then select ‘B’; when score>=60 then select ‘C’; else select ‘D’; end case; end $
call test_case(95) $
<a name="c4kas"></a>
## 9.2 循环结构
while loop repeat
<a name="yDrlT"></a>
### 9.2.1 语法
```sql
# 1 while
【标记:】while 循环条件 do
循环体;
end while 【标记】;
# 2 loop
# 死循环,可用 leave 关键字跳出循环
【标记:】loop
循环体;
end loop 【标记】;
# 3 repeat
【标记:】repeat
循环体;
until 结束条件
end repeat 【标记】;
# 4 iterate:类似 continue
# 5 leave:类似 break
9.2.2 使用
# 1 【循环结构】
# 1.1 【无循环控制】批量插入100条数据到admin表
create procedure test_while1(in insertCount int)
begin
declare i int default 1;
while i<=insertCount do
insert into admin(username password)
values(concat('xy4_',i),'444');
set i=i+1;
end while;
end $
call test_while1(100) $
# 1.2 【leave】批量插入多条数据到admin表,插入条数大于20时停止插入
create procedure test_while2(ininsertCount int)
begin
declare i int default 1;
a:while i<=insertCount do
insert into admin(username password)
values(concat('xy5_',i),'555');
if i>=20 then leave a;
end if;
set i=i+1;
end while a;
end $
call test_while2(100) $
# 1.3 【iterate】批量插入多条数据到admin表,仅插入偶数条目
create procedure test_while3(ininsertCount int)
begin
declare i int default 0;
a:while i<=insertCount do
set i=i+1;
if mod(i,2)!=0 then iterate a;
end if;
insert into admin(username password)
values(concat('xy5_',i),'555');
end while a;
end $
call test_while3(100) $