Friday, August 31, 2018

DATEDIFF in T-SQL may not be the best way to calculate how old someone is at a given point in time.

This...

Declare @age int = DATEDIFF(YEAR, @birthday, @afterbirthday)
SELECT @age

 
 

...merely subtracts one year from another leading to some nasty results. You may compensate like so:

Declare @age int = DATEDIFF(YEAR, @birthday, @afterbirthday)
Declare @birthdaymonth int = MONTH(@birthday)
Declare @afterbirthdaymonth int = MONTH(@afterbirthday)
if @birthdaymonth > @afterbirthdaymonth
BEGIN
   set @age = @age -1
END
if @birthdaymonth = @afterbirthdaymonth
BEGIN
   DECLARE @birthdayday int = DAY(@birthday)
   DECLARE @afterbirthdayday int = DAY(@afterbirthday)
   DECLARE @differenceindays int = @afterbirthdayday - @birthdayday
   IF @differenceindays < 0
   BEGIN
      set @age = @age -1
   END
END
SELECT @age

No comments:

Post a Comment