表格检查
val
----
5705
5704
5703
5702
5701
存储过程
BEGIN
DECLARE x INT;
DECLARE done INT DEFAULT FALSE;
DECLARE myType INT;
DECLARE cur1 CURSOR FOR select val from checkval;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET x = 10;
WHILE x >= 2 DO
##############
OPEN cur1;
read_loop: LOOP
IF done THEN
LEAVE read_loop;
END IF;
FETCH cur1 INTO myType;
insert into myType values (myType);
END LOOP read_loop;
CLOSE cur1;
SET x = x-1;
##################
END WHILE;
END
当前输出
5705
5704
5703
5702
5701--Loops only twice
5705
5704
5703
5702
5701
所需输出
5705 - Loops 8 times
5704
5703
5702
5701
5705
5704
5703
5702
5701
5705
5704
5703
5702
5701
5705
5704
5703
5702
5701
5705
5704
5703
5702
5701
5705
5704
5703
5702
5701
5705
5704
5703
5702
5701
5705
5704
5703
5702
5701
为什么即使我指定从10
开始到2
开始的while循环,我是否只在目标表中循环输出两次。我希望看到它重复8次。你能帮忙吗?
答案 0 :(得分:1)
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `fred`$$
CREATE DEFINER=`root`@`windows7.home` PROCEDURE `fred`()
BEGIN
DECLARE X INT;
DECLARE done INT DEFAULT FALSE;
DECLARE myType INT;
DECLARE cur1 CURSOR FOR SELECT val FROM checkval;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET X = 10;
WHILE X >= 2 DO
##############
OPEN cur1;
FETCH cur1 INTO myType;
read_loop: LOOP
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO myType VALUES (myType);
FETCH cur1 INTO myType;
END LOOP read_loop;
CLOSE cur1;
SET X = X-1;
SET done=FALSE;
##################
END WHILE;
END$$
DELIMITER ;
答案 1 :(得分:0)
我认为这与您的处理程序有关。尝试添加
SET done = FALSE
关闭光标后。
==编辑==
一般来说,你应该避免瘟疫之类的游标。
您可以使用"Numbers" Table
执行此操作create table Numbers (Number int);
insert into Numbers (Number) values (1);
insert into Numbers (Number) values (2);
insert into Numbers (Number) values (3);
insert into Numbers (Number) values (4);
insert into Numbers (Number) values (5);
insert into Numbers (Number) values (6);
insert into Numbers (Number) values (7);
insert into Numbers (Number) values (8);
select val from checkval cross join Numbers
where Numbers.Number between 1 and 8;
请参阅此SQL Fiddle。
您可以向Numbers表中添加值,以便根据需要随意复制数据。