DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`buy_label`(IN entry_id_ INT, IN groupby TINYINT(1))
BEGIN

	DECLARE done INT DEFAULT 0;
	DECLARE label INT;
	DECLARE id INT;
	DECLARE recordset CURSOR FOR SELECT Compres.Etiquetas, Compres.Id_Compra FROM Compres INNER JOIN
        (SELECT e.Id_entrada FROM Entradas e INNER JOIN (
            SELECT Id_Entrada,Inventario,Id_proveedor,travel_id,Id_Agencia FROM Entradas e1 INNER JOIN travel t ON e1.travel_id = t.id WHERE Id_Entrada = entry_id_) y 
        ON y.Inventario = e.Inventario AND e.travel_id = y.travel_id AND e.Id_proveedor = y.Id_proveedor AND y.Id_Agencia = e.Id_Agencia
        WHERE (0 OR e.Id_Entrada = entry_id_)) entry_label 
    ON Compres.Id_Entrada = entry_label.Id_entrada 
    INNER JOIN Articles ON Compres.Id_Article = Articles.Id_Article WHERE Articles.Imprimir <> FALSE;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
   
    DROP TEMPORARY TABLE IF EXISTS `buy_label_source`;

	CREATE TEMPORARY TABLE `buy_label_source`
	(
		`buy_id` INT(11) NOT NULL
	)
    
	ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
	OPEN recordset;

	REPEAT

		FETCH recordset INTO label, id;
		WHILE label > 0 DO
	
			SET label = label - 1;
			INSERT INTO buy_label_source (buy_id) VALUES (id);

		END WHILE;

	UNTIL done END REPEAT;

END$$
DELIMITER ;
