DELIMITER $$ CREATE PROCEDURE orderupdate() BEGIN DROP TABLE temp_order_details; CREATE TEMPORARY TABLE IF NOT EXISTS temp_order_details as (select a.act_id order_id, i.act_id order_item_id, e.name, a.status, deliveryStatus.value as deliveryStatus, fi.quantity as quantity, receivedQuantity.value as receivedQuantity, cancelledQuantity.value cancelledQuantity from acts a join act_relationships r on r.source_id = a.act_id and r.arch_short_name = "actRelationship.supplierOrderItem" join act_details deliveryStatus on a.act_id = deliveryStatus.act_id and deliveryStatus.name = "deliveryStatus" join acts i on r.target_id = i.act_id join financial_acts fi on i.act_id = fi.financial_act_id join act_details receivedQuantity on i.act_id = receivedQuantity.act_id and receivedQuantity.name = "receivedQuantity" join act_details cancelledQuantity on i.act_id = cancelledQuantity.act_id and cancelledQuantity.name = "cancelledQuantity" join participations p on p.act_id = a.act_id and p.arch_short_name = "participation.supplier" join entities e on p.entity_id = e.entity_id where a.arch_short_name = "act.supplierOrder" and a.status = "ACCEPTED" and deliveryStatus.value = "PENDING"); //may want to add e.name LIKE `%PROVET%` set @numrow = (SELECT COUNT(*) FROM temp_order_details); set @currow = 0; PREPARE ordersql FROM 'SELECT order_id, order_item_id, quantity INTO @order_id, @order_item_id, @qty from temp_order_details LIMIT 1 OFFSET ?'; PREPARE updatesql FROM 'update act_details d, acts a set d.value = ? where a.act_id = d.act_id and d.name = "receivedQuantity" and a.act_id = ?'; PREPARE updatesql2 FROM 'update act_details d, acts a set d.value = "FULL" where a.act_id = d.act_id and d.name = "deliveryStatus" and d.value = "PENDING" and a.act_id = ?'; REPEAT EXECUTE ordersql USING @currow; EXECUTE updatesql using @qty, @order_item_id; EXECUTE updatesql2 USING @order_id; Set @currow = @currow +1; UNTIL @currow = @numrow END REPEAT; DEALLOCATE PREPARE ordersql; DEALLOCATE PREPARE updatesql; DEALLOCATE PREPARE updatesql2; END$$ DELIMITER ; this creates a procedure you can call from mysql CALL orderupdate;