• rajemessage 14195 (11/30/2016)


    i have taught my team to use set based operation strictly,...

    Excellent. You're a man after my own heart.

    rajemessage 14195 (11/30/2016)


    ... but there are cases where ,we are forced.

    That's what I'm talking about. A lot of people think that a given process simply can't be done without an explicit loop or a bit of "Hidden RBAR". It's not because they're bad programmers. It just that they sometimes don't know how. For example, is it possible to write a query against a million node hierarchy that will return the total sales for each person AND the total sales for each level of the "downline" for that person in less than a minute or will you need a loop for it? Most people end up writing a loop for such a thing and it can totally be avoided fairly easily but only if you know how.

    Having gotten that off my chest, let's get to your question of...

    so specific to loop: i wanted to know that , should we use temp table,even in single table looping also

    like if i have to loop single table , should i make temp table , to reduce lock and block.

    That's a 'Tried'n'True' method of 'Divide'n'Conquer' and frequently has the side benefits of moving the problem to high-speed memory (things in TempDB start there and only spill to disk if they get big enough) as well as allowing the data to persist during troubleshooting efforts. It's one of the reasons I don't use cursors. It's true that a static FIREHOSE cursor runs just as fast as a well written WHILE loop/Temp Table combination and can actually be easier to write but are more difficult to troubleshoot because you can't see the underlying data without jumping through the DEBUG hullabaloo. It also has the action of possibly acting as a simplification or pre-aggregation of data greatly reducing the needs for joins that would otherwise possibly cause a many-to-many race condition requiring the use of (ugh!) DISTINCT to uniquify the output.

    But, again, "It Depends" and you simply need to try it. Populating the Temp Table and, perhaps, Indexing it may take longer that you might expect but, at the same time, I've done things like reducing a server crippling 45 minute run to a 3 second burp by using Temp Tables as you suggest.

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