MySQL循环语句概述与类型
MySQL数据库的操作中同样包含循环语句功能。网络上通常提及三种标准的循环模式:while循环、loop循环以及repeat循环。此外还存在一种非标准的goto语句。由于goto语句的跳转特性容易导致编程逻辑混乱,因此在实际开发中并不推荐使用。
上述几种循环语句的基本语法格式分别如下:WHILE……DO……END WHILE;REPEAT……UNTIL END REPEAT;LOOP……END LOOP;以及GOTO。
While循环测试与Delimeter用法
目前仅针对while循环进行了实际测试验证。
delimiter $$ // 定义结束符为 $$
drop procedure if exists wk; // 删除 已有的 存储过程
create procedure wk() // 创建新的存储过程
begin
declare i int; // 变量声明
set i = 1;
while i < 11 do // 循环体
insert into user_profile (uid) values (i);
set i = i +1;
end while;
end $$ // 结束定义语句
// 调用
delimiter ; // 先把结束符 回复为;
call wk();
在MySQL中,默认的定界符(delimiter)是分号(;)。它用于告知MySQL解释器当前命令段是否已经结束,从而决定是否可以执行该命令。
此处使用delimiter关键字重新定义结束符的主要目的是防止存储过程中的内部语句在定义阶段被提前执行或输出。
创建MySQL存储过程的基础语法结构为:
CREATE PROCEDURE 存储过程名称( [in | out | inout] 参数 )
BEGIN
Mysql 语句
END
调用已创建的存储过程方法如下:
call 存储过程名称() // 名称后面要加()
Repeat循环实现示例
二 、 REPEAT 循环
delimiter //
drop procedure if exists looppc;
create procedure looppc()
begin
declare i int;
set i = 1;
repeat
insert into user_profile_company (uid) values (i+1);
set i = i + 1;
until i >= 20
end repeat;
end //
---- 调用
call looppc()
Loop循环实现示例
三、 LOOP 循环
delimiter $$
drop procedure if exists lopp;
create procedure lopp()
begin
declare i int ;
set i = 1;
lp1 : LOOP // lp1 为循环体名称 LOOP 为关键字insert into user_profile (uid) values (i);
set i = i+1;
if i > 30 then
leave lp1; // 离开循环体
end if;
end LOOP; // 结束循环
end $$