• Katerine459 (2/27/2015)


    ... what is that?

    This generates a Tally table on the fly with zero reads.

    Could you please take me through what that does? Your comment, "Enough for 12 years" implies that it returns 144 numbers (one for each month for 12 years)?

    That's right. Well, actually it generates 145 because of the SELECT 0 UNION ALL.

    And that there's a cross join or an outer join in there somewhere? Is "E, E x" shorthand for "E CROSS JOIN E"?

    That's right, it's known as the old-join syntax which creates a cross join because there's no condition to join.

    And I'm familiar (slightly) with using SELECT Row_NUMBER() OVER(ORDER BY), but only in the context of getting the first/last/maximum/minumum row for something... what does SELECT NULL do in this context?

    I'm using (SELECT NULL) because ORDER BY in the OVER() clause doesn't admin constants. I could use anything but the important reason is that I don't care about the order, I just want to get consecutive numbers from 1 to 144 ()in this case. You can check what it does if you run that part of the code. Here's how I test cascading CTEs:

    WITH E(N) AS(

    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL

    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 --12 rows

    )

    --,cteTally(N) AS(

    SELECT 0

    UNION ALL

    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL))

    FROM E, E x --Enough for 12 years

    --)

    --SELECT ClientID,

    -- MONTH( DATEADD(MONTH, N, ISNULL(StartDate,'20140101'))) MonthNum,

    -- YEAR( DATEADD(MONTH, N, ISNULL(StartDate,'20140101'))) YearNum

    --FROM cteTally t

    --JOIN dbo.Client_Clients c ON DATEADD( MONTH, t.N * -1, GETDATE()) >= StartDate

    -- OR (DATEADD( MONTH, t.N * -1, GETDATE()) >= '20140101'

    -- AND StartDate IS NULL)

    --WHERE ExitDate IS NULL

    --AND N % SheetsRequiredNumMonths = 0

    ----AND ClientID = @ClientID

    Sorry about the stupid questions, but I really like to understand the ins and outs, and my head is so. Very. Foggy!

    Thanks again, (to everybody, not just Luis Cazares). 🙂

    I don't believe that those are stupid questions since you had most of the answer and it's good to be sure about the code you're implementing.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2