DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getNextDueDate`(vDated DATE, vGapDays INT, vPayDay INT) RETURNS date NOT DETERMINISTIC NO SQL BEGIN DECLARE vReturn DATE; DECLARE vDuaDate DATE; DECLARE vDuaDateDay INT; SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate; IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); END IF; IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN IF util.isLeapYear(YEAR(vDuaDate)) THEN SET vPayDay = 29; ELSE SET vPayDay = 28; END IF; END IF; SELECT DAY(vDuaDate) INTO vDuaDateDay; RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay))); END$$ DELIMITER ;