Home Forums SQL Server 7,2000 T-SQL How can we calculate Age of employee? RE: How can we calculate Age of employee?

  • Please be careful using ANY advice from an open forum such as this one without testing it first. The algorithms offered so far are severely lacking in accuracy. Although as schoolchildren, we learned that there are 365 days in a year, most of us would agree that because of the nature of the rules for leap years, we cannot use either 365 or 365.25 as an accurate divisor. And, of course, you don't believe that every month has 30 days.

    I do appreciate the opportunity your request and the interim responses gave me to work up what I now believe to be an accurate script for returning an age in years, months and days. As has been suggested, it would probably be best implemented as a UDF (user defined function).

    Oh. One more thing. Despite my confidence in this code, you must be sure of it before using it. Test it with as many weird combinations of @Today and @DOB as you can to prove out its accuracy.

    Declare @DOB smallDatetime

    ,@Today smallDatetime

    ,@AgeYears int

    ,@AgePlusMonths int

    ,@AgePlusDays int

    ,@LastBD datetime

    ,@LastMonthBD datetime

    --======================--

    set @DoB = '20040228'

    set @Today = '20080229'

    --======================--

    select

    @AgeYears

    = year(@today)-year(@dob)

    - case when month(@today) < month(@dob)

    or (month(@today) = month(@dob) and day(@today) < day(@dob))

    then 1

    else 0

    end

    ,@LastBD = dateadd(year,@AgeYears,@Dob)

    ,@AgePlusMonths = datediff(month, @LastBD, @Today)

    - case when month(@today) <= month(@LastBD) and day(@today) < day(@LastBD)

    then 1

    else 0

    end

    - case when month(@dob) = 2 and day(@dob) = 29

    then 1

    else 0

    end

    ,@LastMonthBD = dateadd(month,@AgePlusMonths,@LastBD)

    ,@AgePlusDays = datediff(day, @LastMonthBD, @Today)

    Select @today as today

    ,@DoB DoB

    ,@LastBD as LastBD

    ,@LastMonthBD as LastMonthBD

    ,@AgeYears AgeYears

    ,@AgePlusMonths As AgePlusMonths

    ,@AgePlusDays as AgePlusDays