Monday, March 19, 2012

Calculate age using multiple fields

The database I work with uses a BirthDay, BirthMonth, and BirthYear field to hold data concerning an individual. I need to calculate their age - down to the day, if the individual is only days old, or month if the individual is months old, etc. I found a formula that got it to years, but no further.

Thanks for your help!

you can try this

DECLARE @.Person TABLE (
BirthMonth int
, BirthDate int
, BirthYear int
, BirthDay AS CONVERT(varchar(2),BirthMonth) + '/' + CONVERT(varchar(2),BirthDate) + '/' + CONVERT(varchar(4),BirthYear)
, Age AS CASE WHEN DATEDIFF(year,CONVERT(varchar(2),BirthMonth) + '/' + CONVERT(varchar(2),BirthDate) + '/' + CONVERT(varchar(4),BirthYear),GETDATE()) > 0 THEN
CONVERT(varchar,DATEDIFF(year,CONVERT(varchar(2),BirthMonth) + '/' + CONVERT(varchar(2),BirthDate) + '/' + CONVERT(varchar(4),BirthYear),GETDATE())) + ' year(s) old'
WHEN DATEDIFF(month,CONVERT(varchar(2),BirthMonth) + '/' + CONVERT(varchar(2),BirthDate) + '/' + CONVERT(varchar(4),BirthYear),GETDATE()) = 0 THEN
CONVERT(varchar,ABS(DATEDIFF(day,CONVERT(varchar(2),BirthMonth) + '/' + CONVERT(varchar(2),BirthDate) + '/' + CONVERT(varchar(4),BirthYear),GETDATE()))) + ' day(s) old'
ELSE
CONVERT(varchar,ABS(DATEDIFF(month,CONVERT(varchar(2),BirthMonth) + '/' + CONVERT(varchar(2),BirthDate) + '/' + CONVERT(varchar(4),BirthYear),GETDATE()))) + ' month(s) old'
END
)

INSERT
INTO @.Person
SELECT 10,21,2005

INSERT
INTO @.Person
SELECT 4,28,2007

INSERT
INTO @.Person
SELECT 5,20,2007

SELECT *
FROM @.person|||It works! Thank you so much!

No comments:

Post a Comment