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
Release: 2024-12-20 03:05:09
Original
638 people have browsed it

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
Copy after login

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
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template