I'm looking for the best way (short & efficient) to compute an employee's age based on a birth date and a target date. The DATEDIFF function does't seem to work properly (at least according to the way I envision it). I've figured out two other methods to compute the proper age, but they seem a bit involved for my tastes. Here's the sample code:
DECLARE
@birthdt DATETIME,
@targetdt DATETIME
SELECT
@birthdt = '1/15/1930',
@targetdt = '1/1/2001'
SELECT
wrongage0 = DATEDIFF(yy, @birthdt, @targetdt),
wrongage1 = CONVERT(INT, DATEDIFF(mm, @birthdt, @targetdt) / 12),
rightage0 = CONVERT(INT,
CASE WHEN ((DATEPART(mm, @birthdt) = DATEPART(mm, @targetdt)) AND
(DATEPART(dd, @birthdt) = DATEPART(dd, @targetdt)))
THEN DATEDIFF(dd, @birthdt, @targetdt) / 365.2425 + 0.002
ELSE DATEDIFF(dd, @birthdt, @targetdt) / 365.2425
END),
rightage1 = CONVERT(INT, DATEDIFF(mm, @birthdt, @targetdt) / 12) -
(CASE WHEN (DATEPART(mm, @birthdt) = DATEPART(mm, @targetdt)) AND
(DATEPART(dd, @birthdt) > DATEPART(dd, @targetdt)) THEN 1 ELSE 0 END)
wrongage0 wrongage1 rightage0 rightage1
----------- ----------- ----------- -----------
71 71 70 70