Calculate age in SQL with years, months, and days

In this article we take birth date and using the “GetDate” function to find the years, months and days. So let’s have a look at a practical example of how to calculate age in SQL Server 2008. The example is developed in SQL Server 2008 using the SQL Server Management Studio.

Date Format = MM/DD/YYYY

DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int

SELECT @date = ’04/06/1988′

SELECT @tmpdate = @date

SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) – CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) – CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())

SELECT @years as Years, @months as Months, @days as Days

Output:

Output
calculate age in SQL with years, months, and days

Happy Coding 🙂

Advertisements

2 thoughts on “Calculate age in SQL with years, months, and days

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