2

我有一个存储过程,它检查一个表中的行以将其详细信息插入另一个表。我正在使用游标,但我有一个大问题:游标在同一行上循环 2 次。所以我得到了 2 个重复插入。这是sp代码:

    IF (SELECT 1 FROM NOVEDADES  WHERE LEGAJO_ID = pLEGAJO_ID AND FECHA >= pFECHA AND CONCEPTO_ID != 11 AND CONCEPTO_ID != 13 AND CONCEPTO_ID != 12 LIMIT 1) = 1
    THEN
        BEGIN
        DECLARE vCONCEPTO_ID INT;
        DECLARE vMONTO DECIMAL(12,2);
        DECLARE vID INT;
        DECLARE vDONE INT DEFAULT 0;

        DECLARE CURSOR_NOVEDADES CURSOR FOR     

        SELECT ID
        FROM NOVEDADES 
        WHERE LEGAJO_ID = pLEGAJO_ID
        AND FECHA >= pFECHA
        AND CONCEPTO_ID != 11 
        AND CONCEPTO_ID != 13 
        AND CONCEPTO_ID != 12;

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDONE=1;

        OPEN CURSOR_NOVEDADES;

        SET vDONE = 0;

        REPEAT

            FETCH CURSOR_NOVEDADES INTO vID;

            SELECT CONCEPTO_ID, MONTO INTO vCONCEPTO_ID, vMONTO
            FROM NOVEDADES WHERE ID = vID;

            INSERT INTO LIQUIDACIONES_DETALLE (LIQUIDACION_ID, CONCEPTO_ID, MONTO)
            VALUES(pLIQUIDACION_ID, vCONCEPTO_ID, vMONTO);

        UNTIL vDONE END REPEAT;
        CLOSE CURSOR_NOVEDADES;
        END;
    END IF;

以“p”开头的变量是IN参数,“v”是公共变量。我必须说游标的查询只返回 1 个值。我也尝试过 LOOP,但结果相同。我试过“调试”插入一些 SELECTS 的过程,我看到重复了。

非常感谢。

4

1 回答 1

6

在循环的最后一次迭代中,fetch失败了。当它这样做时,您将重新插入以前的值。这是解决此问题的一种方法:

    REPEAT

        FETCH CURSOR_NOVEDADES INTO vID;

        if ! vdone then

            SELECT CONCEPTO_ID, MONTO INTO vCONCEPTO_ID, vMONTO
            FROM NOVEDADES WHERE ID = vID;

            INSERT INTO LIQUIDACIONES_DETALLE (LIQUIDACION_ID, CONCEPTO_ID, MONTO)
            VALUES(pLIQUIDACION_ID, vCONCEPTO_ID, vMONTO);
       end

    UNTIL vDONE END REPEAT;
于 2013-06-03T15:45:42.483 回答