DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`invoiceOut_beforeInsert` BEFORE INSERT ON `invoiceOut` FOR EACH ROW BEGIN DECLARE vRef CHAR(10) ; IF YEAR(NEW.issued) <= 2021 THEN SELECT CONCAT(NEW.serial, IFNULL(RIGHT(MAX(i.ref), LENGTH(i.ref)-1) , RPAD(CONCAT(c.sage200Company, RIGHT(YEAR(util.VN_CURDATE()), 2)), 7,'0')) + 1) INTO vRef FROM invoiceOut i LEFT JOIN company c ON c.id = i.companyFk WHERE i.serial = NEW.serial AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.dayEnd(util.lastDayOfYear(NEW.issued)) AND c.id = NEW.companyFk; ELSE SELECT CONCAT(NEW.serial, IFNULL(RIGHT(MAX(i.ref), LENGTH(i.ref)-1) , RPAD(CONCAT(c.sage200Company, RIGHT(YEAR(util.VN_CURDATE()), 2)), 8,'0')) + 1) INTO vRef FROM invoiceOut i LEFT JOIN company c ON c.id = i.companyFk WHERE i.serial = NEW.serial AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.dayEnd(util.lastDayOfYear(NEW.issued)) AND c.id = NEW.companyFk; END IF; SET NEW.ref = vRef; END$$ DELIMITER ;