DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`route_beforeInsert` BEFORE INSERT ON `route` FOR EACH ROW BEGIN DECLARE vDefaultAgencyModeFk INT; DECLARE vUserFk INT ; SET vUserFk = account.myUser_getId(); SET NEW.editorFk = vUserFk; SET NEW.firstEditorFk = vUserFk; SET NEW.commissionWorkCenterFk = ( SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk) FROM vn.routeConfig r LEFT JOIN vn.business b ON b.workerFk = vUserFk AND NEW.dated BETWEEN b.started AND IFNULL(b.ended, NEW.dated)); IF ISNULL(NEW.agencyModeFk) THEN SELECT r.agencyModeFk INTO vDefaultAgencyModeFk FROM routeDefaultAgencyMode r JOIN business b ON b.workCenterFk = r.workCenterFK JOIN worker w ON w.businessFk = b.id WHERE b.workerFk = vUserFk; SET NEW.agencyModeFk = vDefaultAgencyModeFk; END IF; END$$ DELIMITER ;