如何在MySQL的存储过程中分配默认值
DELIMITER $$
CREATE DEFINER=`ntc`@`%` PROCEDURE `MangerModule`()
BEGIN
select (select sum(AmountRecevied) from collection) as TotalAmount,
(select @DayAmount := sum(AmountRecevied) as TotoalAmountperday
from collection
where day(Date_Time)= day(CURRENT_DATE())) as Dayamount,
(select @MonthAmount :=sum(AmountRecevied) as TotoalAmountperMonth
from collection
where date_time between DATE_FORMAT(NOW() ,'%Y-%m-01')
and LAST_DAY(now() - interval 0 month )) as monthamount,
(select @YearAmount := sum(AmountRecevied) as TotoalAmountperYear
from collection
where year(Date_Time) =YEAR(CURRENT_DATE())) as yearamount;
END
答案 0 :(得分:1)
使用IFNULL
:
select (select IFNULL(sum(AmountRecevied), 0.0) from collection) as TotalAmount,
(select @DayAmount := IFNULL(sum(AmountRecevied), 0.0) as TotoalAmountperday
from collection
where day(Date_Time)= day(CURRENT_DATE())) as Dayamount,
(select @MonthAmount := IFNULL(sum(AmountRecevied), 0.0) as TotoalAmountperMonth
from collection
where date_time between DATE_FORMAT(NOW() ,'%Y-%m-01')
and LAST_DAY(now() - interval 0 month )) as monthamount,
(select @YearAmount := IFNULL(sum(AmountRecevied), 0.0) as TotoalAmountperYear
from collection
where year(Date_Time) =YEAR(CURRENT_DATE())) as yearamount;
答案 1 :(得分:0)
您需要在为其分配任何值之前设置用户变量。默认情况下,MySQL中的用户变量为NULL。所以,任何事情+ NULL = NULL
在BEGIN
之后执行此操作:
SET @DayAmount = 0.0;
SET @MonthAmount = 0.0;
SET @YearAmount = 0.0;