MySQL - 存储过程 - 仅使用while循环获取最后一条记录

时间:2016-11-23 23:27:45

标签: mysql sql

我试图继续从表中添加所有价格值。我试过了 n_total_price = n_total_price + d_price;

这是一项任务,我必须使用存储过程

它只是给了我最后一条记录

    DELIMITER $$
    CREATE PROCEDURE P_TOTAL_PRICES(OUT N_TOTAL_PRICE DECIMAL(30,2))
    BEGIN
        DECLARE D_PRICE DECIMAL(30,2);
        DECLARE ABC DECIMAL(30,2);
        DECLARE FOUND BOOLEAN;
        DECLARE CURSOR_1 CURSOR FOR SELECT PRICE FROM PRODUCT;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET FOUND = FALSE;
        SET FOUND = TRUE;
        OPEN CURSOR_1;
        FETCH CURSOR_1 INTO ABC;
        WHILE FOUND DO 
            SET N_TOTAL_PRICE = N_TOTAL_PRICE + D_PRICE;
            FETCH CURSOR_1 INTO ABC;
        END WHILE;
        CLOSE CURSOR_1;
    END; $$

1 个答案:

答案 0 :(得分:0)

DELIMITER $$
CREATE PROCEDURE P_TOTAL_PRICES(OUT N_TOTAL_PRICE DECIMAL(30,2))
BEGIN
DECLARE D_PRICE DECIMAL(30,2);
DECLARE ABC DECIMAL(30,2);
DECLARE FOUND BOOLEAN;
DECLARE CURSOR_1 CURSOR FOR SELECT PRICE FROM PRODUCT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET FOUND = FALSE;
SET FOUND = TRUE;
OPEN CURSOR_1;
FETCH CURSOR_1 INTO ABC;
**SET N_TOTAL_PRICE = 0;**
WHILE FOUND DO SET N_TOTAL_PRICE = N_TOTAL_PRICE +D_PRICE;
FETCH CURSOR_1 INTO ABC;
END WHILE;
CLOSE CURSOR_1;
END; $$