DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`prepareTicketList`(vStartingDate DATETIME, vEndingDate DATETIME)
BEGIN
	DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket;
	CREATE TEMPORARY TABLE tmp.productionTicket
		(PRIMARY KEY (ticketFk))
		ENGINE = MEMORY
		SELECT t.id ticketFk, t.clientFk
			FROM ticket t
				JOIN alertLevel al ON al.code = 'DELIVERED'
				LEFT JOIN ticketState ts ON ts.ticketFk = t.id
				JOIN client c ON c.id = t.clientFk

			WHERE c.typeFk IN ('normal','handMaking','internalUse')
				AND (
					t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate
					OR (
						ts.alertLevel < al.id
						AND t.shipped >= vStartingDate
						AND t.shipped < util.VN_CURDATE()
					)
				);
END$$
DELIMITER ;
