Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Calculate Birthday In Years

From Wiki

Jump to: navigation, search

To calculate a person's age in SQL is pretty straight forward. You take the difference in years and if todays month and date is less than the month and date of the birthdate then you subtract -1

If you run the code below on 2007-11-28 the output is 37, if you change the birth date to 19701129 it return 36

  1. Select all
  2.  
  3.     DECLARE @Birthday DATETIME, @DateToCheck DATETIME
  4.     SELECT @Birthday = '19701127', @DateToCheck = CURRENT_TIMESTAMP
  5.      
  6.      
  7.     SELECT DATEDIFF(YEAR, @Birthday, @DateToCheck) -
  8.         CASE WHEN DATEPART(mm,@Birthday) > DATEPART(mm,@DateToCheck)
  9.        OR (DATEPART(mm,@Birthday) = DATEPART(mm,@DateToCheck)
  10.        AND DATEPART(dd,@Birthday) > DATEPART(dd,@DateToCheck))
  11.         THEN 1 ELSE 0 END

Contributed by: --SQLDenis 17:04, 30 May 2008 (GMT)

  1. SELECT YEAR(@DateToCheck - DATEPART(dy, @Birthday) + 1) - YEAR(@Birthday)

--ErikE 00:47, 3 June 2008 (GMT)

Part of SQL Server Programming Hacks

Section Dates

124 Rating: 2.3/5 (72 votes cast)