Blog Post

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

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating