• Suggestions:

    1. Include running totals utilizing the SQL 2012+ enhancements to the OVER clause (yes, the QU is still faster... but this is documented in BOL, and still beats everything else, including a cursor).

    2. Include the ROW_NUMBER trick of having two ROW_NUMBER calculations (differing by the PARTITION BY clause) and subtracting these from each other to assign the same value to sequential rows.

    If necessary, I can provide samples for both of these.

    Also - check out the article from R. Barry Young from a few years ago on re-writing cursor code to be set-based.

    If some other examples are provided, I could take this one on.

    Wayne
    Microsoft Certified Master: SQL Server 2008
    Author - SQL Server T-SQL Recipes


    If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
    Links:
    For better assistance in answering your questions
    Performance Problems
    Common date/time routines
    Understanding and Using APPLY Part 1 & Part 2