DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`expedition_beforeInsert` BEFORE INSERT ON `expedition` FOR EACH ROW BEGIN DECLARE vMaxCounter INT; SET NEW.editorFk = account.myUser_getId(); IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; SELECT IFNULL(MAX(counter),0) + 1 INTO vMaxCounter FROM expedition e JOIN alertLevel al ON al.code = 'DELIVERED' JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk WHERE t2.id = NEW.ticketFk AND ts.alertLevel < al.id AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = vMaxCounter; END IF; END$$ DELIMITER ;