GO

/****** Object:  StoredProcedure [dbo].[P_EST_NF_SAI_CPL_GERA]    Script Date: 10/10/2017 16:23:14 ******/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER PROCEDURE [dbo].[P_EST_NF_SAI_CPL_GERA]
AS
    BEGIN
	   DECLARE @CD_EMP INT;
	   DECLARE @CD_FILIAL INT;
	   DECLARE @CD_NF INT;
	   DECLARE @CONTADOR INT;
	   DECLARE @Emissao DATE;
	   DECLARE @CdSerie INT;


	   DECLARE CnotasCpl CURSOR FAST_FORWARD FOR
		  SELECT DISTINCT  
			 s.CD_EMP
			,s.CD_FILIAL
			,s.CD_NF
			,s.DT_EMISSAO_NOVA
			,s.CD_NF_SERIE
		  FROM
			 EST_NF_SAI_CPL_EMISSAO				   s
			 LEFT OUTER JOIN EST_NF_SAI_EST_NF_SAI_CPL cpl ON
			 s.CD_EMP = cpl.CD_EMP
			 AND s.CD_FILIAL = cpl.CD_FILIAL
			 AND s.CD_NF = cpl.CD_NF_REF
		  WHERE
			 cpl.CD_NF IS NULL ;


	   SET @CONTADOR = 1;
	   OPEN CnotasCpl ;
	   FETCH NEXT FROM CnotasCpl INTO @CD_EMP
							    ,@CD_FILIAL
							    ,@CD_NF
							    ,@Emissao
							    ,@CdSerie;

	   WHILE @@FETCH_STATUS = 0
		  BEGIN
			 PRINT 'Nota Fiscal ' + CONVERT(VARCHAR, @CD_NF) + ' ' + CONVERT(VARCHAR, @CONTADOR) + ' '
				  + CONVERT(VARCHAR, GETDATE(), 108);
			 -- WAITFOR DELAY '00:00:05'

			 EXEC P_EST_NF_SAI_CPL
				@CD_EMP
			    ,@CD_FILIAL
			    ,@CD_NF
			    ,@Emissao
			    ,@CdSerie
			 ;

			 SET @CONTADOR = @CONTADOR + 1;
			 FETCH NEXT FROM CnotasCpl INTO @CD_EMP
							    ,@CD_FILIAL
							    ,@CD_NF
							    ,@Emissao
							    ,@CdSerie;

		  END;
	   PRINT 'Concluido.';
	   CLOSE CnotasCpl;
	   DEALLOCATE CnotasCpl;
    END
    ;


GO


