Finding someone's age in SQL

前端 未结 7 2330
孤街浪徒
孤街浪徒 2020-12-16 21:11

In a SQL Server database, I record people\'s date of birth. Is there an straight-forward method of working out the person\'s age on a given date using SQL only?

Usi

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 22:10

    FWIW, Age can be computed in a straightforward manner without resorting to hacks (not that there's anything wrong with hacks!):

    CREATE FUNCTION Age (@BirthDate DATETIME)
    RETURNS INT
    AS
    BEGIN
        DECLARE @AgeOnBirthdayThisYear INT
        DECLARE @BirthdayThisYear DATETIME
        SET @AgeOnBirthdayThisYear = DATEDIFF(year, @BirthDate, GETDATE())
        SET @BirthdayThisYear = DATEADD(year, @AgeOnBirthdayThisYear, @BirthDate)
        RETURN
            @AgeOnBirthdayThisYear
            - CASE WHEN @BirthdayThisYear > GETDATE() THEN 1 ELSE 0 END
    END
    

提交回复
热议问题