Home > Database > Mysql Tutorial > mysql while,loop,repeat循环,符合条件跳出循环_MySQL

mysql while,loop,repeat循环,符合条件跳出循环_MySQL

PHP中文网
Release: 2016-05-27 13:46:37
Original
2609 people have browsed it

mysql while,loop,repeat循环,符合条件跳出循环_MySQL

1、while循环

 

DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_test_while`$$
CREATE  PROCEDURE `sp_test_while`(
 IN p_number INT, #要循环的次数
 IN p_startid INT #循环的其实值
)
BEGIN  
DECLARE v_val INT DEFAULT 0;  
SET v_val=p_startid;
outer_label:  BEGIN  #设置一个标记
WHILE v_val<=p_number DO  
    SET v_val=v_val+1;  
    IF(v_val=100)THEN
        LEAVE  outer_label;  #满足条件,终止循环,跳转到end outer_label标记
    END IF;
END WHILE;  
SELECT &lsquo;我是while外,outer_label内的SQL&lsquo;; 
#由于这句SQL在outer_label代码块内,所以level后,这句SQL将不会执行;
#只要是在outer_label代码块内 任意位置 Leave outer_label,那么Leave后的代码将不再执行
END outer_label;   
 SELECT CONCAT(&lsquo;test&lsquo;,v_val) AS tname;
END$$

DELIMITER ;

CALL sp_test_while(1000,0);
Copy after login

2、loop 循环

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_testloop`$$
CREATE  PROCEDURE `sp_testloop`(
 IN p_number INT, #要循环的次数
 IN p_startid INT #循环的其实值
)
BEGIN  
    DECLARE v_val INT DEFAULT 0;  
    SET v_val=p_startid;

    loop_label:  LOOP   #循环开始
        SET v_val=v_val+1; 
         
        IF(v_val>p_number)THEN
            LEAVE  loop_label;  #终止循环
        END IF;
    END LOOP; 
     SELECT CONCAT(&lsquo;testloop_&lsquo;,v_val) AS tname;
END$$

delimiter ;

CALL sp_testloop(1000,0);
Copy after login

3、repeat循环下载地址

DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_test_repeat`$$
CREATE  PROCEDURE `sp_test_repeat`(
 IN p_number INT, #要循环的次数
 IN p_startid INT #循环的其实值
)
BEGIN  
DECLARE v_val INT DEFAULT 0;  
SET v_val=p_startid;

 REPEAT  #repeat循环开始

    SET v_val=v_val+1; 
      until v_val>p_number #终止循环的条件,注意这里不能使用&lsquo;;&lsquo;分号,否则报错     
      
 END repeat; #循环结束 

 SELECT CONCAT(&lsquo;test&lsquo;,v_val) AS tname;
END$$

DELIMITER ;

CALL sp_test_repeat(1000,0);
Copy after login

 

以上就是mysql while,loop,repeat循环,符合条件跳出循环_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template