如何在 MySQL 中使用游标遍历表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7990786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:32:14  来源:igfitidea点击:

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

mysqlcursor

提问by Harsha

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

回答by AYRM1112013

The PROCEDURE above return only one row, because you update your variables(vDate, vInQty, tOutQty) every time inside the REPEAT body.

上面的 PROCEDURE 仅返回一行,因为您每次在 REPEAT 主体内更新变量(vDate、vInQty、tOutQty)。

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 */
  1. CREATE TEMPORARY TABLE tmp_table,其中每个变量代表这个 tmp_table 中的一列。
  2. 在 REPEAT 内插入到那个 tmp_table 中。
  3. 从 temp_table 中选择 *。
  4. 删除 tmp_table。/* 清理 */