• I'll second what GSquared just said.

    Sometimes, the optimizer needs a little help. Sometimes that help is to just very quickly isolate a much smaller subset in a temp table (which the optimizer sometimes does on its own, BTW. They're called "Work" tables and you can see them with SET STATISTICS IO ON). It can make all the difference in the world.

    Probably the greatest example that I can personally remember was with a year-end query that some folks had written at a previous company. It was so resource intensive that they actually asked me to build a separate instance of the database to run the bloody query because it would paralyze the server for a good 45 minutes.

    I got it down to 8 seconds that made only a "pip" on CPU usage by isolating one part of the query to a Temp Table and then joining on that Temp Table. To be sure, the data in the Temp Table was only used once.

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