• Jeff Moden - funny, I was thinking about how you'd react if you saw this code, and BAM, there you are!

    Evgeny - great code.  I'm trying to think if there's a way to run this without the RBAR.  I guess you could dynamically create the INSERT... EXEC statements, but that's essentially the same thing.

    I do have a couple of questions: 

    1. Why the 'ORDER BY IndexSizeKB DESC' on the initial SELECT statement?  It doesn't matter which order the rows are processed and inserted into the table since you don't have to order your results coming out of the cursor.
    2. Secondly, you could run 'SELECT * INTO #estimates_tmp_r FROM #estimates_tmp_p WHERE 1 = 1' instead of a second CREATE TABLE statement.  That probably won't make much of a difference in resources, creation time, etc.  In fact, the execution plan shows the CREATE TABLE statement as taking 0% of the query cost when run along with the SELECT * INTO...  

    Does anyone else have any comments on my ideas here?