Friday, 7 July 2017

Calculate age in SQL

Question: Given a DateTime representing a person's birthday, how do I calculate their age in years?

 Solution:


declare @dd smalldatetime = '1980-04-01'
declare @age int = YEAR(GETDATE())-YEAR(@dd)
if (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1

print @age 

No comments:

Post a Comment