对于MySQL中的循环例子

在MySQL中,我有这个存储过程中有一个For循环:

DELIMITER $$ CREATE PROCEDURE ABC() BEGIN DECLARE a INT Default 0 ; simple_loop: LOOP SET a=a+1; select a; IF a=5 THEN LEAVE simple_loop; END IF; END LOOP simple_loop; END $$ 

它总是打印1 。 什么是MySQL for循环的正确语法?

 drop table if exists foo; create table foo ( id int unsigned not null auto_increment primary key, val smallint unsigned not null default 0 ) engine=innodb; drop procedure if exists load_foo_test_data; delimiter # create procedure load_foo_test_data() begin declare v_max int unsigned default 1000; declare v_counter int unsigned default 0; truncate table foo; start transaction; while v_counter < v_max do insert into foo (val) values ( floor(0 + (rand() * 65535)) ); set v_counter=v_counter+1; end while; commit; end # delimiter ; call load_foo_test_data(); select * from foo order by id; 

在MySQL中循环语法的例子:

 delimiter // CREATE procedure yourdatabase.while_example() wholeblock:BEGIN declare str VARCHAR(255) default ''; declare x INT default 0; SET x = 1; WHILE x <= 5 DO SET str = CONCAT(str,x,','); SET x = x + 1; END WHILE; select str; END// 

打印:

 mysql> call while_example(); +------------+ | str | +------------+ | 1,2,3,4,5, | +------------+ 

MySQL中的REPEAT循环语法示例:

 delimiter // CREATE procedure yourdb.repeat_loop_example() wholeblock:BEGIN DECLARE x INT; DECLARE str VARCHAR(255); SET x = 5; SET str = ''; REPEAT SET str = CONCAT(str,x,','); SET x = x - 1; UNTIL x <= 0 END REPEAT; SELECT str; END// 

打印:

 mysql> call repeat_loop_example(); +------------+ | str | +------------+ | 5,4,3,2,1, | +------------+ 

在MySQL中FOR循环语法示例:

 delimiter // CREATE procedure yourdatabase.for_loop_example() wholeblock:BEGIN DECLARE x INT; DECLARE str VARCHAR(255); SET x = -5; SET str = ''; loop_label: LOOP IF x > 0 THEN LEAVE loop_label; END IF; SET str = CONCAT(str,x,','); SET x = x + 1; ITERATE loop_label; END LOOP; SELECT str; END// 

打印:

 mysql> call for_loop_example(); +-------------------+ | str | +-------------------+ | -5,-4,-3,-2,-1,0, | +-------------------+ 1 row in set (0.00 sec) 

做这个教程: http : //www.mysqltutorial.org/stored-procedures-loop.aspx

如果我抓住你把这种MySQL for-loop结构投入生产,我会用泡沫导弹发射器来拍摄你。 你可以用一个pipe子扳手敲钉子,但这样做会让你看起来很傻。

假设你有一个名字为“table1”的表。 它包含一个varchartypes的列“col1”。 查询到箱表如下

 CREATE TABLE `table1` ( `col1` VARCHAR(50) NULL DEFAULT NULL ) 

现在,如果要在该表中插入1到50之间的数字,请使用以下存储过程

 DELIMITER $$ CREATE PROCEDURE ABC() BEGIN DECLARE a INT Default 1 ; simple_loop: LOOP insert into table1 values(a); SET a=a+1; IF a=51 THEN LEAVE simple_loop; END IF; END LOOP simple_loop; END $$ 

调用该存储过程使用

 CALL `ABC`()