Most of the other answers are not designed for age - whole years (for example, January 1, 2009 - one year after December 31, 2008). Thus, if you use most of the calculations on this page, on average you return the wrong age for half a year. Luke is the only person who has seen this, but his answer seems too complicated to me - there is an easier way:
Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age
(NOTE: Thank you for the “Training” for making a wonderful catch using my original algorithm - this is an audit that uses hours instead of days).
Since rounding is very grainy here, it is almost perfectly accurate for every day of every year. The exceptions are so confusing that they are almost humorous: every fourth year returns at an age even younger if we A) ask for the age before 6:00 in the morning, B) for the person’s birthday, and C) their birthday after February 28th. Of course, depending on what time someone was born, this may be “technically” correct! In my setup, this is a perfectly acceptable compromise.
Here is a cycle that prints ages to show that it works.
Declare @age int; Declare @BirthDate datetime; Declare @Year int; Set @Year = 2008; WHILE (@Year > 1930) BEGIN -- Put today date where you see '-03-18' SET @BirthDate = CAST(Cast(@Year as varchar(4)) + '-03-18' AS DATETIME) SELECT @age=CAST(DATEDIFF(hh, @BirthDate, GETDATE()) / 8766 AS int); Print Cast(@Year as varchar) + ' Age: ' + Cast(@age as varchar); Set @Year = @Year - 1; END;
Finally, this is the version that also converts the date of the integer Paul to a real date:
CAST(DATEDIFF(hh, Convert(Datetime, Convert(varchar(8), [birthdate]), 112), GETDATE()) / 8766 AS int) AS Age
Mark brittingham
source share