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

后端 未结 24 1942
无人共我
无人共我 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 06:15

    DECLARE @BirthDate datetime, @AgeInMonths int
    SET @BirthDate = '10/5/1971'
    SET @AgeInMonths                              -- Determine the age in "months old":
        = DATEDIFF(MONTH, @BirthDate, GETDATE())  -- .Get the difference in months
        - CASE WHEN DATEPART(DAY,GETDATE())       -- .If today was the 1st to 4th,
                  < DATEPART(DAY,@BirthDate)      --   (or before the birth day of month)
               THEN 1 ELSE 0 END                  --   ... don't count the month.
    SELECT @AgeInMonths / 12 as AgeYrs            -- Divide by 12 months to get the age in years
          ,@AgeInMonths % 12 as AgeXtraMonths     -- Get the remainder of dividing by 12 months = extra months
          ,DATEDIFF(DAY                           -- For the extra days, find the difference between, 
                   ,DATEADD(MONTH, @AgeInMonths   -- 1. Last Monthly Birthday 
                                 , @BirthDate)    --     (if birthdays were celebrated monthly)
                   ,GETDATE()) as AgeXtraDays     -- 2. Today's date.
    

提交回复
热议问题