How to loop through a table using a cursor in MySQL?

ε祈祈猫儿з 提交于 2019-12-05 05:42:00

问题


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:

  1. CREATE TEMPORARY TABLE tmp_table, which each variable represent a column in this tmp_table.
  2. inside the REPEAT insert into that tmp_table.
  3. select * from temp_table.
  4. DROP tmp_table. /* Clean up */


来源:https://stackoverflow.com/questions/7990786/how-to-loop-through-a-table-using-a-cursor-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!