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

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

    What about a solution with only date functions, not math, not worries about leap year

    CREATE FUNCTION dbo.getAge(@dt datetime) 
    RETURNS int
    AS
    BEGIN
        RETURN 
            DATEDIFF(yy, @dt, getdate())
            - CASE 
                WHEN 
                    MONTH(@dt) > MONTH(GETDATE()) OR 
                    (MONTH(@dt) = MONTH(GETDATE()) AND DAY(@dt) > DAY(GETDATE())) 
                THEN 1 
                ELSE 0 
            END
    END
    

提交回复
热议问题