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

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

    Gotta throw this one out there. If you convert the date using the 112 style (yyyymmdd) to a number you can use a calculation like this...

    (yyyyMMdd - yyyyMMdd) / 10000 = difference in full years

    declare @as_of datetime, @bday datetime;
    select @as_of = '2009/10/15', @bday = '1980/4/20'
    
    select 
        Convert(Char(8),@as_of,112),
        Convert(Char(8),@bday,112),
        0 + Convert(Char(8),@as_of,112) - Convert(Char(8),@bday,112), 
        (0 + Convert(Char(8),@as_of,112) - Convert(Char(8),@bday,112)) / 10000
    

    output

    20091015    19800420    290595  29
    

提交回复
热议问题