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

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

    So many of the above solutions are wrong DateDiff(yy,@Dob, @PassedDate) will not consider the month and day of both dates. Also taking the dart parts and comparing only works if they're properly ordered.

    THE FOLLOWING CODE WORKS AND IS VERY SIMPLE:

    create function [dbo].[AgeAtDate](
        @DOB    datetime,
        @PassedDate datetime
    )
    
    returns int
    with SCHEMABINDING
    as
    begin
    
    declare @iMonthDayDob int
    declare @iMonthDayPassedDate int
    
    
    select @iMonthDayDob = CAST(datepart (mm,@DOB) * 100 + datepart  (dd,@DOB) AS int) 
    select @iMonthDayPassedDate = CAST(datepart (mm,@PassedDate) * 100 + datepart  (dd,@PassedDate) AS int) 
    
    return DateDiff(yy,@DOB, @PassedDate) 
    - CASE WHEN @iMonthDayDob <= @iMonthDayPassedDate
      THEN 0 
      ELSE 1
      END
    
    End
    

提交回复
热议问题