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

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

    You need to consider the way the datediff command rounds.

    SELECT CASE WHEN dateadd(year, datediff (year, DOB, getdate()), DOB) > getdate()
                THEN datediff(year, DOB, getdate()) - 1
                ELSE datediff(year, DOB, getdate())
           END as Age
    FROM 

    Which I adapted from here.

    Note that it will consider 28th February as the birthday of a leapling for non-leap years e.g. a person born on 29 Feb 2020 will be considered 1 year old on 28 Feb 2021 instead of 01 Mar 2021.

    提交回复
    热议问题