在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 $$
Run Code Online (Sandbox Code Playgroud)
它总是打印1.MySQL for循环的正确语法是什么?
Jon*_*ack 135
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;
Run Code Online (Sandbox Code Playgroud)
Eri*_*ski 53
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//
Run Code Online (Sandbox Code Playgroud)
哪个印刷品:
mysql> call while_example();
+------------+
| str |
+------------+
| 1,2,3,4,5, |
+------------+
Run Code Online (Sandbox Code Playgroud)
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//
Run Code Online (Sandbox Code Playgroud)
哪个印刷品:
mysql> call repeat_loop_example();
+------------+
| str |
+------------+
| 5,4,3,2,1, |
+------------+
Run Code Online (Sandbox Code Playgroud)
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//
Run Code Online (Sandbox Code Playgroud)
哪个印刷品:
mysql> call for_loop_example();
+-------------------+
| str |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
做教程:http://www.mysqltutorial.org/stored-procedures-loop.aspx
如果我抓住你将这种MySQL for-loop结构推向生产,我将用泡沫导弹发射器射击你.你可以用管钳敲打钉子,但这样做会使你看起来很傻.
Fat*_*n P 12
假设您有一个名为'table1'的表.它包含一个带有varchar类型的列'col1'.查询包装箱表如下
CREATE TABLE `table1` (
`col1` VARCHAR(50) NULL DEFAULT NULL
)
Run Code Online (Sandbox Code Playgroud)
现在,如果要在该表中插入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 $$
Run Code Online (Sandbox Code Playgroud)
要调用该存储过程使用
CALL `ABC`()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
440419 次 |
| 最近记录: |