Technical Article

Function to find the current age

,

Use this script to figure out the current age of a person or object. It also takes leap year birthdates into consideration. You can also use this to find out the age of something at a particular point of time.

CREATE Function dbo.fn_FindAge(@Birthdate datetime, @TodaysDate datetime)
RETURNS tinyint
AS

BEGIN


Declare @Birthyear int, @CurrentYear int, @Age tinyint
Set @Birthyear = datepart(yy, @Birthdate)
Set @CurrentYear = datepart(yy, @TodaysDate)

--Check for leap year birthdates
If datepart(m, @Birthdate) = 2 AND datepart(d, @Birthdate) = 29
If ('2/28/' + convert(varchar(4), @CurrentYear)) < @TodaysDate
Set @Age = (Select @CurrentYear - @Birthyear)
Else
Set @Age = (Select (@CurrentYear -1) - @Birthyear)
ELSE
If (convert(varchar(2), datepart(m, @Birthdate)) + '/' + convert(varchar(2), datepart(d, @Birthdate)) + '/' + convert(varchar(4), @CurrentYear)) < @TodaysDate
Set @Age = (Select  @CurrentYear - @Birthyear)
Else
Set @Age = (Select(@CurrentYear -1) - @Birthyear)

Return @Age
END

Rate

2 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

2 (1)

You rated this post out of 5. Change rating