Tuesday, August 9, 2016

Sql Server: Calculate Age in years from Date of Birth (DOB)

In this article I am going to explain how to calculate the age in years from given Date of Birth in Sql.


Implementation:

You can calculate the age from DOB using below given methods:

Method 1:
Declare @DOB DATE ='09/28/1980'
Declare @Currentdate date = getdate()
SELECT [Date Of Birth] = @DOB,[Current Date]=@Currentdate,[Age]=DATEDIFF(yy,@DOB,@Currentdate)


Method 2:
SELECT [Age in Years] = DATEDIFF(DAY, '09/28/1980', GetDate()) / 366


Method 3:
Declare @DOB DATE ='09/28/1980'
Declare @Currentdate date = getdate()
SELECT[Date of Birth] = @DOB,[Current Date]=@Currentdate,[Age]=DATEDIFF(yy,@DOB,@Currentdate)-
   (CASE WHEN DATEADD(YY,DATEDIFF(YEAR,@DOB,@Currentdate),@DOB)>  @Currentdate THEN 1 ELSE 0 END)


Method 4:
Declare @DOB DATE ='07/28/1980'
Declare @Currentdate date = getdate()
SELECT [Date Of Birth] = @DOB,[Current Date]=@Currentdate,[Age]=DATEDIFF(dd,@DOB,@Currentdate)/365.25




No comments:

Post a Comment