MYSQL cursor loop, runs one extra round, why?

前端 未结 2 1232
攒了一身酷
攒了一身酷 2021-02-01 21:51

I\'m looping through a cursor result set in a MYSQL stored procedure. I\'m facing an issue which is that the loop always run thorough the last record twice. Here is my code,

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 22:36

    The handler, which sets not_found_creadit = 1, is fired when the FETCH returns no rows, but you are checking its value before executing FETCH, so the main body of your loop will execute one extra time when the FETCH fails, then the loop loop exits at the start of the next iteration.

    Rearrange your code to check the value of your variable immediately after the FETCH:

    credit_loop : LOOP 
        FETCH cur_credit INTO vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note;
        IF not_found_creadit THEN
            CLOSE cur_credit;
            LEAVE credit_loop;
        END IF;
        SELECT vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note;
        ......
        ......
    END LOOP;
    


    Also, consider correcting the spelling of your variable to not_found_credit

提交回复
热议问题