DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`entry_getCommission`(vTravelFk INT, vCurrencyFk INT, vSupplierFk INT ) RETURNS int(11) NOT DETERMINISTIC READS SQL DATA BEGIN DECLARE vCommission INT; DECLARE vCurrentCommission INT; DECLARE vIsNotEUR INT; DECLARE vLastEntryFk INT; DECLARE vTravelFkLanded INT; SELECT count(*) INTO vIsNotEUR FROM currency c WHERE c.code <> 'EUR' AND id = vCurrencyFk; IF vIsNotEUR THEN SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission FROM travel t LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped WHERE t.id = vTravelFk ORDER BY r.`dated` DESC LIMIT 1; RETURN IFNULL(vCommission, 0); ELSE SELECT landed INTO vTravelFkLanded FROM travel WHERE id = vTravelFk; SELECT e.id INTO vLastEntryFk FROM `entry` e JOIN travel tr ON tr.id = e.travelFk WHERE tr.landed < vTravelFkLanded AND e.supplierFk = vSupplierFk ORDER BY (vTravelFkLanded - tr.landed) ASC, tr.landed DESC LIMIT 1; IF vLastEntryFk THEN SELECT commission INTO vCurrentCommission FROM `entry` WHERE id = vLastEntryFk; ELSE SELECT commission INTO vCurrentCommission FROM supplier s WHERE s.id = vSupplierFk; END IF; RETURN vCurrentCommission; END IF; END$$ DELIMITER ;