Link to home
Start Free TrialLog in
Avatar of Alex A
Alex A

asked on

T-SQL: calculating person age

One table column has Date of Birth.
I have to calculate person's age in  years, for example 1.23 ,  8.35 , 37.36 etc. in another column.
Any thoughts on this?
ASKER CERTIFIED SOLUTION
Avatar of Simone B
Simone B
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Patrick Matthews
Buttercup1,

I like it, but I see a couple of problems, such as:
In either formula, having two decimal places is not enough precision, and
In the 365.25 formula, you have a risk that you will understate the true age in some edge cases

Illustrating the first, consider this example:

DECLARE @dob datetime = '2012-02-28',
    @today datetime = '2013-02-27'
    
SELECT CAST(CAST(DATEDIFF(d, @dob, @today) AS DECIMAL(10, 2)) / 365.00 AS DECIMAL(10, 2)) AS _365,
    CAST(CAST(DATEDIFF(d, @dob, @today) AS DECIMAL(10, 2)) / 365.25 AS DECIMAL(10, 2)) AS _36525

Open in new window


This returns 1.00 and 1.00, respectively, yet most people would agree that this person is not yet a year old.  Using only two digits for the decimal portion is not precise enough.  Using decimal(10, 4) instead would remedy that.

Now consider how using 365.25 can understate the age in some edge cases.  (I am adopting the more precise decimal(10, 4) here.)

DECLARE @dob datetime = '2013-02-28',
    @today datetime = '2014-02-28'
    
SELECT CAST(CAST(DATEDIFF(d, @dob, @today) AS DECIMAL(10, 4)) / 365.00 AS DECIMAL(10, 4)) AS _365,
    CAST(CAST(DATEDIFF(d, @dob, @today) AS DECIMAL(10, 4)) / 365.25 AS DECIMAL(10, 4)) AS _36525

Open in new window


The "365" formula returns 1.0000, and the "365.25" formula returns 0.9993, but everyone would agree that such a person should be counted as one year old.

:)

Patrick
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial