MySQL存储过程的控制语句~循环语句+迭代语句

#while循环语句
#首先判断条件是否成立,如果成立,则执行循环体#while循环输出100个随机数

drop procedure proc_test
create procedure proc_test(in rows int)
begin 
declare test_val double;

    create table test(
        id int primary key auto_increment,
        val varchar(20)
    );
    
    while rows>0 do
    
        select RAND() into test_val;
        insert into test(val) values(test_val);
        set rows=rows-1;
                
    end while;
    
    select* from test;
end;

call proc_test(100);

#loop循环语句
#不需判断初始条件,直接执行循环体
#碰到levae语句,退出循环#案例 批量插入3个信的检查项目,检查项目名称为'胃镜 肠镜和支气管纤维镜 各项检查的价格均为70元'
#实例一
#substr() substring_index() char_length() 用法

drop procedure if exists proc_checkItem
create procedure proc_checkItem(in checkitems varchar(50))
begin
declare sub_str varchar(20);
loop_label:loop

    set sub_str=substring_index(checkitems,',',1);
    set checkitems=substr(checkitems,char_length(sub_str)+2);
    
    
    insert into checkitem(checkItemName,checkItemcost) values (sub_str,70);
    if char_length(checkitems)<=0 then leave loop_label;
    end if;
    
    
end loop loop_label;
end;

call proc_checkItem('胃镜,肠镜,支气管纤维镜,');
select * from checkitem

#实例二
#locate() substr() 用法

drop procedure if exists proc_checkItem
create procedure proc_checkItem(in checkitems varchar(50))
begin
declare sub_str varchar(20);
declare sub_pos int;
    loop_label:loop
    
        set sub_pos=LOCATE(',',checkitems)
        set sub_str=SUBSTR(checkitems,1,sub_pos-1);
        
        if sub_str !='' then set checkitems=substr(checkitems,sub_pos+1);
        else set sut_str=checkitems;
        end if;
        
        insert into checkitem(checkItemName,checkItemCost) values(sub_str,70);
        
        if stu_pos=0 or stu_str='' then leave loop_label;
        end if;
        
    end loop loop_lable;
end;

call proc_checkItem('胃镜,肠镜,支气管纤维镜,');
select * from checkitem

#repeat循环语句
#与java中的do-while循环语句类似
#与loop循环语句比较
#相同点:不需要初始条件直接进入循环体
#不同点:repeat语句可以设置退出条件

#案例 根据输入的行数要求,向测试表test中插入测试数据
#输入需要增加数据行数,随机产生的测试数据必须大于0.5

 #iterate迭代语句

#关键字可以镶嵌到loop while repeat程序块中

drop procedure proc_test
create procedure proc_test(in rows int)
begin 
declare rand_val double;
    loop_label:while rows>0 do
        select rand() into rand_val;
        if rand_val<0.5 then iterate loop_label;
        end if;
        insert into proc_test values(null,rand_val);
        set rows=rows-1;
    end while loop_label;
end;

call proc_test(100);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[微信紅包]恭喜发財,大吉大利!

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值