Get an Accurate Age by Date

This would work too 🙂

As an explanation, I use datediff to get the number of days, divide that by the correct number of days in a year (keeping track of leap years, there are only 97 in every 400 years) and then FLOOR the result, thus making sure it doesn’t get rounded up accidentally.

CREATE FUNCTION [dbo].[GetAge]
    (
      @Geburtsdatum DATETIME
    )
RETURNS INT
AS
    BEGIN
        RETURN FLOOR(DATEDIFF(dd, @Geburtsdatum, CURRENT_TIMESTAMP)/365.2425)
    END
GO

Originally published on CodeProject on 2010-02-19. Archived original URL not established. Preserved for historical reference.