如果循环中包含多个语句的语句不起作用

时间:2019-08-12 22:49:32

标签: mysql stored-procedures

我有以下步骤:

DELIMITER $$

CREATE PROCEDURE getCost(
     in  p_idp int(11), 
     out p_cost  double)
BEGIN
DECLARE strt double;
DECLARE stop double;
DECLARE diff double;
DECLARE p_hs INTEGER;
DECLARE p_hf INTEGER;
DECLARE p_hcost double;
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE i INTEGER;
    -- declare cursor
DECLARE tariffe_cursor CURSOR FOR 
SELECT hs,hf,cost FROM tariffe ORDER BY hs;

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

SELECT UNIX_TIMESTAMP(data_inizio) INTO strt
FROM prenotazioni WHERE IdP = p_idp;

SET stop = UNIX_TIMESTAMP();
SET diff = stop - strt;

SET diff = diff / 3600;

SET i = 0;
SET p_cost = 0;

WHILE i < diff
DO

    OPEN tariffe_cursor;

    get_tariffe: LOOP

        FETCH next FROM tariffe_cursor INTO p_hs,p_hf,p_hcost;

        IF v_finished = 1 THEN 
            LEAVE get_tariffe;
        END IF;

        IF (i >= p_hs AND i < p_hf) THEN
            SET p_cost = p_cost + p_hcost;
            SET v_finished = 1;
        END IF; 

    END LOOP get_tariffe;

    CLOSE tariffe_cursor;

    SET i = i + 1;
END WHILE;

IF diff < 0.25 THEN
    SET p_cost = 0;
END IF; 

END$$
DELIMITER ;

表价目表有2条记录:

  1. hs = 0,hf = 3,hcost = 3

  2. hs = 3,hf = 1000,hcost = 2

假设DIFF = 1.50->预期p_cost为6

假设DIFF = 3.75->预期p_cost为11

但是p_cost总是3

试图使用一些INSERT(插入到临时表中)检查WHILE循环和游标循环,并意识到

IF (i >= p_hs AND i < p_hf) THEN

仅当i = 0(第一个while循环)时才计算为true,但当i> 0时总是被计算为false。

F.ex。当i = 1时,第一个游标FETCH返回hs = 0,hf = 3,hcost = 3,但是如果IF为假

我做错了什么?

我也尝试过(没有成功)

IF (i >= p_hs) AND (i < p_hf)
IF i >= p_hs AND i < p_hf

逻辑:

Diff是开始和停止之间的小时数(租用期)。

Tariffe桌子的租金:0到3小时-> 3欧元,从3到1000欧元-> 2欧元。

每租借一个小时都会循环一次

光标循环检查正确的小时成本并将其添加到p_cost

1 个答案:

答案 0 :(得分:0)

问题在于,离开v_finished循环并继续0循环时,您永远不会将get_tariffe设置回while i < diff。因此,在随后的迭代中,if v_finished = 1始终为true,并且在添加到p_cost之前先退出循环。

放入

SET v_vinished = 0;

之后

OPEN tariffe_cursor;

但我认为您不会因此而得到11。您在添加第一SET v_finished = 1;之后执行p_hcost,因此它将永远不会处理表的第二行。我不确定要获得11的意图是什么。也许您应该删除设置v_finished的行。