You dont require to use a cursor here. You can apply a set based approach like :-UPDATE tSET t.Accumulated=d.TotalFROM TOTAL tINNER JOIN (SELECT Customer,Item,SUM(Amount) AS Total FROM DETAIL GROUP BY Customer,Item)dINSERT INTO TOTAL(Customer,Item,Accumulated)SELECT d.Customer,d.Item,d.TotalFROM (SELECT Customer,Item,SUM(Amount) AS Total FROM DETAIL GROUP BY Customer,Item)dLEFT JOIN TOTAL tON t.Customer=d.CustomerAND t.Item=d.ItemWHERE t.Customer IS NULL
WHat i've done here is to group the detail data based on Customer & Iem to get one line per combination and check if the combination exists. If exists, we update Accumulated with sum of amounts from detail rows. If not we will insert a new row with sum value.