DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`moving_between`(vBufferA INT, vBufferB INT) BEGIN DECLARE vExpeditionFk INT; SELECT e.id INTO vExpeditionFk FROM srt.expedition e LEFT JOIN srt.moving m ON m.expeditionFk = e.id WHERE e.bufferFk = vBufferA AND ISNULL(m.id) ORDER BY e.`position` LIMIT 1; IF ISNULL(vExpeditionFk) THEN SET vExpeditionFk = srt.expedition_check(0); UPDATE srt.expedition SET bufferFk = vBufferA, `position` = 1 WHERE id = vExpeditionFk; END IF; CALL `srt`.`expedition_Relocate`(vExpeditionFk, IFNULL(vBufferB,srt.buffer_get(vExpeditionFk))); SELECT * FROM srt.moving m ORDER BY id; END$$ DELIMITER ;