Home / MySQL DBMS / Repeat command in Procedure

Repeat command in SPocedure

WHILE Loop

Syntax:

WHILE expression DO
   Statements
END WHILE

Example:

DELIMITER $$
 DROP PROCEDURE IF EXISTS WhileLoopProc$$
 CREATE PROCEDURE WhileLoopProc()
       BEGIN
               DECLARE x  INT;
               DECLARE str  VARCHAR(255);
               SET x = 1;
               SET str =  '';
               WHILE x  <= 5 DO
                           SET  str = CONCAT(str,x,',');
                           SET  x = x + 1; 
               END WHILE;
               SELECT str;
       END$$
   DELIMITER ;


REPEAT Loop

Syntax:

REPEAT
Statements;
UNTIL expression
END REPEAT

Example:

DELIMITER $$
 DROP PROCEDURE IF EXISTS RepeatLoopProc$$
 CREATE PROCEDURE RepeatLoopProc()
       BEGIN
               DECLARE x  INT;
               DECLARE str  VARCHAR(255);
               SET x = 1;
               SET str =  '';
               REPEAT
                           SET  str = CONCAT(str,x,',');
                           SET  x = x + 1; 
               UNTIL x  > 5
               END REPEAT;
               SELECT str;
       END$$
 DELIMITER ;


LOOP loop – LEAVE and ITERATE instructions

The LEAVE command allows you to exit the current loop (similar to break in Java or C#)

The ITERATE command allows the loop to continue (similar to Java or C#'s continue command)

Example: a reference example

DELIMITER $$
 DROP PROCEDURE IF EXISTS LOOPLoopProc$$
 CREATE PROCEDURE LOOPLoopProc()
       BEGIN
               DECLARE x  INT;
               DECLARE str  VARCHAR(255);
               SET x = 1;
               SET str =  '';
               loop_label:  LOOP
                           IF  x > 10 THEN
                                       LEAVE  loop_label;
                           END  IF;
                           SET  x = x + 1;
                           IF  (x mod 2) THEN
                                       ITERATE  loop_label;
                           ELSE
                                       SET  str = CONCAT(str,x,',');
                           END  IF;
                           
               END LOOP;    
               SELECT str;
       END$$

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖