游标或处理程序声明sql语句后的变量或条件声明(mysql)

7kjnsjlb  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(617)

即使我尝试了很多方法,它仍然会给我这个错误(游标或处理程序声明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%

ndasle7k

ndasle7k1#

我添加了declare percentage1,percentage2,percentage3 float default 0;一开始就像卡门斯那样,我和它一起工作

gajydyqb

gajydyqb2#

您可以使用 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

相关问题