DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`warehouseFitting`(IN vWhOrigin INT , IN vWhDestiny INT) BEGIN DECLARE vCacheVisibleOriginFk INT; DECLARE vCacheVisibleDestinyFk INT; CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin); CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny); SELECT i.id itemFk, i.longName, i.size, i.subName, vOrigin.visible AS Origen, vDestiny.visible Destino FROM vn.item i JOIN vn.itemType it ON it.id = i.typeFk LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id LEFT JOIN cache.visible vDestiny ON vDestiny.calc_id = vCacheVisibleDestinyFk AND vDestiny.item_id = i.id WHERE (vOrigin.visible OR vDestiny.visible) AND it.categoryFk < 6 ORDER BY IF(vOrigin.visible,0,1), longName, size, subName; END$$ DELIMITER ;