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

后端 未结 24 1956
无人共我
无人共我 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:59

    DECLARE @DoB AS DATE = '1968-10-24'
    DECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE)
    
    SELECT 
    --Get Year difference
    DATEDIFF(YEAR,@DoB,@cDate) -
    --Cases where year difference will be augmented
    CASE 
        --If Date of Birth greater than date passed return 0
        WHEN YEAR(@DoB) - YEAR(@cDate) >= 0 THEN DATEDIFF(YEAR,@DoB,@cDate)
    
        --If date of birth month less than date passed subtract one year
        WHEN MONTH(@DoB) - MONTH(@cDate) > 0 THEN 1 
    
        --If date of birth day less than date passed subtract one year
        WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) > 0 THEN 1 
    
        --All cases passed subtract zero
        ELSE 0
    END
    

提交回复
热议问题