Home > Database > Mysql Tutorial > What are the loop statements in MySQL?

What are the loop statements in MySQL?

WBOY
Release: 2023-05-26 23:49:46
forward
5674 people have browsed it

There are three commonly used looping methods in MySQL: while, repeat and loop.. There is also a kind of goto, which is not recommended.

What are the loop statements in MySQL?

1.while loop

-- 设置mysql分隔符为//,也就意味着,当遇到下一个//时,整体执行SQL语句
DELIMITER //

DROP PROCEDURE if EXISTS ‘test’;    # 如果存在test存储过程则删除CREATE procedure test() # 创建无参存储过程,名称为testBEGIN
DECLARE i INT;  # 申明变量SET i = 0;  # 变量赋值WHILE i# 结束循环的条件: 当i大于5时跳出while循环
INSERT INTO test VALUES(i+11,'test','20');  # 往test表添加数据SET i = i+1;    # 循环一次,i加1END WHILE;  # 结束while循环SELECT * FROM test; # 查看test表数据END
//  # 结束定义语句CALL test();    # 调用存储过程DELIMITER ; # 重新将分隔符设置为;
Copy after login

2.repeat loop

DELIMITER //
DROP PROCEDURE IF EXISTS test;
CREATE PROCEDURE test()
BEGIN
 DECLARE i INT;
 SET i = 0;
 REPEAT
   INSERT INTO test VALUES(i+11,'test','20');           # 往test表添加数据   SET i = i + 1;                                  # 循环一次,i加一 UNTIL i > 10 END REPEAT;                           # 结束循环的条件: 当i大于10时跳出repeat循环 SELECT * FROM test;
END
//
CALL test();
DELIMITER ;
Copy after login

3.loop loop

DELIMITER //
DROP PROCEDURE IF EXISTS test;
CREATE PROCEDURE test()
BEGIN
 DECLARE i INT;
 SET i = 0;
   lp : LOOP                                   # lp为循环体名,可随意 loop为关键字       INSERT INTO test VALUES(i+11,'test','20');   # 往test表添加数据       SET i = i + 1;                          # 循环一次,i加一       IF i > 10 THEN                       # 结束循环的条件: 当i大于10时跳出loop循环                   LEAVE lp;
           END IF;
   END LOOP;
   SELECT * FROM test;
END
//
CALL test();
DELIMITER ;
Copy after login

The above is the detailed content of What are the loop statements in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template