How to calculate age in T-SQL with years, months, and days
Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.
DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
SELECT @date = '2/29/04'
SELECT @tmpdate = @date
SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(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, @months, @days
Try this...
SELECT CASE WHEN
(DATEADD(year,DATEDIFF(year, @datestart ,@dateend) , @datestart) > @dateend)
THEN DATEDIFF(year, @datestart ,@dateend) -1
ELSE DATEDIFF(year, @datestart ,@dateend)
END
Basically the "DateDiff( year...", gives you the age the person will turn this year, so i have just add a case statement to say, if they have not had a birthday yet this year, then subtract 1 year, else return the value.
Simple way to get age as text is as below:
Select cast((DATEDIFF(m, date_of_birth, GETDATE())/12) as varchar) + ' Y & ' +
cast((DATEDIFF(m, date_of_birth, GETDATE())%12) as varchar) + ' M' as Age
Results Format will be:
**63 Y & 2 M**