"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2025-02-03
Browse:135

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;
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3