我通过在MySQL存储过程中设置一个游标结果循环。 我现在面临的一个问题是环路始终运行彻底的最后一条记录的两倍。 这里是我的代码,
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;
也就是说,如果我有3条记录,循环运行的4倍,如果是10条循环运行11次,等等。任何想法发生了什么吗?
处理程序,这台not_found_creadit = 1
,就会引发FETCH
没有返回行,但在执行前要检查它的价值FETCH
,所以你的循环的主体将执行一个额外的时间,当FETCH
失败,则循环退出循环下一轮迭代的开始。
重新安排你的代码后,立即检查您的变量的值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;
另外,还要考虑纠正你的变量的拼写not_found_credit
BECAUSE我写DEFAULT(我不知道你在表信用),你必须正确类型。 结束。如果U创建表不是Temptable使用
TRUNCATE TempTable;
请重写例子
CREATE CREATE TEMPORARY TABLE TempTable (`Id` int(11) NOT NULL auto_increment,
`customer_id` int(11) NOT NULL,
`amount` int(11) NOT NULL,
`status` varchar(1000) NOT NULL,
`user_type` int(11) NOT NULL default '0',
`employee` varchar(1000) NOT NULL,
PRIMARY KEY (`customer_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;");
ofcourse类型是坏:)
DELIMITER $$
DROP PROCEDURE IF EXISTS CursorX $$
CREATE PROCEDURE `CursorX`()
BEGIN
DECLARE xCustomerId int(11);
DECLARE xStatus int(11);
DECLARE xUserType varchar(255);
DECLARE xEmployee varchar(255);
DECLARE xNote varchar(255);
DECLARE i int(11);
DECLARE recordNotFound INTEGER 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 recordNotFound = 1;
DROP TEMPORARY TABLE IF EXISTS TempTable;
CREATE TEMPORARY TABLE TempTable AS(SELECT * FROM credit);
OPEN cur_credit;
set not_found_creadit = 0;
credit_loop: LOOP
SET i = i +1;
FETCH cur_credit INTO xCustomerId,xStatus,xUserType,xEmployee,xNote;
IF not_found_creadit THEN
LEAVE credit_loop;
END IF;
END LOOP credit_loop;
CLOSE cur_credit;
select * FROM TempTable;
END $$