问题
I have following table in my database and I wrote following stored procedure to loop through the table.
When I call this stored procedure, I get only one record.
What could be the error I have done, and how can this be fixed?
+--------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| date | date | NO | | NULL | |
| inQty | decimal(5,2) | NO | | 0.00 | |
| outQty | varchar(45) | YES | | 0.0 | |
+--------+--------------+------+-----+---------+-------+
-- --------------------------------------------------------------------------------
-- Routine DDL
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_balance`()
BEGIN
DECLARE vDate DATE DEFAULT '0000-00-00';
DECLARE vInQty DECIMAL DEFAULT 0.0;
DECLARE tOutQty DECIMAL DEFAULT 0.0;
DECLARE balance DECIMAL DEFAULT 0.0;
DECLARE vvDate DATE DEFAULT '0000-00-00';
DECLARE flag INT DEFAULT 0;
DECLARE tCursor CURSOR FOR SELECT * FROM new_table;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag = 1;
OPEN tCursor;
REPEAT
FETCH tCursor INTO vDate, vInQty, tOutQty;
SELECT vDate, vInQty, tOutQty;
UNTIL flag
END REPEAT;
CLOSE tCursor;
END
回答1:
The PROCEDURE above return only one row, because you update your variables(vDate, vInQty, tOutQty) every time inside the REPEAT body.
My suggestion to fix that is:
- CREATE TEMPORARY TABLE tmp_table, which each variable represent a column in this tmp_table.
- inside the REPEAT insert into that tmp_table.
- select * from temp_table.
- DROP tmp_table. /* Clean up */
来源:https://stackoverflow.com/questions/7990786/how-to-loop-through-a-table-using-a-cursor-in-mysql