Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

cursor

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
like image 568
Harsha Avatar asked Feb 02 '26 06:02

Harsha


1 Answers

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 */
like image 127
AYRM1112013 Avatar answered Feb 04 '26 21:02

AYRM1112013