zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MySQL存储过程-循环结构

mysql循环存储 过程 结构
2023-06-13 09:14:25 时间

测试表结构如下,使用存储过程的三种循环结构向表中插入数据。

create table tb
(
    type varchar(20)  not null,
    name varchar(255) not null,
    id   varchar(20)  not null,
    primary key (type, id),
    constraint index1
        unique (name)
);

三种循环结构为: loop……end loop while……do……end while repeat……until…end repeat

1、loop

create procedure insertData()
begin
    declare i int default 0;
    loop_label:
    loop
        insert into tb values (i, concat('test', i), i);
        set i = i + 1;
        if i > 100 then
            leave loop_label;
        end if;
    end loop;
end;
  • 使用loop时,需要在其内部嵌套if语句和leave语句,才能在满足条件时离开循环。leave格式:leave 循环标号,循环标号自定义即可。

2、while

create procedure insertData()
begin
    declare i int default 0;
    while i < 100
        do
            insert into tb values (i, concat('test', i), i);
            set i = i + 1;
        end while;
end;

3、repeat

create procedure insertData()
begin
    declare i int default 0;
    repeat
        insert into tb values (i, concat('test', i), i);
        set i = i + 1;
    until i > 100
        end repeat;
end;
  • repeat在执行后检查是否满足循环条件(until i > 100),而while则是执行前检查(while i < 100 do)。所以用while写的存过会插入100条数据,用repeat写的则会插入101条数据。
  • utitl i > 100 后没有分号,否则报语法错误。

Q.E.D.