Home >Database >Mysql Tutorial >How Does the MySQL LOOP Statement Work and How Can I Exit It Early?

How Does the MySQL LOOP Statement Work and How Can I Exit It Early?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 03:05:09695browse

How Does the MySQL LOOP Statement Work and How Can I Exit It Early?

MySQL LOOP Syntax

In MySQL, a LOOP statement can be used to repeatedly execute a block of code. The correct syntax for a MySQL LOOP is as follows:

LOOP
    -- Code to be executed
END LOOP

To exit the loop early, you can use the LEAVE statement. The LEAVE statement takes a label as an argument. When the LEAVE statement is executed, the loop with the matching label will be exited.

LOOP label1
    -- Code to be executed
    LEAVE label1
END LOOP label1

Example

The following example demonstrates how to use a LOOP statement to iterate through a range of values:

DECLARE i INT DEFAULT 1;
DECLARE max_value INT DEFAULT 10;

LOOP
    SELECT i FROM DUAL;
    SET i = i + 1;
    IF i > max_value THEN
        LEAVE;
    END IF;
END LOOP;

The above is the detailed content of How Does the MySQL LOOP Statement Work and How Can I Exit It Early?. 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