IF OBJECT_ID('P_EST_NF_ENT_IT_COMPRADOR_APLICAR') IS NOT NULL
	BEGIN
		DROP PROCEDURE P_EST_NF_ENT_IT_COMPRADOR_APLICAR
	END
GO
/*
Esta procedure roda dentro da P_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE_EXEC_ALL
*/
CREATE PROCEDURE P_EST_NF_ENT_IT_COMPRADOR_APLICAR 
WITH ENCRYPTION
AS
BEGIN
DECLARE @CD_EMP INT
DECLARE @CD_FILIAL INT
DECLARE @CD_NF INT
DECLARE @CD_PROD INT
DECLARE @CD_COMPRADOR INT
PRINT 'VINCULANDO NOTA FISCAL DE ENTRADA COM O COMPRADOR'
SET NOCOUNT ON
	delete
		cpp
	from
		EST_NF_ENT_IT_PENDENCIA_COMPRADOR cpp INNER JOIN EST_NF_ENT_IT_COMPRADOR cp ON
		cpp.CD_EMP = cp.CD_EMP AND
		cpp.CD_FILIAL = cp.CD_FILIAL AND
		cpp.CD_NF = cp.CD_NF AND
		cpp.CD_PROD = cp.CD_PROD 

	DECLARE AplicarCompradorNotaFiscalEntradaCompras CURSOR FAST_FORWARD FOR
		SELECT
			E.CD_EMP,
			E.CD_FILIAL,
			E.CD_NF,
			E.CD_PROD,
			ISNULL(IT.CD_COMPRADOR,EST_PROD_COMPRADOR.CD_COMPRADOR)
		FROM
			EST_NF_ENT_IT_PENDENCIA_COMPRADOR E 
			LEFT OUTER JOIN EST_NF_ENT_PED_CP P ON E.CD_EMP    = P.CD_EMP 
											   AND E.CD_FILIAL = P.CD_FILIAL 
											   AND E.CD_NF     = P.CD_NF 
			LEFT OUTER JOIN EST_PED_CP_IT_COMPRADOR IT ON E.CD_EMP    = IT.CD_EMP 
													  AND E.CD_FILIAL = IT.CD_FILIAL 
													  AND P.CD_PED    = IT.CD_PED 
													  AND E.CD_PROD   = IT.CD_PROD 
			INNER JOIN EST_PROD_COMPRADOR_CPL ON E.CD_EMP  = EST_PROD_COMPRADOR_CPL.CD_EMP 
											 AND E.CD_PROD = EST_PROD_COMPRADOR_CPL.CD_PROD 
			INNER JOIN EST_PROD_COMPRADOR ON EST_PROD_COMPRADOR_CPL.CD_CTR = EST_PROD_COMPRADOR.CD_CTR
			
			
			 INNER JOIN EST_NF_ENT_IT ON E.CD_EMP    = EST_NF_ENT_IT.CD_EMP
			                         AND E.CD_FILIAL = EST_NF_ENT_IT.CD_FILIAL
			 					   	 AND E.CD_NF     = EST_NF_ENT_IT.CD_NF
									 AND E.CD_PROD   = EST_NF_ENT_IT.CD_PROD 

		OPEN AplicarCompradorNotaFiscalEntradaCompras

		FETCH NEXT FROM AplicarCompradorNotaFiscalEntradaCompras INTO @CD_EMP, 
																	  @CD_FILIAL, 
																	  @CD_NF, 
																	  @CD_PROD, 
																	  @CD_COMPRADOR

		WHILE @@FETCH_STATUS = 0
			BEGIN
				INSERT INTO EST_NF_ENT_IT_COMPRADOR
				(CD_EMP,
				CD_FILIAL,
				CD_NF,
				CD_PROD,
				CD_COMPRADOR, 
				DT_CAD)
				SELECT       
					@CD_EMP,
					@CD_FILIAL, 
					@CD_NF,
					@CD_PROD,
					@CD_COMPRADOR,
					GETDATE()
		
				FETCH NEXT FROM AplicarCompradorNotaFiscalEntradaCompras INTO @CD_EMP, 
																			  @CD_FILIAL, 
																			  @CD_NF, 
																			  @CD_PROD, 
																			  @CD_COMPRADOR
			END
		PRINT 'Concluído.'

		CLOSE AplicarCompradorNotaFiscalEntradaCompras;
		DEALLOCATE AplicarCompradorNotaFiscalEntradaCompras;
END