IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_EST_NF_ENT_GERA_PRE_FATURA_ALL]') AND type in (N'P', N'PC'))
begin
	DROP PROCEDURE P_EST_NF_ENT_GERA_PRE_FATURA_ALL
end
GO
GO
--P_EST_NF_ENT_GERA_PRE_FATURA_ALL 
CREATE PROCEDURE [dbo].[P_EST_NF_ENT_GERA_PRE_FATURA_ALL] 
AS
begin
DECLARE @CD_NF INT
DECLARE @CONTADOR INT
DECLARE @CD_EMP INT
DECLARE @CD_FILIAL INT
DECLARE @CD_DEST INT
DECLARE @CD_NT_MOV INT
DECLARE @NR_NF INT

DECLARE CnotasPreFatura CURSOR FAST_FORWARD FOR 
SELECT
	  e.CD_EMP,
	 e.CD_FILIAL,
	 e.CD_NF,
	 F.CD_FILIAL_DEST,
	 366,
	 E.NR_NF
FROM
	[dbo].[0Folha2] f inner join est_nf_ent e on
	1 = e.cd_emp and
	f.CD_FILIAL=e.cd_forn and
	f.NR_NF = e.nr_nf
	LEFT OUTER join EST_NF_ENT_CROSS_DOCKING d on
	e.cd_emp = d.cd_emp and
	e.cd_filial = d.cd_filial and
	e.cd_nf = d.cd_nf 
where
	e.cd_emp =1
	and e.cd_filial = 900
	AND d.cd_nf  IS NULL
SET @CONTADOR=1
OPEN CnotasPreFatura
FETCH NEXT FROM CnotasPreFatura INTO @CD_EMP,@CD_FILIAL,@CD_NF,@CD_DEST, @CD_NT_MOV,@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_GERA_PRE_FATURA @CD_EMP,@CD_FILIAL,@CD_DEST,@CD_NT_MOV,@CD_NF
		SET @CONTADOR=@CONTADOR+1
		FETCH NEXT FROM CnotasPreFatura INTO @CD_EMP,@CD_FILIAL,@CD_NF,@CD_DEST, @CD_NT_MOV,@NR_NF
	end
PRINT 'Concluido.'
CLOSE CnotasPreFatura;
DEALLOCATE CnotasPreFatura;
end

GO


