MySQL LEAVE语句
时间:2019-11-20 08:52:31 来源:igfitidea点击:
简介:在本教程中,您将学习如何使用MySQL LEAVE语句退出存储的程序或终止循环。
MySQL LEAVE语句简介
LEAVE语句退出具有给定标签的流控制。
下面显示了LEAVE语句的基本语法:
LEAVE label;
使用这种语法,您可以在LEAVE关键字之后指定要退出的块的标签。
使用LEAVE语句退出存储过程
如果标签在存储过程或功能块的最外面,则LEAVE终止存储过程或功能。
以下语句显示如何使用LEAVE语句退出存储过程:
CREATE PROCEDURE sp_name()
sp: BEGIN
IF condition THEN
LEAVE sp;
END IF;
-- other statement
END$$
例如,以下语句创建一个新的存储过程,该过程检查示例数据库中的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 ;
在循环中使用LEAVE语句
LEAVE语句允许您终止循环。
在LOOP,REPEAT和WHILE语句中使用时,LEAVE语句的一般语法。
将LEAVE与LOOP语句一起使用:
[label]: LOOP
IF condition THEN
LEAVE [label];
END IF;
-- statements
END LOOP [label];
将LEAVE与REPEAT语句一起使用:
[label:] REPEAT
IF condition THEN
LEAVE [label];
END IF;
-- statements
UNTIL search_condition
END REPEAT [label];
将LEAVE与WHILE语句一起使用:
[label:] WHILE search_condition DO
IF condition THEN
LEAVE [label];
END IF;
-- statements
END WHILE [label];
LEAVE使标签指定的电流循环终止。
如果一个循环包含在另一个循环中,则可以使用单个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 ;
该语句调用LeaveDemo过程:
CALL LeaveDemo(@result); SELECT @result;
这是输出之一:
+------------------+ | @result | +------------------+ | 1,2,3,4,5,6,7,8, | +------------------+ 1 row in set (0.00 sec)
在本教程中,您学习了如何使用MySQL LEAVE语句退出存储的程序或终止循环。

