一、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);