Labels

Tuesday, July 30, 2013

Calculate Age from Date of Birth in SQL

Below SQL function is used to get age of a person from Date of Birth.
CREATE FUNCTION [dbo].[fn_GetAge] (@in_DOB AS DATETIME)
RETURNS INT
AS
BEGIN
 DECLARE @age INT
 DECLARE @now DATETIME = (
   SELECT GETDATE()
   )

 --PRINT @NOW              
 IF cast(datepart(m, @now) AS INT) > cast(datepart(m, @in_DOB) AS INT)
  SET @age = cast(datediff(yyyy, @in_DOB, @now) AS INT)
 ELSE IF cast(datepart(m, @now) AS INT) = cast(datepart(m, @in_DOB) AS INT)
  IF datepart(d, @now) >= datepart(d, @in_DOB)
   SET @age = cast(datediff(yyyy, @in_DOB, @now) AS INT)
  ELSE
   SET @age = cast(datediff(yyyy, @in_DOB, @now) AS INT) - 1
 ELSE
  SET @age = cast(datediff(yyyy, @in_DOB, @now) AS INT) - 1

 RETURN @age
END
Executing below SQL query you will get following output..
select dbo.fn_GetAge('1987-02-28'), GETDATE()
select dbo.fn_GetAge('1987-03-01'), GETDATE()
select dbo.fn_GetAge('1987-03-02'), GETDATE()
Get Age

1 comment: