How to calculate age in T-SQL with years, months, and days

后端 未结 24 1582
无人共我
无人共我 2020-11-22 05:42

What would be the best way to calculate someone\'s age in years, months, and days in T-SQL (SQL Server 2000)?

The datediff function doesn\'t handle year

24条回答
  •  误落风尘
    2020-11-22 05:57

    Here is a (slightly) simpler version:

    CREATE PROCEDURE dbo.CalculateAge 
        @dayOfBirth datetime
    AS
    
    DECLARE @today datetime, @thisYearBirthDay datetime
    DECLARE @years int, @months int, @days int
    
    SELECT @today = GETDATE()
    
    SELECT @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)
    
    SELECT @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END)
    
    SELECT @months = MONTH(@today - @thisYearBirthDay) - 1
    
    SELECT @days = DAY(@today - @thisYearBirthDay) - 1
    
    SELECT @years, @months, @days
    GO
    

提交回复
热议问题