This function will take 2 datetime parameters, the DOB, and a date to check the age at.
CREATE FUNCTION [dbo].[Calc_Age] ( @DOB datetime , @calcDate datetime ) RETURNS int AS BEGIN declare @age int IF (@calcDate < @DOB ) RETURN -1 -- If a DOB is supplied after the comparison date, then return -1 SELECT @age = YEAR(@calcDate) - YEAR(@DOB) + CASE WHEN DATEADD(year,YEAR(@calcDate) - YEAR(@DOB) ,@DOB) > @calcDate THEN -1 ELSE 0 END RETURN @age END
Check the age:
SELECT dbo.Calc_Age('2010-04-13',Getdate())
Output
11
No comments:
Post a Comment