1. IF 语句
- 语法
1. MySQL内置 if条件语句 (如果表达式为真则执行值1,否则执行值2)
if(条件,值1,值2)
2. if-then-else (只能应用在begin-end中)
if 条件1 then 语句1;
elseif 条件2 then 语句2;
......
else 语句n;
end if
- 代码示例
# 创建存储过程,判断两个输入的参数哪一个更大
create procedure comp (in k1 int, in k2 int, out values char(6) )
begin
if k1>k2 then set k3= '大于';
elseif k1=k2 then set k3= '等于';
else set k3= '小于';
end if;
end
2. CASE语句
- 语法
情况1
case 变量或表达式
when 值1 then 语句1 ;
when 值2 then 语句2 ;
......
else 语句n;
end case;
情况2
case
when 条件1 then 语句1;
when 条件2 then 语句2;
......
else 语句n;
end case;
- 代码示例
# 创建函数并传入分数。如果大于90则返回'A',如果[80,90)则返回'B',如果[60,80)则返货'C',如果小于60则返回'D'
creat function grade(score int) returns char
begin
declare values char(2) default 'D';
case
when score>90 then set values='A';
when score<90 and score>=80 then set values='B';
when score<80 and score>=60 then set values='C';
else score<60 then set values='D';
end case;
end
3. 循环语句
循环语句可以搭配循环控制语句使用。常用的循环控制语句有:
①iterate类似于 continue(终止本次循环继续下次循环)
② leave 类似于 break( 结束当前循环)
3.1 WHILE 语句
- 语法( 先判断条件是否为真再执行语句 )
[begin_label:]
while 条件 do
语句序列
end while [end_label];
- 代码示例
# 传入大于0的数每次-2并返回最后的结果
create function Sub(value int)
begin
while value > 0 do
set value = value-2;
return value;
end while;
end
# 根据传入的参数批量向S表插入多条记录,如果次数>20则停止插入
creat procedure insert_values(in num int )
begin
declare i int default 1;
labela:
while i<num do
insert into S values('20201128','张三','男');
set i=i+1;
if i > 20 then leave labela;
end if;
end while;
end
3.2 REPEAT 语句
- 语法 ( 先执行在判断是否条件为真 )
[begin_label:]
repeat
语句序列
until 结束循环的条件
end repeat [end_label]
- 代码示例
creat procedure insert_values(in num int )
begin
declare i int default 0;
repeat
insert into S values('20201128','张三','男');
set i=i+1;
until i>20;
end repeat;
end
3.3 LOOP 语句
- 语法
[begin_label:]
loop
语句序列
end loop [end_label]
- 代码示例
create procedure doloop()
begin
set @ a=10;
label:
loop
set @ a= @ a-1;
if @ a<0 then leave label;
end if;
end loop label;
end