• I'm not sure how SQL Server is going to deal with all those correlated queries. I'd love to see the execution plan for this. Can you get the actual execution plan and post it?

    Without specifics, I'll make this suggestion. You've got the same two queries over and over through the code there, just changing the SELECT list. What about consolidating all that down to a single two queries and then combine them. If you can't JOIN them together, then UNION them, but repeating the query over and over like that seems likely to give the optimizer fits. But, understand, I'm speculating on inadequate information.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning