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

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

    Declare @dob datetime
    Declare @today datetime
    
    Set @dob = '05/20/2000'
    set @today = getdate()
    
    select  CASE
                WHEN dateadd(year, datediff (year, @dob, @today), @dob) > @today 
                THEN datediff (year, @dob, @today) - 1
                ELSE datediff (year, @dob, @today)
            END as Age
    

提交回复
热议问题