1 year ago

#372422

test-img

Mohammad

MySQL procedure: bug in inserting data into temporary table

I have created a stored procedure to generate some data through loops and insert it to a temporary table, as shown in the code below, the first loop should do 3 iterations, so I should get records in the temporary table with "2021", "2022", and "2023" values, but it seems like only the "2021" values are inserted:

    DROP PROCEDURE IF EXISTS `my_procedure`;
    DELIMITER $$
    CREATE PROCEDURE `my_procedure` (IN template_id int)
    BEGIN

        DECLARE loop_month INT DEFAULT 1;
        DECLARE loop_year INT DEFAULT 2021;
        DECLARE cur_id INT;
        DECLARE cur_name VARCHAR(255);
        DECLARE cur_days_spread INT;
        DECLARE loop_date date;
        DECLARE finished INTEGER DEFAULT 0;
        DECLARE visit_id INT;
        DECLARE visit_name VARCHAR(255);
        DECLARE visit_date DATE;
        DECLARE visits_cursor CURSOR FOR
            SELECT
            table_name.id,
            table_name.name,
            table_name.days_spread
            FROM table_name
            WHERE table_name.template_id = template_id;

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

        DROP TEMPORARY TABLE IF EXISTS forecasted_visits;
        CREATE temporary table forecasted_visits(id int, year int, name varchar(255), visit_date date);

        OPEN visits_cursor;

        years_loop: LOOP
            IF loop_year > 2023 THEN
                LEAVE years_loop;
            END IF;

            SET loop_date = MAKEDATE(loop_year, 1);

            months_loop: LOOP
                IF loop_month > 12 THEN
                    LEAVE months_loop;
                END IF;

                visits_loop: LOOP
                    FETCH visits_cursor INTO cur_id, cur_name, cur_days_spread;

                    IF finished = 1 THEN
                        LEAVE visits_loop;
                    END IF;

                    SET visit_id = cur_id;
                    SET visit_name = cur_name;
                    SET visit_date = DATE_ADD(loop_date, INTERVAL (cur_days_spread) DAY);

                    SET loop_date = visit_date;

                    INSERT INTO forecasted_visits VALUES(visit_id, loop_year, visit_name, visit_date);

                END LOOP visits_loop;

                SET loop_month = loop_month + 1;

            END LOOP months_loop;

            SET loop_year = loop_year + 1;

        END LOOP years_loop;

        SELECT * from forecasted_visits;

        CLOSE visits_cursor;

    END$$
    DELIMITER ;

The result should be something like this:

ID year name visit_date
1 2021 abc 2021-01-01
2 2021 def 2021-01-14
3 2022 ghi 2022-01-01
4 2022 jkl 2022-01-14
5 2023 mno 2023-01-01
6 2023 pqr 2023-01-14

while what I get is only 2021 records:

ID year name visit_date
1 2021 abc 2021-01-01
2 2021 def 2021-01-14

sqlfiddle example

mysql

stored-procedures

temp-tables

0 Answers

Your Answer

Accepted video resources