Script to Determine Age at a Given Date

Posted: November 21, 2011 in SQL Server 2005

If you need a caculate age at a given date, you can try the following:

-- Declare variables
DECLARE @ldt_birthdate   DATETIME;
DECLARE @ldt_age_at_date DATETIME;
DECLARE @li_age_at       INT;

-- Initialise variables
SET @ldt_birthdate   = '1985-03-27';
SET @ldt_age_at_date = GETDATE();
SET @li_age_at       = 0;

IF @ldt_birthdate <= @ldt_age_at_date
BEGIN
   SET @li_age_at = DATEDIFF(yy, @ldt_birthdate, @ldt_age_at_date);

   IF ((MONTH(@ldt_age_at_date) * 100) + DAY (@ldt_age_at_date)) < 
      ((MONTH(@ldt_birthdate)   * 100) + DAY (@ldt_birthdate))
   BEGIN      
     SET @li_age_at = @li_age_at - 1;
   END;
  
   -- Return age
   SELECT @li_age_at;
END
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s