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$


浙公網安備 33010602011771號