I've seen the question several times with results outputting Years, Month, Days but never a numeric / decimal result. (At least not one that doesn't round incorrectly). I welcome feedback on this function. Might not still need a little adjusting.
-- Input to the function is two dates. -- Output is the numeric number of years between the two dates in Decimal(7,4) format. -- Output is always always a possitive number.
-- Logic is based on three steps. -- 1) Is the difference less than 1 year (0.5000, 0.3333, 0.6667, ect.) -- 2) Is the difference exactly a whole number of years (1,2,3, ect.)
CREATE Function [dbo].[F_Get_Actual_Age](@pi_date1 datetime,@pi_date2 datetime)
RETURNS Numeric(7,4)
AS
BEGIN
Declare
@l_tmp_date DATETIME
,@l_days1 DECIMAL(9,6)
,@l_days2 DECIMAL(9,6)
,@l_result DECIMAL(10,6)
,@l_years DECIMAL(7,4)
--Check to make sure there is a date for both inputs
IF @pi_date1 IS NOT NULL and @pi_date2 IS NOT NULL
BEGIN
IF @pi_date1 > @pi_date2 --Make sure the "older" date is in @pi_date1
BEGIN
SET @l_tmp_date = @pi_date2
SET @pi_date2 = @Pi_date1
SET @pi_date1 = @l_tmp_date
END
--Check #1 If date1 + 1 year is greater than date2, difference must be less than 1 year
IF DATEADD(YYYY,1,@pi_date1) > @pi_date2
BEGIN
--How many days between the two dates (numerator)
SET @l_days1 = DATEDIFF(dd,@pi_date1, @pi_date2)
--subtract 1 year from date2 and calculate days bewteen it and date2
--This is to get the denominator and accounts for leap year (365 or 366 days)
SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2)
SET @l_years = @l_days1 / @l_days2 -- Do the math
END
ELSE
--Check #2 Are the dates an exact number of years apart.
--Calculate years bewteen date1 and date2, then add the years to date1, compare dates to see if exactly the same.
IF DATEADD(YYYY,DATEDIFF(YYYY,@pi_date1,@pi_date2),@pi_date1) = @pi_date2
SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2) --AS Years, 'Exactly even Years' AS Msg
ELSE
BEGIN
--Check #3 The rest of the cases.
--Check if datediff, returning years, over or under states the years difference
SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2)
IF DATEADD(YYYY,@l_years,@pi_date1) > @pi_date2
SET @l_years = @l_years -1
--use basicly same logic as in check #1
SET @l_days1 = DATEDIFF(dd,DATEADD(YYYY,@l_years,@pi_date1), @pi_date2)
SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2)
SET @l_years = @l_years + @l_days1 / @l_days2
--SELECT @l_years AS Years, 'Years Plus' AS Msg
END
END
ELSE
SET @l_years = 0 --If either date was null
RETURN @l_Years --Return the result as decimal(7,4)
END
`