DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`f10_no_vincular`(lngEntrada INTEGER)
BEGIN
	DECLARE datFecha DATE DEFAULT util.VN_CURDATE();
    
-- Modifica el NoVincular si hay dos entradas con el mismo Packing y el mismo Id_Articulo 
	DROP TEMPORARY TABLE IF EXISTS f10_no_vincular_;
	CREATE TEMPORARY TABLE IF NOT EXISTS f10_no_vincular_
		SELECT c.Id_Entrada,c.Id_Compra,c.Id_Article, c.Novincular, c.Packing, be.pri
		FROM Compres c
			JOIN buy_edi be ON c.buy_edi_id = be.id	AND be.fec = datFecha
			LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = c.Id_Entrada
		WHERE
			((ek.Id_Entrada IS NOT NULL AND ek.sub IS NULL)
				OR (c.Id_Entrada = 9200 AND be.ok <> FALSE)
				OR c.Id_Entrada = lngEntrada) AND Id_Article <> 90;
                       
    -- Modifica el NoVincular si hay dos entradas con el mismo Packing y el mismo Id_Articulo
    DROP TEMPORARY TABLE IF EXISTS f10_mismo_Packing;
	CREATE TEMPORARY TABLE IF NOT EXISTS f10_mismo_Packing
		SELECT * FROM (
			SELECT * FROM f10_no_vincular_
		ORDER BY pri DESC
		LIMIT 10000000000000000000) t
			GROUP BY Id_Article,Packing
			HAVING count(Id_Compra) > 1 AND BIT_OR(Id_Entrada = 9200);
 
	UPDATE Compres c
			JOIN buy_edi be ON c.buy_edi_id = be.id	AND be.fec = datFecha
			JOIN f10_mismo_Packing f ON f.Id_Article = c.Id_Article AND c.Packing = f.Packing
			LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = f.Id_Entrada
        SET c.Novincular = IF(c.Id_Compra = f.Id_Compra,0,1)
		WHERE
			((ek.Id_Entrada IS NOT NULL AND ek.sub IS NULL)
				OR (c.Id_Entrada = 9200 AND be.ok <> FALSE)
				OR c.Id_Entrada = lngEntrada);
  
-- Modifica el Id_Articulo si hay dos entradas con packing y el mismo Id_Articulo 
	DROP TEMPORARY TABLE IF EXISTS f10_mismo_Articulo;
	CREATE TEMPORARY TABLE IF NOT EXISTS f10_mismo_Articulo
		SELECT Id_Article FROM (
			SELECT * FROM (
				SELECT * FROM f10_no_vincular_
				ORDER BY Id_Entrada = 9200 DESC
				LIMIT 10000000000000000000) t
				GROUP BY Id_Article,Packing ) t 
          GROUP BY Id_Article HAVING COUNT(*) > 1 AND BIT_OR(Id_Entrada = 9200);
          SELECT 4;       
	UPDATE Compres c
		JOIN buy_edi be ON c.buy_edi_id = be.id	AND be.fec = datFecha
		JOIN f10_mismo_Articulo f ON f.Id_Article = c.Id_Article
		LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = c.Id_Entrada
	SET c.Id_Article = 90
	WHERE c.Id_Entrada = 9200 AND be.ok <> FALSE;
  
	DROP TEMPORARY TABLE IF EXISTS f10_no_vincular_;
	DROP TEMPORARY TABLE IF EXISTS f10_mismo_Packing;
    DROP TEMPORARY TABLE IF EXISTS f10_mismo_Articulo;
END$$
DELIMITER ;
