/****** Object:  StoredProcedure [dbo].[P_EST_NF_ENT_EFETUA_ENTRADA_NF_CPL_ALL]    Script Date: 02/11/2014 18:34:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_NF_ENT_EFETUA_ENTRADA_NF_CPL_ALL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_NF_ENT_EFETUA_ENTRADA_NF_CPL_ALL]
GO
GO 
GO
--P_EST_NF_ENT_EFETUA_ENTRADA_NF_CPL_ALL 1,999,355,'2015-11-30','2015-11-30',0
CREATE PROCEDURE P_EST_NF_ENT_EFETUA_ENTRADA_NF_CPL_ALL (@CD_EMP INT, 
															 @CD_FILIAL_ORIG INT, 
															 @CD_NT_MOV INT,
															 @DT_ENT DATETIME,
															 @DT_PROC DATETIME,
															 @CD_NF_SAI_PROC INT=0)
AS
begin
DECLARE @CD_NF INT
DECLARE @NR_NF INT
DECLARE @CONTADOR INT

DECLARE CnotasCplEntrada CURSOR FAST_FORWARD FOR 
	SELECT  DISTINCT TOP 5000
			NF.CD_NF,
			NF.NF_NF
    FROM EST_NF_SAI NF INNER JOIN EST_NF_SAI_EST_NF_SAI_CPL C ON
			NF.CD_EMP			= C.CD_EMP AND
			NF.CD_FILIAL	= C.CD_FILIAL AND
			NF.CD_NF		= C.CD_NF	
			INNER JOIN EST_NF_SAI_NFE nfe ON
			NF.CD_EMP = nfe.CD_EMP AND
			NF.CD_FILIAL = nfe.CD_FILIAL AND
			NF.CD_NF = nfe.CD_NF 
	WHERE NF.CD_EMP = @CD_EMP
			AND NF.CD_FILIAL = @CD_FILIAL_ORIG	
			AND NF.CD_NF = CASE WHEN @CD_NF_SAI_PROC= 0 THEN NF.CD_NF ELSE @CD_NF_SAI_PROC END
			AND NF.STS_NF=0	
			AND NF.DT_EMI_NF=@DT_PROC	
			AND NOT EXISTS (SELECT T.CD_EMP
							FROM EST_NF_ENT_EST_NF_SAI_TRANSF T 
							WHERE   T.CD_EMP			 = NF.CD_EMP
									AND T.CD_FIL_ORIG	 = NF.CD_FILIAL
									AND T.CD_NF_SAI		 = NF.CD_NF)
			AND NOT EXISTS (SELECT I.CD_EMP
							FROM EST_NF_SAI_EST_NF_NFE_INU I 
							WHERE   I.CD_EMP			 = NF.CD_EMP
									AND I.CD_FILIAL	 = NF.CD_FILIAL
									AND I.CD_NF		 = NF.CD_NF)

			AND NOT EXISTS (SELECT d.CD_EMP
							FROM EST_NF_SAI_NF_ENT d 
							WHERE   d.CD_EMP			 = NF.CD_EMP
									AND d.CD_FILIAL	 = NF.CD_FILIAL
									AND d.CD_NF_SAI		 = NF.CD_NF)

		ORDER BY
			NF_NF
SET @CONTADOR=1
OPEN CnotasCplEntrada
FETCH NEXT FROM CnotasCplEntrada INTO @CD_NF,@NR_NF
	WHILE @@FETCH_STATUS=0
	  begin
	  PRINT 'Nota Fiscal ' + CONVERT(VARCHAR, @NR_NF) + ' ' + CONVERT(VARCHAR, @CONTADOR) + ' ' + CONVERT(VARCHAR, GETDATE (),108)
	    
		EXEC P_EST_NF_ENT_EFETUA_ENTRADA_NF_CPL @CD_EMP,@CD_FILIAL_ORIG,@CD_NT_MOV,@DT_ENT,@CD_NF

		SET @CONTADOR=@CONTADOR+1
	  FETCH NEXT FROM CnotasCplEntrada INTO @CD_NF,@NR_NF
	end
PRINT 'Concluido.'
CLOSE CnotasCplEntrada;
DEALLOCATE CnotasCplEntrada;
end