摘要:在本教程中,您将学习如何使用 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
语句允许您终止循环。在LOOP
、 REPEAT
和WHILE
语句中使用LEAVE
语句的一般语法。
将LEAVE
与LOOP
语句一起使用:
[label]: LOOP
IF condition THEN
LEAVE [label];
END IF;
-- statements
END LOOP [label];
Code language: SQL (Structured Query Language) (sql)
将LEAVE
与REPEAT
语句一起使用:
[label:] REPEAT
IF condition THEN
LEAVE [label];
END IF;
-- statements
UNTIL search_condition
END REPEAT [label];
Code language: SQL (Structured Query Language) (sql)
将LEAVE
与WHILE
语句一起使用:
[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
语句退出存储程序或终止循环。
本教程有帮助吗?