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

后端 未结 24 1554
无人共我
无人共我 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:02

    Try this...

    SELECT CASE WHEN
     (DATEADD(year,DATEDIFF(year, @datestart  ,@dateend) , @datestart) > @dateend)
    THEN DATEDIFF(year, @datestart  ,@dateend) -1
    ELSE DATEDIFF(year, @datestart  ,@dateend)
    END
    

    Basically the "DateDiff( year...", gives you the age the person will turn this year, so i have just add a case statement to say, if they have not had a birthday yet this year, then subtract 1 year, else return the value.

提交回复
热议问题