How to calculate age in T-SQL with years, months, and days

后端 未结 24 2182
无人共我
无人共我 2020-11-22 05:42

What would be the best way to calculate someone\'s age in years, months, and days in T-SQL (SQL Server 2000)?

The datediff function doesn\'t handle year

24条回答
  •  面向向阳花
    2020-11-22 06:14

    The same sort of thing as a function.

    create function [dbo].[Age](@dayOfBirth datetime, @today datetime)
       RETURNS varchar(100)
    AS
    
    Begin
    DECLARE @thisYearBirthDay datetime
    DECLARE @years int, @months int, @days int
    
    set @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)
    set @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END)
    set @months = MONTH(@today - @thisYearBirthDay) - 1
    set @days = DAY(@today - @thisYearBirthDay) - 1
    
    return cast(@years as varchar(2)) + ' years,' + cast(@months as varchar(2)) + ' months,' + cast(@days as varchar(3)) + ' days'
    end
    

提交回复
热议问题