如何从CURSOR读取数据 - mysql存储过程

时间:2018-05-12 05:33:18

标签: mysql stored-procedures database-cursor

我在mysql存储过程中实现了CURSOR ...我在读取光标时遇到了挑战...基本上我想从光标和放大器中读取列值将相同的内容存储到一个变量..但我得到的变量值为NULL ...解决方案是什么...请帮助我..提前感谢...

我的代码如下,

delimiter //

CREATE PROCEDURE placeOrder(IN cartId INT)
BEGIN

   DECLARE countitem INT DEFAULT 0;
   DECLARE productId INT;
   DECLARE quantity INT;
   DECLARE itemDicountAmt DOUBLE DEFAULT 0;
  DECLARE v_finished INT DEFAULT 0;


 DEClARE cart_cursor CURSOR FOR 
 SELECT ProductId, Quantity FROM TBL_SHOPPING_CART_ITEM;

 -- declare NOT FOUND handler
 DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET v_finished = 1;

 OPEN cart_cursor;

 get_cart: LOOP

 FETCH cart_cursor into productId, quantity;

 IF v_finished = 1 THEN 
 LEAVE get_cart;
 END IF;

 -- build email list
 insert into debugtable select concat('PRODUCT :', productId);
  insert into debugtable select concat('QUANTITY :', quantity);
 END LOOP get_cart;

 CLOSE cart_cursor;

END//

delimiter ;

输出:

tmptable 空值 NULL

因为我在购物车表中有一条记录......

1 个答案:

答案 0 :(得分:1)

请参阅C.1 Restrictions on Stored Programs :: Name Conflicts within Stored Routines

选项1:

...
/*DEClARE cart_cursor CURSOR FOR 
 SELECT ProductId, Quantity FROM TBL_SHOPPING_CART_ITEM;*/
DEClARE cart_cursor CURSOR FOR 
 SELECT
   TBL_SHOPPING_CART_ITEM.ProductId,
   TBL_SHOPPING_CART_ITEM.Quantity
 FROM TBL_SHOPPING_CART_ITEM;
...

选项2:

...
/*DECLARE productId INT;
DECLARE quantity INT;*/
DECLARE _productId INT;
DECLARE _quantity INT;
...
/*FETCH cart_cursor into productId, quantity;*/
FETCH cart_cursor into _productId, _quantity;
...
/*insert into debugtable select concat('PRODUCT :', productId);
insert into debugtable select concat('QUANTITY :', quantity);*/
insert into debugtable select concat('PRODUCT :', _productId);
insert into debugtable select concat('QUANTITY :', _quantity);
...