当前位置:Gxlcms > 数据库问题 > 009-MySQL循环while、repeat、loop使用

009-MySQL循环while、repeat、loop使用

时间:2021-07-01 10:21:17 帮助过:30人阅读

drop table if exists `test_table`; create table `test_table`( `id` bigint NOT NULL AUTO_INCREMENT COMMENT 自增主键, `modelid` varchar(50) COMMENT 字符主键, `modelname` varchar(50) COMMENT 名称, `desc` varchar(50) COMMENT 描述, primary key (`id`) ) ENGINE=InnoDB charset=utf8 collate=utf8_bin;

1.1、while循环

delimiter //  #定义标识符为双斜杠
DROP PROCEDURE IF EXISTS my_procedure ; #如果存在 my_procedure 存储过程则删除
CREATE PROCEDURE my_procedure () #创建无参存储过程
BEGIN
DECLARE n INT DEFAULT 1 ; #申明变量
WHILE n <= 10 DO     #结束循环的条件:
    insert into test_table (modelid,modelname,`desc`) 
        value (n,CONCAT(name,n),desc);   #处理语句
    SET n = n + 1 ; #循环一次,i加一
END WHILE ; #结束while循环
    select count(*) from test_table;
END
//             
delimiter ;
call my_procedure(); #调用存储过程

1.2、repeat

delimiter //                            #定义标识符为双斜杠
drop procedure if exists my_procedure;          #如果存在test存储过程则删除
create procedure my_procedure()                 #创建无参存储过程,名称为test
begin
    declare n int default 1;                      #申明变量
    # set i = 0;                          #变量赋值
    repeat
        insert into test_table (modelid,modelname,`desc`) 
        value (n,CONCAT(name,n),desc); 
        set n = n + 1;                  #循环一次,i加一
    until n > 10 end repeat;            #结束循环的条件: 当i大于10时跳出repeat循环
    select count(*) from test_table;                 #查看test表数据
end
//                                      #结束定义语句
call my_procedure();                            #调用存储过程

1.3、loop

delimiter //                            #定义标识符为双斜杠
drop procedure if exists my_procedure;          #如果存在test存储过程则删除
create procedure my_procedure()                 #创建无参存储过程,名称为test
begin
    declare i int;                      #申明变量
    set i = 1;                          #变量赋值
    lp : loop                           #lp为循环体名,可随意 loop为关键字
        insert into test_table (modelid,modelname,`desc`) 
        value (i,CONCAT(name,i),desc); 
        set i = i + 1;                  #循环一次,i加一
        if i > 10 then                  #结束循环的条件: 当i大于10时跳出loop循环
            leave lp;
        end if; 
    end loop;
    select count(*) from test_table;                 #查看test表数据
end
//                                      #结束定义语句
call my_procedure();                            #调用存储过程

 

 

 

 

 

009-MySQL循环while、repeat、loop使用

标签:mys   st表   sele   test   def   class   repeat   mysql   roc   

人气教程排行