• AmarettoSlim (10/19/2013)


    Can I ask why you don't want a loop? Recursion via a common table expression (CTE) can be your friend in this case.

    DECLARE @fromYear DATETIME, @toYear DATETIME

    SELECT @fromYear='1913-01-01', @toYear='1998-01-01'

    WITH YearSequence (Year) as

    (

    SELECT @fromYear AS Year

    UNION ALL

    SELECT DATEADD(YEAR, 1, Year)

    FROM YearSequence

    WHERE Year < @toyear

    )

    SELECT Year FROM YearSequence ORDER BY 1 DESC

    Because of the extremely low rowcount, you can't actually see the insidious problem with CTE's that count. Please see the following article...

    http://www.sqlservercentral.com/articles/T-SQL/74118/

    Also, your code didn't actually run right the first time I tried to run it because of missing semi-colons. You might also want to get out of the habit of using ORDER BY on a column ordinal because that method has been deprecated.

    As for why you might want to avoid a loop, do you have a good reason for why you'd want to intentionally write slower code when faster code is easily available and usually easier to write?

    --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)