Skip to content

Instantly share code, notes, and snippets.

@jakobii
Last active September 8, 2022 12:45
Show Gist options
  • Save jakobii/118d6e21834fa6ae163353a96872b19d to your computer and use it in GitHub Desktop.
Save jakobii/118d6e21834fa6ae163353a96872b19d to your computer and use it in GitHub Desktop.

On MS SQL Server

to Accurately calcutalte the age of something this works for most situations

SELECT
  FLOOR( --floor function returns age in years
    CAST( DATEDIFF( DAY, /*StartDate*/ , /*EndDate*/ ) AS DEC(38,16) ) / CAST(365.2425 AS DEC(38,16)) 
  ) As AgeInYears

FROM SomeTable
Example 1:

calculate age from current date using GETDATE

SELECT
  FLOOR( CAST( DATEDIFF( DAY, e.BirthDate , GETDATE() ) AS DEC(38,16) ) / CAST(365.2425 AS DEC(38,16)) ) As AgeInYears

FROM Employees AS e
Example 2:

Calculate age from a specific date using DATEFROMPARTS

SELECT
  FLOOR( CAST( DATEDIFF( DAY, p.ReleaseDate , DATEFROMPARTS(3030,3,11) ) AS DEC(38,16) ) / CAST(365.2425 AS DEC(38,16)) ) As AgeInYears

FROM Products as p
Other Helpful Links
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment