DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`( vSectorFk INT ) BEGIN DECLARE vId INT; DECLARE vLastParkingFk INT; DECLARE vNextParkingFk INT; SELECT sh.parkingFk INTO vLastParkingFk FROM itemShelvingPlacementSupply isps JOIN itemShelving ish ON ish.id = isps.itemShelvingFk JOIN shelving sh ON sh.id = ish.shelvingFk WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; SET vNextParkingFk = itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); SELECT ipsl.id INTO vId FROM itemPlacementSupplyList ipsl JOIN itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk WHERE ipsl.saldo > 0 AND (ipsl.repoUserFk is NULL OR ipsl.repoUserFk = getUser()) AND ipsl.sectorFk = vSectorFk ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created LIMIT 1; UPDATE itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; SELECT * FROM itemPlacementSupplyList WHERE id = vId AND sectorFk = vSectorFk; END$$ DELIMITER ;