• Since you're using a temp table - you will want to add a clustered index in order to make the running totals work.

    You should start by reading Jeff's article on the matter (so you can understand why the clustered index is such a hot topic all of a sudden):

    http://www.sqlservercentral.com/articles/T-SQL/68467/[/url]

    Also since you're using temp tables, you should pre-aggregate the data so that there is ONE record per code+value combination. Referring back to your example records, having multiple likes of code=160, value= 40 would make like substantially more complicated than necessary. Praggregating would also allow you to know what your target number is on the running total.

    ----------------------------------------------------------------------------------
    Your lack of planning does not constitute an emergency on my part...unless you're my manager...or a director and above...or a really loud-spoken end-user..All right - what was my emergency again?