How to calculate age (in years) based on Date of Birth and getDate()

前端 未结 30 2068
死守一世寂寞
死守一世寂寞 2020-11-22 02:08

I have a table listing people along with their date of birth (currently a nvarchar(25))

How can I convert that to a date, and then calculate their age in years?

30条回答
  •  醉话见心
    2020-11-22 02:30

    Ed Harper's solution is the simplest I have found which never returns the wrong answer when the month and day of the two dates are 1 or less days apart. I made a slight modification to handle negative ages.

    DECLARE @D1 AS DATETIME, @D2 AS DATETIME
    SET @D2 = '2012-03-01 10:00:02'
    SET @D1 = '2013-03-01 10:00:01'
    SELECT
       DATEDIFF(YEAR, @D1,@D2)
       +
       CASE
          WHEN @D1<@D2 AND DATEADD(YEAR, DATEDIFF(YEAR,@D1, @D2), @D1) > @D2
          THEN - 1
          WHEN @D1>@D2 AND DATEADD(YEAR, DATEDIFF(YEAR,@D1, @D2), @D1) < @D2
          THEN 1
          ELSE 0
       END AS AGE
    

提交回复
热议问题