即使我尝试了很多事情,它仍然给我这个错误(在游标或处理程序声明之后的变量或条件声明 SQL语句)
sp必须使用光标
CREATE PROCEDURE monthly_sum (IN cardId INT(36), IN monthN INT, OUT sumV float)
BEGIN
DECLARE cursor_1 CURSOR FOR
SELECT SUM(purchased.amountPurchased)
FROM purchased
WHERE MONTH(purchased.dateUsed) = monthN AND purchased.purchasedCardId = cardId AND DAY(purchased.dateUsed) <=10;
DECLARE cursor_2 CURSOR FOR
SELECT SUM(purchased.amountPurchased)
FROM purchased
WHERE MONTH(purchased.dateUsed) = monthN AND purchased.purchasedCardId = cardId AND DAY(purchased.dateUsed) <=20 AND DAY(purchased.dateUsed) >10;
DECLARE cursor_3 CURSOR FOR
SELECT SUM(purchased.amountPurchased)
FROM purchased
WHERE MONTH(purchased.dateUsed) = monthN AND purchased.purchasedCardId = cardId AND DAY(purchased.dateUsed) >20;
DECLARE percentage1, percentage2, percentage3 float default 0;
OPEN cursor_1;
FETCH cursor_1
INTO percentage1;
CLOSE cursor_1;
OPEN cursor_2;
FETCH cursor_2
INTO percentage2;
CLOSE cursor_2;
OPEN cursor_3;
FETCH cursor_3
INTO percentage3;
CLOSE cursor_3;
SET sumV = percentage1*0.01 + percentage2*0.02 + percentage1*0.03;
SELECT sumV;
END
预期的输出总和为前10天的1%,接下来10天的2%,本月其余天的3%
答案 0 :(得分:1)
i添加了DECLARE percent1,percent2,percent3 float默认值0;一开始像karmens89一样评论我,它奏效了
答案 1 :(得分:0)
可以使用select into
来代替不必要地调用游标。由于游标用于逐行获取,但是在您的情况下,它只会生成一次。
CREATE PROCEDURE monthly_sum (IN cardId INT(36), IN monthN INT, OUT sumV float)
BEGIN
DECLARE percentage1, percentage2, percentage3 float default 0;
SELECT SUM(purchased.amountPurchased) INTO percentage1
FROM purchased
WHERE MONTH(purchased.dateUsed) = monthN
AND purchased.purchasedCardId = cardId
AND DAY(purchased.dateUsed) <=10;
SELECT SUM(purchased.amountPurchased) INTO percentage2
FROM purchased
WHERE MONTH(purchased.dateUsed) = monthN
AND purchased.purchasedCardId = cardId
AND DAY(purchased.dateUsed) <=20 AND DAY(purchased.dateUsed) >10;
SELECT SUM(purchased.amountPurchased) INTO percentage3
FROM purchased
WHERE MONTH(purchased.dateUsed) = monthN
AND purchased.purchasedCardId = cardId
AND DAY(purchased.dateUsed) >20;
SET sumV = percentage1*0.01 + percentage2*0.02 + percentage1*0.03; # I think percentage3 to be added instead of percentage1
END