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

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

    After trying MANY methods, this works 100% of the time using the modern MS SQL FORMAT function instead of convert to style 112. Either would work but this is the least code.

    Can anyone find a date combination which does not work? I don't think there is one :)

    --Set parameters, or choose from table.column instead:
    
    DECLARE @DOB    DATE = '2000/02/29' -- If @DOB is a leap day...
           ,@ToDate DATE = '2018/03/01' --...there birthday in this calculation will be 
    
    --0+ part tells SQL to calc the char(8) as numbers:
    SELECT [Age] = (0+ FORMAT(@ToDate,'yyyyMMdd') - FORMAT(@DOB,'yyyyMMdd') ) /10000
    

提交回复
热议问题