DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`getShipmentHour`(vTicket INT) RETURNS int(11) NOT DETERMINISTIC READS SQL DATA BEGIN DECLARE vShipmentHour INT; SELECT HOUR(shipped) INTO vShipmentHour FROM ticket WHERE id = vTicket; IF vShipmentHour = 0 THEN DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; CREATE TEMPORARY TABLE tmp.production_buffer ENGINE = MEMORY SELECT am.agencyFk as agency_id , t.warehouseFk as warehouse_id , a.provinceFk as province_id , 0 as Hora , 0 as Departure FROM ticket t JOIN agencyMode am on am.id = t.agencyModeFk JOIN address a on a.id = t.addressFk WHERE t.id = vTicket; SELECT Hora INTO vShipmentHour FROM tmp.production_buffer; END IF; RETURN vShipmentHour; END$$ DELIMITER ;