Home  >  Article  >  Database  >  How is the MySQL REPEAT loop statement used in a stored procedure?

How is the MySQL REPEAT loop statement used in a stored procedure?

王林
王林forward
2023-09-06 09:41:081088browse

MySQL REPEAT循环语句如何在存储过程中使用?

As we all know, MySQL provides us with loop statements that allow us to repeatedly execute SQL code blocks based on conditions. REPEATThe loop statement is one such loop statement. The syntax is as follows -

REPEAT
   statements;
UNTIL expression
END REPEAT

First, MySQL executes the statement and then evaluates the expression. If the expression evaluates to FALSE, MySQL executes the statement repeatedly until the expression evaluates to TRUE. REPEAT The loop checks the expression after executing the statement, which is why it is called a post-test loop.

To demonstrate the usage of a REPEAT loop using a stored procedure, here is an example:

mysql> Delimiter //
mysql> CREATE PROCEDURE Repeat_Loop()
   -> BEGIN
   -> DECLARE A INT;
   -> DECLARE XYZ Varchar(50);
   -> SET A = 1;
   -> SET XYZ = '';
   -> REPEAT
   -> SET XYZ = CONCAT(XYZ,A,',');
   -> SET A = A + 1;
   -> UNTIL A > 10
   -> END REPEAT;
   -> SELECT XYZ;
   -> END //
Query OK, 0 rows affected (0.04 sec)

Now, when we call this procedure, we can see below Result−

mysql> DELIMITER ;
mysql> CALL Repeat_Loop();
+-----------------------+
| XYZ                   |
+-----------------------+
| 1,2,3,4,5,6,7,8,9,10, |
+-----------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

The above is the detailed content of How is the MySQL REPEAT loop statement used in a stored procedure?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete