Search 
Thursday, May 23, 2013 ..:: Examples » Datetime TSQL » Calculating Age ::.. Register  Login
 Calculating Age

This example calculates the age. It does this by first determining the number of years between the current date, and the Birthday. Then if the birthday has not happened this year then 1 is subtracted from the number of years between the current date and the Birthday. 

-- Calculating Age
-- Written by: Gregory A. Larsen Date: 2/23/2008

DECLARE @BirthDay DATETIME
SET @BirthDay = '1/22/1967'
SELECT
 YEAR(GETDATE()) - YEAR(@BirthDay) -
 (CASE
-- IF Birthday for this year has not come yet, then subtract one
  WHEN (MONTH(@BirthDay) > MONTH(GETDATE()))
   OR (MONTH(@BirthDay) = MONTH(GETDATE())
   AND DAY(@BirthDay) > DAY(GETDATE()))
  THEN 1 
  ELSE 0 END)

 

 

  
SQL Tools Heaven
SQLMonitor_160x600_BackToTheFuture_M2
SQL Backup
Copyright 2007, 2008 by SQLServerExamples.com   Terms Of Use  Privacy Statement