0

表校验

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和结束的 while 循环2,我的输出是否只在目标表中循环了两次。我希望看到它重复8次。你能帮忙吗?

4

2 回答 2

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 ;
于 2013-05-20T13:23:02.703 回答
0

我认为这与您的处理程序有关。SET done = FALSE 关闭光标后尝试添加 。

== 编辑 ==

一般来说,你应该避免像瘟疫这样的游标。

您可以使用“数字”表执行此操作

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 表中添加值,以根据需要任意复制数据。

于 2013-05-20T13:06:13.447 回答