I have a date of birth column to which I need to compare the current date and return the difference as age. Currently I am using the following query :
DECLARE @DateOfBirth date = '2000-07-27'
DECLARE @CurrentDate date = '2015-07-25'
SELECT
@Age = DATEDIFF(YEAR, @DateOfBirth, @CurrentDate)
I am getting a difference as 15, but the desired result should be 14. This is because it compares the year and gets the difference between 2015 and 2000. So I used the following query :
select
@Age = CAST(datediff(day, @DOB, @CurrentDate) / 365.2425 AS INT)
RESULT : 14
But when I change the Date Of Birth value to '2000-07-25', I still get the value of 14, but it should be 15 since the date difference is exactly 15 years.
How can I get the exact year difference from this?
Best Answer
Subtract one from each other in YYYYMMDD format, and divide by 10000 using integer division (which rounds down).
So:
20150725-20000727 = 149998, and 149998 / 10000 = 14
You can also use
CONVERT(int,CONVERT(char(8),@CurrentDate,112))
, because style 112 is YYYYMMDD, but that's a little obfuscated in my opinion.