Finding someone's age in SQL

前端 未结 7 2333
孤街浪徒
孤街浪徒 2020-12-16 21:11

In a SQL Server database, I record people\'s date of birth. Is there an straight-forward method of working out the person\'s age on a given date using SQL only?

Usi

7条回答
  •  无人及你
    2020-12-16 22:05

    There is another way that is a bit simpler:

    Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age
    

    Because the rounding here is very granular, this is almost perfectly accurate. The exceptions are so convoluted that they are almost humorous: every fourth year the age returned will be one year too young if we A) ask for the age before 6:00 AM, B) on the person's birthday and C) their birthday is after February 28th. In my setting, this is a perfectly acceptable compromise.

提交回复
热议问题