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 Id_Ticket, c.Id_Cliente
			FROM vn.ticket t
				LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id
				JOIN Clientes c ON c.Id_Cliente = t.clientFk
			WHERE c.typeFk IN ('normal','handMaking','internalUse')
				AND (
					t.shipped BETWEEN util.today() AND vEndingDate
					OR (
						ts.alertLevel < 3
						AND t.shipped >= vStartingDate
						AND t.shipped < util.today()
					)
				);
END$$
DELIMITER ;
