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

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

    There is an easy way, based on the hours between the two days BUT with the end date truncated.

    SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM 
    

    This one has proven to be extremely accurate and reliable. If it weren't for the inner CAST on the GETDATE() it might flip the birthday a few hours before midnight but, with the CAST, it is dead on with the age changing over at exactly midnight.

提交回复
热议问题