Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Age calculation with SQL Server

There seem to be many different methods being suggested to calculate an age in SQLServer.  Some are quite complex but most are simply wrong.  This is by far the simplest and accurate method that I know.

 

Declare @Date1 datetime
Declare
@Date2 datetime


Select
@Date1 = '15Feb1971'
Select @Date2 = '08Dec2009'
select CASE
WHEN
dateadd(year, datediff (year, @Date1, @Date2), @Date1) > @Date2
THEN datediff (year, @Date1, @Date2) - 1
ELSE datediff (year, @Date1, @Date2)
END as Age

This even copes with the tricky situation of 29th feb,  although I cant say correctly as according to Wikipedia birthdays may be on the 28th of Feb or 1st March.

This post has been part of T-SQL Tuesday, hosted this month by Adam Machanic

Comments

No comments.

Leave a Comment

Please register or log in to leave a comment.