Search code examples
mysqlprocedureaddition

MySQL Stored Procedures - Adding integer variable to date returns null


I am writing my first mysql procedure. I have a date variable and 2 integer variables. I am multiplying the two integer variables and adding the resultant integer to the date variable.

For example:

pint=6;
noftimes=3
sdate=2020-05-05
totDays=pint*noftimes
edate=2020-05-05+totDays

I am able to multiple pint*noftimes but not add sdate+totDays. Whereas If I add sdate+10 then I am getting a correct incremental date value. The following is my procedure:

DELIMITER $$
CREATE DEFINER=`pattu`@`localhost` PROCEDURE `getFieldWorkDates`(IN `p_id` INT, OUT `totDays` INT, OUT `edate` DATE)
BEGIN
DECLARE noftimes int;
DECLARE pint int;
DECLARE sdate DATE;
DECLARE tdays int;
SELECT startDate into sdate from projects where idprojects=p_id;
SELECT projectDuration into noftimes from projects where idprojects=p_id;
SELECT recFreq into pint from projects where idprojects=p_id;
SET totDays=pint*noftimes;
SET edate = sdate+(pint*noftimes);

END$$
DELIMITER ;

When I execute this, I am getting the message, your query has been executed successfully. 0 rows affected


Solution

  • SET edate = sdate+(pint*noftimes);

    You cannot add integer to date. Use DATE_ADD() function.


    CREATE 
    DEFINER=pattu@localhost
    PROCEDURE getFieldWorkDates ( IN p_id INT, 
                                  OUT totDays INT, 
                                  OUT edate DATE)
    SELECT recFreq * projectDuration, 
           startDate + INTERVAL recFreq * projectDuration DAY 
    INTO totDays, 
         edate 
    FROM projects 
    WHERE idprojects=p_id;