SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

James Howards SQL Blog

Add to Technorati Favorites Add to Google
 

Common Forum Queries: Calculate age from the date of birth

By James Howard in James Howards SQL Blog | 11-25-2009 10:14 AM | Categories: Filed under: , , ,
Rating: (not yet rated) |  Discuss | 763 Reads | 130 Reads in Last 30 Days |1 comment(s)

 Some questions reappear on forums more than others, my experience suggests none more so than how one should work out an individual’s age based on their date of birth.

 I have been using the following logic within a procedure, as I didn’t require specific months and days as part of the returned result.

 

DECLARE @DOB as DateTime

Set @DOB='29 Jun 1980' -- Date Of Birth

select year(getdate())

     - year(@DOB)

     - case when month(@DOB) > month(getdate()) then 1

            when month(@DOB) < month(getdate()) then 0

                  when day(@DOB) > day(getdate()) then 1

            else 0

        end as age

 

Well now the requirements have changed with the application now expecting the Month and Day part of the calculated age.

The following tsql will fulfil these new criteria:

DECLARE @date datetime,

@tmpdate datetime,

@years int,

@months int,

@days int

SELECT @date = '6/29/80'

SELECT @tmpdate = @date

SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN MONTH(@date) > MONTH(GETDATE()) THEN 1 ELSE 0 END

SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)

SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END

SELECT @tmpdate = DATEADD(m, @months, @tmpdate)

SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())

SELECT @years as Yr, @months as Mnths, @days as [Days]

 

This seems to do the trick but I’d be interested to hear from anyone with a different (better) way of producing the additional columns for the latter query.

Comments
 

Mitesh Oswal said:

DECLARE @date datetime,

@tmpdate datetime,

@years int,

@months int,

@days int

SELECT @date = '11/26/80'

SELECT

@years = DATEDIFF(yy,@date,GETDATE())

SELECT

@date= DATEADD(yy,@years,@date)

SELECT

@months = DATEDIFF(mm,@date,GETDATE())

SELECT

@date = DATEADD(mm,@months,@date)

SELECT

@days = DATEDIFF(dd,@date,GETDATE())

SELECT

CASE WHEN (@days <= 0 AND @months <= 0 )  THEN @years - 1 ELSE @years END AS "Year",

CASE WHEN (@days <= 0 AND @months < 0 ) THEN  12+@Months-1

ELSE CASE WHEN @months < 0  THEN 11 ELSE @months END END MONTHS,

CASE WHEN @days < 0 THEN 31+@days ELSE @days END AS Days

November 27, 2009 2:16 AM
Leave a Comment
Only members of SQLServerCentral may leave comments. Register now for your free account or Sign-In if you are already a member.