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,
YOU MUST CORRECT TYPE BECAUSE I WRITE DEFAULT (i dont know what You have in table credit). End If U create table TempTable use
TRUNCATE TempTable;
Please rewrite example
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 type is bad :)
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 $$