• Brandie Tarvin (10/3/2013)


    Remember, not all cursors are bad. Some of them are necessary, and some of them can be faster than regular WHILE loops or other code. It just depends on the cursor.

    No while loops here... Just to give you an example of what I've found, there's a trigger on a table ProductStore that has for each product the quantity on a store.

    The update/insert/delete triggers call a SP that updates quantity on the Products table. But does it using a cursor to go over the INSERTED and DELETED records an calls the procedure updateProductQuantity @product, @newquantity, @type (delete or add).

    This can be replaced inside the trigger with

    UPDATE Produts SET Qnt = Qnt + t.Qnt FROM (SELECT Product, SUM(Qnt) Qnt FROM INSERTED GROUP BY Product) t WHERE t.Product = Products.Product

    and the same with DELETED...

    No need to go over each record in INSERTED and DELETED and call a procedure...

    Thanks,

    Pedro



    If you need to work better, try working less...