Calculated Age Column in SQL Server Using Function

Function to Calculate Age Column based on Floor.




Create FUNCTION [dbo].[fnCalcAge]


(


   @DOB datetime, -- Provide Column name of BirthDate.

   @CurrentDate datetime -- Provide Date or getdate() for Current Date.

 
)


RETURNS real


AS

 

BEGIN

 

    RETURN FLOOR(((DATEDIFF(dd, @DOB, @CurrentDate) +

    CASE WHEN DATEPART(mm, @DOB) = DATEPART(mm, @CurrentDate) AND

    DATEPART(dd, @DOB) = DATEPART(dd, @CurrentDate)

    THEN 1 ELSE 0 END) / 365.25) / .25) * .25

 

END

 
GO



Use function with calculated age column :

For eg. Column name is BirthDate


([dbo].[fnCalcAge]([BirthDate],getdate()))