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

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

    DateTime values in T-SQL are stored as floats. You can just subtract the dates from each other and you now have a new date that is the timespan between them.

    declare @birthdate datetime
    set @birthdate = '6/15/1974'
    
    --age in years - short version
    print year(getdate() - @birthdate) - year(0)
    
    --age in years - visualization
    declare @mindate datetime
    declare @span datetime
    
    set @mindate = 0
    set @span = getdate() - @birthdate
    
    print @mindate
    print @birthdate
    print getdate()
    print @span
    --substract minyear from spanyear to get age in years
    print year(@span) - year(@mindate)
    print month(@span)
    print day(@span)
    

提交回复
热议问题