Wednesday, December 6, 2017

Age calculation based on today's date and birthday

To calculate the exact age based on today's date and birthday, it might be a little tricky to implement it in SQL. Below is one way to do it.
declare @BirthDate datetime = '12/1/2016'
declare @Today datetime = DateAdd(dd, DateDiff(dd, 0, getdate()), 0)

declare @age int = 
  ( CONVERT(int,CONVERT(char(8),@Today,112)) - CONVERT(char(8), @BirthDate, 112)) /10000

select @age 
/* returns 1 if today's date is 12/1/2017. */
/* returns 0 if today's date is 12/2/2017. */


No comments: