mysql 游标 一次,MYSQL游标循环,多运行一次,为什么?

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,

BEGIN

DECLARE not_found_creadit INT DEFAULT 0;

DECLARE cur_credit CURSOR FOR

SELECT customer_id, amount, status, user_type, employee, note FROM credit WHERE status = 'approved' AND customer_id = int_cust_id;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found_creadit = 1;

OPEN cur_credit;

SET not_found_creadit = 0;

credit_loop : LOOP

IF not_found_creadit THEN

CLOSE cur_credit;

LEAVE credit_loop;

END IF;

FETCH cur_credit INTO vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note;

SELECT vc_customer, dec_amount, vc_status, vc_user_type, vc_emp, vc_note;

......

......

END LOOP;

END;

Means if I have 3 records, loop runs 4 times, if it is 10 records loop runs 11 times, etc. Any idea whats happening here?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值