MySql存储过程循环语句使用

2022/5/29 2:20:00

本文主要是介绍MySql存储过程循环语句使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、while循环

1、格式

【标签】while 循环条件 do
      循环体;
end while 【标签】;

 

2、操作

案例一:满足某种条件终止循环

DROP PROCEDURE IF EXISTS proc1;
delimiter $$
create procedure proc1(in in_count int)
begin

  DECLARE i int DEFAULT 1;

    label:while i<=in_count do
    
    if i=6 then     # 当i等于6就终止循环
     LEAVE label;
  end if;
    INSERT into users(user_name,sex) VALUES(CONCAT('用户名','',i),CONCAT('性别','',i));
    
    set i=i+1;
    end while label;
    
end $$ 
delimiter ;


call proc1(10);

案例二:满足某种条件跳过此处循环,并继续执行循环操作

DROP PROCEDURE IF EXISTS proc1;
delimiter $$
create procedure proc1(in in_count int)
begin

  DECLARE i int DEFAULT 0;

    label:while i<in_count do
    set i=i+1;
    if i=6 then     # 当i等于6就跳出此次循环,继续执行
     ITERATE label;
  end if;
    INSERT into users(user_name,sex) VALUES(CONCAT('用户名','',i),CONCAT('性别','',i));
    
    
    end while label;
    
end $$ 
delimiter ;


call proc1(10);

 

 

二、repeat循环

1、格式

【标签】: repeat
     循环体;
until 条件表达式
end repeat 【标签】;

 

2、操作

DROP PROCEDURE IF EXISTS proc1;
delimiter $$
create procedure proc1(in in_count int)
begin

  DECLARE i int DEFAULT 1;

    label:repeat
    INSERT into users(user_name,sex) VALUES(CONCAT('用户名','',i),CONCAT('性别','',i));
    
    set i=i+1;
    UNTIL i>in_count
    end repeat label;
    
end $$ 
delimiter ;


call proc1(10);

 

三、loop循环

1、格式

 

【标签】:loop
   循环体;
 if 条件表达式 then
   leave 【标签】
 end if;
end loop;

 

2、操作

DROP PROCEDURE IF EXISTS proc1;
delimiter $$
create procedure proc1(in in_count int)
begin

  DECLARE i int DEFAULT 0;

    label:loop
    set i=i+1;
    
    if i=5 then
    LEAVE label;
    end if;
    
    INSERT into users(user_name,sex) VALUES(CONCAT('用户名','',i),CONCAT('性别','',i));
    end loop;
    
end $$ 
delimiter ;


call proc1(10);

 



这篇关于MySql存储过程循环语句使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程