#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);