DELIMITER // CREATE OR REPLACE FUNCTION getDaysBetween(starting_date DATETIME, ser_num VARCHAR(25)) RETURNS INT NOT DETERMINISTIC BEGIN DECLARE fiscal_year VARCHAR(4); DECLARE actual_year_begin VARCHAR(25); DECLARE first_yearly_meter_read_date VARCHAR(25); DECLARE total_printing_days INT; /*Declare the cursor that will get the earliest meter read date for this serial number that is in the same fiscal year as the starting_date. The total days, used to CALCULATE THE AVERAGE copies/day, will be the difference between the first actual meter read for this serial number and the starting_date. 1 row will be returned.*/ DECLARE getFirstMeterReadDate CURSOR FOR SELECT MIN(created_date) first_meter_read_date FROM y2019_meters WHERE serial_number = ser_num AND created_date BETWEEN actual_year_begin AND starting_date GROUP BY serial_number; /*Concat the date that the fiscal year begins. Use the same year as the starting_date and the default fiscal date .*/ SELECT YEAR(starting_date) INTO fiscal_year; SET actual_year_begin = CONCAT(fiscal_year, '-07-01 00:00:00'); OPEN getFirstMeterReadDate; FETCH getFirstMeterReadDate INTO first_yearly_meter_read_date; CLOSE getFirstMeterReadDate; /*Get total_printing_days. This will be divided into the total copies for the same time period, to get the average copies printed per day.*/ SELECT DATEDIFF(starting_date, first_yearly_meter_read_date) INTO total_printing_days; RETURN total_printing_days; END // DELIMITER ;