• george-178499 - Monday, February 26, 2018 9:16 PM

    Hmm, there is already a datediff function which will tell you the difference between two dates. And it can return the values in whichever format you like the difference --> in days, months, years etc.. In addition there is no overhead of converting the date datatype to that of an integer.
    https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql

    When we comparing two columns , it is best to avoid this overhead of conversion.

    The function you have created how would it work when you pass the following parameters
    DECLARE @DOB DATE = '19991231';
    DECLARE @Today DATE = '20010101';

    It tells you there are 18870 integers between 31-Dec-1999 and 1-Jan-2001 and divide by 10000=0.18 which means age is less than a year?

    Be careful of using DATEDIFF for age calcs.  It counts the number of period boundaries that have passed, so you are often off by 1.
    in the following examples, using DateDiff returns the incorrect value
    DECLARE @DOB DATE = '20160105';
    DECLARE @Today DATE = '20180104';

    SELECT Age_Calc = (CAST(CONVERT(VARCHAR(8), @Today, 112) AS INT) - CAST(CONVERT(VARCHAR(8), @DOB, 112) AS INT)) / 10000;

    SELECT Age_DateDiff_Year = DATEDIFF(YEAR, @DOB, @Today);
    SELECT Age_DateDiff_Month = DATEDIFF(MONTH, @DOB, @Today) /12;
    SELECT Age_DateDiff_Day = DATEDIFF(DAY, @DOB, @Today) /365;