MySQL: REPEAT Statement

MySQL repeat statement

In this guide, we will explain how to use the REPEAT statement (REPEAT UNTIL LOOP) in MySQL with syntax and examples.

Description

In MySQL, the REPEAT statement is used when you do not know how many times you want the loop body to execute.

Syntax

The syntax for the REPEAT statement in MySQL is:

[ label_name: ] REPEAT
   {...statements...}
UNTIL condition
END REPEAT [ label_name ];

Parameters or Arguments

label_nameOptional. It is a name associated with the REPEAT loop statements. The statements of code to execute each pass through the REPEAT loop condition.The condition that will terminate the REPEAT loop.

Note

  • You would use a REPEAT statement when you are unsure of how many times you want the loop body to execute.
  • You terminate a REPEAT statement with the UNTIL condition.

Example

Let’s look at an example that shows how to use the REPEAT statement in MySQL:

DELIMITER //

CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT

BEGIN

   DECLARE income INT;

   SET income = 0;

   label1: REPEAT
     SET income = income + starting_value;
   UNTIL income >= 4000 
   END REPEAT label1;

   RETURN income;

END; //

DELIMITER ;

In this MySQL LOOP example, the REPEAT statement would repeat the loop until income is greater than or equal to 4000, at which point the REPEAT loop would be terminated.

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply