UPDATE C_Order o SET IsDelivered = 'N' WHERE o.IsDelivered = 'Y' AND o.processed = 'Y' AND (o.issotrx = 'Y' OR (o.issotrx = 'N' AND (SELECT dt.isreturn FROM c_doctype dt WHERE o.c_doctypetarget_id = dt.c_doctype_id) = 'Y')) AND EXISTS (SELECT 1 FROM c_orderline ol WHERE o.c_order_id = ol.c_order_id AND ol.c_order_discount_id IS NULL AND ol.QTYORDERED <> ol.QTYDELIVERED );