DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`prepare_ticket_list`(vStartingDate DATETIME, vEndingDate DATETIME)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;    
	CREATE TEMPORARY TABLE tmp.ticket_list
		(PRIMARY KEY (Id_Ticket))
		ENGINE = MEMORY
		SELECT t.Id_Ticket, c.Id_Cliente
			FROM Tickets t
				LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.Id_Ticket
				JOIN Clientes c ON c.Id_Cliente = t.Id_Cliente
			WHERE c.typeFk IN ('normal','handMaking','internalUse')
				AND (
					Fecha BETWEEN util.today() AND vEndingDate
					OR (
						ts.alertLevel < 3
						AND t.Fecha >= vStartingDate
						AND t.Fecha < util.today()
					)
				);
END$$
DELIMITER ;
