MySQL-流程控制语句

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 变量或表达式
when1 then 语句1 ;
when2 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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值