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

前端 未结 30 2096
死守一世寂寞
死守一世寂寞 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:39

    Since there isn't one simple answer that always gives the correct age, here's what I came up with.

    SELECT DATEDIFF(YY, DateOfBirth, GETDATE()) - 
         CASE WHEN RIGHT(CONVERT(VARCHAR(6), GETDATE(), 12), 4) >= 
                   RIGHT(CONVERT(VARCHAR(6), DateOfBirth, 12), 4) 
         THEN 0 ELSE 1 END AS AGE 
    

    This gets the year difference between the birth date and the current date. Then it subtracts a year if the birthdate hasn't passed yet.

    Accurate all the time - regardless of leap years or how close to the birthdate.

    Best of all - no function.

提交回复
热议问题