Getting age in years in SQL

Handy function:

DROP FUNCTION [dbo].[GetAge]
GO

CREATE FUNCTION [dbo].[GetAge] ( @BirthDate    DATETIME,
                                 @PerDate       DATETIME )
RETURNS INT
AS
BEGIN

    DECLARE @Age         INT

    IF @BirthDate >= @PerDate
        RETURN 0

    SET @Age = DATEDIFF(YY, @BirthDate, @PerDate)

    IF MONTH(@BirthDate) > MONTH(@PerDate) OR
      (MONTH(@BirthDate) = MONTH(@PerDate) AND
       DAY(@BirthDate)   > DAY(@PerDate))
        SET @Age = @Age - 1

    RETURN @Age
END
GO

SELECT dbo.GetAge( '2001-02-23', '2010-02-23')
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *