SQL Calculate Age

ALTER FUNCTION [dbo].[ufn_CalculateAge]
(
      @BirthDate DATETIME,
      @CurrentDate DATETIME
)
RETURNS NUMERIC(18,0)
AS
BEGIN
      RETURN
      (
            (     --Age Years Apart i.e. quotient
                  CASE
                        WHEN @BirthDate > @CurrentDate THEN NULL
                        WHEN DATEPART(day, @BirthDate) > DATEPART(day, @CurrentDate) THEN DATEDIFF(month, @BirthDate, @CurrentDate) - 1
                        ELSE DATEDIFF(month, @BirthDate, @CurrentDate)
                  END / 12
            )
            +
            (
                  (     --Age Years Apart % (Modulo) i.e. remainder
                        CASE
                              WHEN @BirthDate > @CurrentDate THEN NULL
                              WHEN DATEPART(day, @BirthDate) > DATEPART(day, @CurrentDate) THEN DATEDIFF(month, @BirthDate, @CurrentDate) - 1
                              ELSE DATEDIFF(month, @BirthDate, @CurrentDate)
                        END % 12
                  ) * 0.01
            )
      )
END

Comments

Popular posts from this blog

Querying a Data Table Using Select Method and Lambda Expressions in Dot Net

StringToTable

GetPhoneSSNFormat