sql提高 循环结构
循环结构
分类:
while、loop、repeat
——对应java中:for、while、do while
循环控制:
iterate 类似于 continue ,继续, 结束本次循环,继续下一次循环
leave 类似于 break, 跳出, 结束当前所在的循环
1.while
语法:
【标签:】 while 循环条件 do 循环体;
end while;
联想:
while(循环条件) { 循环体 };
2.loop
语法:
【标签:】 loop
循环体;
end loop 【标签】;
可以用来描述简单的死循环
3.repeat
语法:
【标签:】repeat
循环体;
until 结束循环的条件
end repeat 【标签】;
#案例:批量插入,根据次数插入到admin表中多条记录
create procedure pro_while1(in insertCount int)
begin
declare i int default 1;
while i <= insertCount do
insert into admin(username, password) values (concat('Rose', i), '666');
set i = i + 1;
end while;
end $
call pro_while1(10)$
select count(*) from admin$
#添加leave语句
#案例:批量插入,根据次数插入到admin表中多条记录,如果次数大于20则停止
truncate table admin$
drop procedure pro_while1$
create procedure pro_while1(in insertCount int)
begin
declare i int default 0;
a:while i <= insertCount do
set i = i + 1;
if i > 20 then leave a;
end if;
if i <= 10 then iterate a;
end if;
insert into admin(username, password) values (concat('Rose', i), '666');
end while a;
end $
call pro_while1(30)$
select count(*) from admin$
#案例1:已知表stringcontent
其中字段:
id 自增长
content varchar(20)
向改表插入指定个数的随机字符串:
drop table if exist stringcontent$
create table stringcontent (
id int primary key auto_increment,
content varchar(20)
)$
create procedure test_randstr_insert(in insertcount int)
begin
declare i int default 1;
declare str varchar(26) default 'abcdefghijklmnopqrstuvwxyz'; #被截取的字符串
declare startindex int default 1; #截取字符串的起始索引
declare len int default 1; #截取字符串的长度
while i < insertcount do
set startindex = ceil(rand() * 26);
set len = ceil(rand() * 7);
insert into stringcontent(content) values(substr(str, startindex, len));
set i = i + 1;
end while;
end $
call test_randstr_insert(30)$
select * from stringcontent$