Процедура SQL, отображающая неверное значение - PullRequest
0 голосов
/ 25 апреля 2018

Я делаю процедуру, чтобы сделать некоторые вычисления для моих данных, извлеченных из моей БД, но я застрял с некоторыми условиями, которые не работают.

DELIMITER #
CREATE PROCEDURE conso(IN p_upcNameId VARCHAR(20), IN p_dateFrom DATETIME, IN p_dateTo DATETIME)     
BEGIN
    DECLARE done int default false;

    DECLARE v_cumule FLOAT;

    DECLARE v_reserve VARCHAR(40);
    DECLARE v_kg VARCHAR(40);
    DECLARE v_date DATETIME;

    DECLARE v_reserve_1 VARCHAR(40);
    DECLARE v_kg_1 VARCHAR(40);
    DECLARE v_date_1 DATETIME;

    DECLARE r1_kg VARCHAR(40);
    DECLARE r2_kg VARCHAR(40);
    DECLARE rs_date DATETIME;

    DECLARE added_kg VARCHAR(40);
    DECLARE refill_date DATETIME;


    DECLARE cur1 CURSOR FOR
        SELECT reserve, kg, day
        FROM
        (
            ( SELECT event_param_3 as reserve, event_param_4 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 50 ORDER BY event_datetime DESC )
            UNION
            ( SELECT event_param_2 as reserve, event_param_3 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 54 ORDER BY event_datetime DESC )

            UNION
            ( SELECT event_param_2 as reserve, event_param_3 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 52 ORDER BY event_datetime DESC )
            UNION
            ( SELECT event_param_1 as reserve, event_param_2 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 56 ORDER BY event_datetime DESC )

            UNION
            ( SELECT event_param_2 as reserve, event_param_3 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 53 ORDER BY event_datetime DESC )
            UNION
            ( SELECT event_param_1 as reserve, event_param_2 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 57 ORDER BY event_datetime DESC )
        ) as diffusion_programs
        WHERE day >= p_dateFrom
        AND day <= p_dateTo
        ORDER BY day DESC;
    DECLARE cur2 CURSOR FOR
        SELECT reserve, kg, day
        FROM
        (
            ( SELECT event_param_3 as reserve, event_param_4 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 50 ORDER BY event_datetime DESC )
            UNION
            ( SELECT event_param_2 as reserve, event_param_3 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 54 ORDER BY event_datetime DESC )

            UNION
            ( SELECT event_param_2 as reserve, event_param_3 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 52 ORDER BY event_datetime DESC )
            UNION
            ( SELECT event_param_1 as reserve, event_param_2 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 56 ORDER BY event_datetime DESC )

            UNION
            ( SELECT event_param_2 as reserve, event_param_3 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 53 ORDER BY event_datetime DESC )
            UNION
            ( SELECT event_param_1 as reserve, event_param_2 as kg, event_datetime as day FROM events WHERE upcNameId = p_upcNameId AND event_code = 57 ORDER BY event_datetime DESC )
        ) as diffusion_programs
        WHERE day >= p_dateFrom
        AND day <= p_dateTo
        ORDER BY day DESC;
    DECLARE cur3 CURSOR FOR 
        SELECT event_param_3, event_param_4, event_datetime FROM events WHERE event_code = 59 AND upcNameId = p_upcNameId AND event_datetime >= p_dateFrom AND event_datetime <= p_dateTo ORDER by event_datetime DESC;
    DECLARE cur4 CURSOR FOR 
        SELECT event_param_1, event_datetime FROM events WHERE event_code = 70 OR event_code = 71 AND upcNameId = p_upcNameId AND event_datetime >= p_dateFrom AND event_datetime <= p_dateTo ORDER by event_datetime DESC;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    OPEN cur1;
    OPEN cur2;
    OPEN cur3;
    OPEN cur4;

    /* Create temporary table */
    CREATE TEMPORARY TABLE tmp
    (
        day DATE,
        kg FLOAT
    );
    SET v_cumule = 0;
    FETCH cur2 INTO v_reserve_1, v_kg_1, v_date_1;
    FETCH cur3 INTO r1_kg, r2_kg, rs_date;

    forLoop: LOOP
        /* Actual row */
        FETCH cur1 INTO v_reserve, v_kg, v_date;

        /* Next row */
        FETCH cur2 INTO v_reserve_1, v_kg_1, v_date_1;





        IF DATE(v_date) = DATE(v_date_1) THEN

        -- Operations if there is a reserve switch during the diffusion
            IF v_reserve != v_reserve_1 THEN

            /* reserve switch cursor */
            FETCH cur3 INTO r1_kg, r2_kg, rs_date;

                IF rs_date >= v_date AND rs_date <= v_date_1 THEN
                    IF v_reserve = '1' THEN
                        SET v_cumule =  r1_kg - v_kg;
                    ELSE SET v_cumule = r2_kg - v_kg;
                    END IF;
                    IF v_reserve_1 = '1' THEN
                        SET v_cumule = v_kg_1 - r1_kg;
                    ELSE SET v_cumule = v_kg_1 - r2_kg;
                    END IF;
                END IF;
            END IF;

        SET v_cumule = v_cumule + (v_kg_1 - v_kg);
        -- Operations if there is a refillment during the diffusion
        IF (v_cumule< 0) THEN 
        FETCH cur4 INTO added_kg, refill_date;
            IF refill_date >= v_date AND refill_date <= v_date_1 THEN
                SET v_cumule = v_cumule + added_kg;
            END IF;
        END IF;





        ELSE

            INSERT INTO tmp VALUES (DATE(v_date), v_cumule);
            SET v_cumule = 0;
        END IF;

        IF done THEN LEAVE forLoop;
        END IF;
    END LOOP;

    CLOSE cur1;
    CLOSE cur2;
    CLOSE cur3;
    CLOSE cur4;
END#

Я использую курсоры 1 и 2 для выборастрока n и строка n + 1.Курсор 3 и 4 предназначен для выбора некоторых данных и вычисления.

Проблема, с которой я столкнулся, связана с курсором 4, как вы можете видеть, я хочу получить все отрицательные результаты и добавить значение, но оно не имеетвлияние на результат.Поэтому мне интересно, хорошо ли написана моя процедура, кроме того факта, что у меня нет ошибок при ее запуске.

Результат от запуска:

day       | kg  
...
2018-02-04 4.947
2018-02-03 4.948
2018-02-02 5.235
2018-02-01 6.85
2018-01-31 6.424
2018-01-30 6.852
2018-01-29 6.851
2018-01-28 6.851
2018-01-27 6.851
2018-01-26 -38.521
...

Здесь последняя строка не должна быть отрицательной из-за операций, если v_cumule <0 Можете ли вы помочь?Спасибо. </p>

...