• I am guessing that you didn't read through the article I suggested and understand this code. You can't reference the cte by multiple statements after it is declared. You need to combine your two update statements. I noticed you also removed the order by in the cte. This order is MANDATORY or you don't know what order the results will be returned. And why oh why did you put this into nested while loops??? You totally destroyed any chance at making this remotely quick. You need to start over here.

    Can you post ddl (create table scripts), sample data (insert statements) and desired output based on your sample data? There is no need to put this in nested loops.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/