MySQL LEAVE

摘要:在本教程中,您将学习如何使用 MySQL LEAVE语句退出存储程序或终止循环。

MySQL LEAVE语句简介

LEAVE语句退出具有给定标签的流控制。

下面显示了LEAVE语句的基本语法:

LEAVE label;
Code language: SQL (Structured Query Language) (sql)

在此语法中,您可以在LEAVE关键字之后指定要退出的块的标签。

使用LEAVE语句退出存储过程

如果label存储过程函数块的最外层, LEAVE终止存储过程或函数。

以下语句显示如何使用LEAVE语句退出存储过程:

CREATE PROCEDURE sp_name()
sp: BEGIN
    IF condition THEN
        LEAVE sp;
    END IF;
    -- other statement
END$$
Code language: SQL (Structured Query Language) (sql)

例如,此语句创建一个新的存储过程,用于检查示例数据库中的customers表中给定客户的信用:

DELIMITER $$

CREATE PROCEDURE CheckCredit(
    inCustomerNumber int
)
sp: BEGIN
    
    DECLARE customerCount INT;

    -- check if the customer exists
    SELECT 
        COUNT(*)
    INTO customerCount 
    FROM
        customers
    WHERE
        customerNumber = inCustomerNumber;
    
    -- if the customer does not exist, terminate
    -- the stored procedure
    IF customerCount = 0 THEN
        LEAVE sp;
    END IF;
    
    -- other logic
    -- ...
END$$

DELIMITER ;
Code language: SQL (Structured Query Language) (sql)

在循环中使用LEAVE语句

LEAVE语句允许您终止循环。在LOOPREPEATWHILE语句中使用LEAVE语句的一般语法。

LEAVELOOP语句一起使用:

[label]: LOOP
    IF condition THEN
        LEAVE [label];
    END IF;
    -- statements
END LOOP [label];
Code language: SQL (Structured Query Language) (sql)

LEAVEREPEAT语句一起使用:

[label:] REPEAT
    IF condition THEN
        LEAVE [label];
    END IF;
    -- statements
UNTIL search_condition
END REPEAT [label];
Code language: SQL (Structured Query Language) (sql)

LEAVEWHILE语句一起使用:

[label:] WHILE search_condition DO
    IF condition THEN
        LEAVE [label];
    END IF;
    -- statements
END WHILE [label];
Code language: SQL (Structured Query Language) (sql)

LEAVE导致label指定的当前循环终止。如果一个循环包含在另一个循环中,则可以使用单个LEAVE语句打破这两个循环。

在循环中使用LEAVE语句示例

以下存储过程生成一个整数字符串,其数字从 1 到 4 到 10 之间的随机数:

DELIMITER $$

CREATE PROCEDURE LeaveDemo(OUT result VARCHAR(100))
BEGIN
    DECLARE counter INT DEFAULT 1;
    DECLARE times INT;
    -- generate a random integer between 4 and 10
    SET times  = FLOOR(RAND()*(10-4+1)+4);
    SET result = '';
    disp: LOOP
        -- concatenate counters into the result
        SET result = concat(result,counter,',');
        
        -- exit the loop if counter equals times
        IF counter = times THEN
            LEAVE disp; 
        END IF;
        SET counter = counter + 1;
    END LOOP;
END$$

DELIMITER ;
Code language: SQL (Structured Query Language) (sql)

此语句调用LeaveDemo过程:

CALL LeaveDemo(@result);
SELECT @result;
Code language: SQL (Structured Query Language) (sql)

这是输出之一:

+------------------+
| @result          |
+------------------+
| 1,2,3,4,5,6,7,8, |
+------------------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

在本教程中,您学习了如何使用 MySQL LEAVE语句退出存储程序或终止循环。

本教程有帮助吗?