Monday, December 3, 2007

How to calculate age in years from given date

There is no function in SQL Server which calculates difference between a given date and recent date. Classic example is of calculating age.

I found a way to calculate age based on date of birth.

CREATE FUNCTION [dbo].[fnCalculateAge] (@Old_Date datetime, @New_Date datetime)
RETURNS int

AS

BEGIN

DECLARE @age int

SELECT
@age = CASE
WHEN dateadd(year, datediff (year, @Old_Date, @New_Date), @Old_Date) > @New_Date

THEN datediff (year, @Old_Date, @New_Date) - 1

ELSE datediff (year, @Old_Date, @New_Date)

END


RETURN
@age
END

Execute function with following statement,

SELECT [dbo].[fnCalculateAge] ('1996-12-03',getdate())