• 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


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)