9

我的 SQL:

CREATE PROCEDURE INV_MIN_PURCHASE_PRICE()
BEGIN
DECLARE done INT;
DECLARE current_inventory_ID INT;
DECLARE cur1 CURSOR FOR SELECT inventory_ID FROM _inventory;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

SET done = 0;
OPEN cur1;

REPEAT

    FETCH cur1 INTO current_inventory_ID;
    UPDATE _debug SET rows=rows+1;

UNTIL done
END REPEAT;

CLOSE cur1;

END;

当我调用这个过程时,MySQL 只获取一行(_debugrows增加了 1)。为什么??它是一个错误吗?

4

3 回答 3

16

我在 MySQL 中的存储过程也遇到了同样的问题。它应该从一个表中获取某个列中具有空值的所有记录,然后从另一个表中填充该值。然而,它在一个记录后停止了:

CREATE PROCEDURE `updateRecord`()
    BEGIN

    DECLARE done INT DEFAULT FALSE;
    DECLARE recordId, newValue INT;
    DECLARE current_record CURSOR FOR SELECT id FROM A where b_id is null;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

    OPEN current_record;

    main_loop: LOOP
        FETCH current_record INTO recordId;

        IF done THEN
             LEAVE main_loop;
        END IF;

        -- fetching some value from table b
        select id into newValue from B where ...

       -- setting new value in record
       update A set b_id = newValue where id = recordId;    

      END LOOP;
    END

答案是“未找到的处理程序”不仅在游标未返回任何行时执行,而且在表 B 上的选择未返回任何行时执行。我的解决方案是使用由处理程序设置的第二个变量,并在选择后重置“完成”变量:

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE, noBfound = TRUE;    

           [...]

           select id into newValue from B where ...

           IF (noBfound = TRUE) THEN 
               SET done = FALSE;
           END IF;

           [...]

加法:显然可以通过在选择后简单地重置“完成”来不使用第二个变量:

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

           [...]

           select id into newValue from B where ...

           SET done = FALSE;

           [...]
于 2013-01-17T17:11:02.113 回答
0

Have you tried a LOOP instead of the REPEAT construct? Seems to work better in MySQL. Replace the REPEAT to END REPEAT section with:

inv_loop: LOOP
    FETCH cur1 INTO current_inventory_ID;
    IF done = 1 THEN
        LEAVE inv_loop;
    END IF;
    UPDATE _debug SET rows=rows+1;
END LOOP;
于 2012-08-18T10:54:46.440 回答
0
IF done THEN
         LEAVE main_loop;
ELSE
         ITERATE main_loop;
END IF;
于 2014-02-24T05:59:38.153 回答