Garadin (1/10/2009)
DECLARE @DOB datetime
SET @DOB = '1/20/1980'
SELECT CASE
WHEN DATEPART(DY,GETDATE()) >= DATEPART(DY,@DOB)
THEN DATEDIFF(YY,@DOB,GETDATE())
ELSE DATEDIFF(YY,@DOB,GETDATE())-1
END
Oh, be careful now. I know this is an old post but the code above doesn't work 100% of the time. For example, it returns "0" years if @DOB = '2000-03-31' and the current date is '2001-03-31'. The problem is that DY contains different values for dates after 28 Feb for ALL leap years.
Try it yourself...
DECLARE @DOB datetime
,@Now datetime
SELECT @DOB = '3/31/2000'
,@Now = '3/31/2001'
SELECT CASE
WHEN DATEPART(DY,@Now) >= DATEPART(DY,@DOB)
THEN DATEDIFF(YY,@DOB,@Now)
ELSE DATEDIFF(YY,@DOB,@Now)-1
END
;
--Jeff Moden
Change is inevitable... Change for the better is not.