在LOOP语句之后插入和更新命令

时间:2013-12-01 18:39:00

标签: mysql loops insert

我正在尝试在MySql中创建一个存储过程,它需要在END LOOP标记之后继续进行更新,就像在下面的代码中一样。

不知何故,END LOOP标签之后的insert命令没有被执行,有人可以告诉我为什么吗?我该如何解决这个问题?

BEGIN
/**Constant variables*/
DECLARE constX  FLOAT DEFAULT 2.660;
DECLARE constMR FLOAT DEFAULT 3.268;

/**Variables for tbSell*/
DECLARE seID, prodID INTEGER DEFAULT 0;
DECLARE qttSell, xV FLOAT DEFAULT 0;
DECLARE previousQttSell, previousXV FLOAT DEFAULT NULL;
DECLARE sPrice, xAvgV, mRAvgV, xUclV, xLclV, mRUclV FLOAT DEFAULT 0;
DECLARE sDt DATE DEFAULT 0;

DECLARE crQttSell CURSOR FOR 
    SELECT ts.`sellQuantity`
    FROM tb_sell ts
    WHERE ts.`productID` = 1;

/**Truncating temp tables*/
TRUNCATE tb_metrics;
TRUNCATE `tb_mr_temp_table`;

OPEN crQttSell;
get_QttSell: LOOP
    FETCH crQttSell INTO qttSell;    
    INSERT INTO tb_metrics VALUES('', 4, 4, 4, 4, 4, 4, 4, 4, 555);    
    SET previousQttSell = qttSell;    
END LOOP get_QttSell;
CLOSE crQttSell;

INSERT INTO tb_metrics VALUES('', 6, 6, 6, 6, 6, 6, 6, 6, 7);

END

1 个答案:

答案 0 :(得分:0)

您必须在fetch语句后检测EOF条件以避免无限循环:

  DECLARE done INT DEFAULT FALSE;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  ....
  ....
  get_QttSell: LOOP
    FETCH crQttSell INTO qttSell;   
    IF done THEN
      LEAVE get_QttSell;
    END IF; 
    INSERT INTO tb_metrics VALUES('', 4, 4, 4, 4, 4, 4, 4, 4, 555);    
    SET previousQttSell = qttSell;    
  END LOOP get_QttSell;
  ....

阅读文档了解详情:http://dev.mysql.com/doc/refman/5.6/en/cursors.html