Home >Database >Mysql Tutorial >How to Correctly Implement FOR and WHILE Loops in MySQL Stored Procedures?

How to Correctly Implement FOR and WHILE Loops in MySQL Stored Procedures?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 10:55:12708browse

How to Correctly Implement FOR and WHILE Loops in MySQL Stored Procedures?

Understanding MySQL's FOR Loop

In MySQL, the FOR loop is an iterative statement used to execute a block of code multiple times. It allows you to iterate through a sequence of values or rows in a table.

Error in the Provided Stored Procedure

The provided stored procedure has an incorrect FOR loop syntax. The correct syntax for a FOR loop in MySQL is as follows:

FOR loop_variable IN expression1, expression2, ...
LOOP
  -- loop body
END LOOP;

Corrected Stored Procedure

The corrected version of the stored procedure with a properly implemented FOR loop:

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 0 ;
      FOR i IN 1..5 LOOP
         SET a=a+1;
         select a;
      END LOOP;
END $$
DELIMITER ;

In this example, the FOR loop iterates from 1 to 5, incrementing a by 1 each iteration. The loop terminates when i reaches 6.

Alternative Loop Syntax: WHILE LOOP

In addition to the FOR loop, MySQL provides a WHILE loop, another iterative statement that executes a block of code while a specified condition is true. Its syntax is as follows:

WHILE condition LOOP
  -- loop body
END LOOP;

Example:

WHILE a < 10 LOOP
  SET a=a+1;
  select a;
END LOOP;

This WHILE loop will continue to execute until a reaches 10.

The above is the detailed content of How to Correctly Implement FOR and WHILE Loops in MySQL Stored Procedures?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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