用于计算总和的存储过程 - MySQL 5

时间:2014-05-06 12:22:12

标签: mysql sql stored-procedures

无效使用群组功能'

只是尝试对“' weight'的所有列值进行求和。在表格中:

BEGIN

DECLARE v_finished int DEFAULT 0;
DECLARE v_weight int DEFAULT 0;
DECLARE totalWeight int DEFAULT 0;

DECLARE weight_cursor CURSOR FOR 
SELECT weight FROM users_teachers;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
OPEN weight_cursor;

get_weight: LOOP
FETCH weight_cursor into v_weight;
IF v_finished = 1 THEN 
        LEAVE get_weight;
    END IF;
SET totalWeight = totalWeight + v_weight;



END LOOP get_weight;

CLOSE weight_cursor;

END

更新:现在的问题是v_weight总是= 0.也就是说,它没有返回DB表中的值,其中一些是非零的

1 个答案:

答案 0 :(得分:1)

因此,第一个错误是在SUM函数中。请试试这个:

BEGIN

DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_weight INTEGER DEFAULT 0;
DECLARE totalWeight INTEGER DEFAULT 0;

DECLARE weight_cursor CURSOR FOR 
   SELECT weight FROM users_teachers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
OPEN weight_cursor;

get_weight: 
LOOP
FETCH weight_cursor into v_weight;
IF v_finished = 1 THEN 
        LEAVE get_weight;
END IF;
SET totalWeight = totalWeight + v_weight; 

END LOOP get_weight;

CLOSE weight_cursor;

END