PRINT '> PRODUCAO - SCRIPT #0005';

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_NF_SAI_NFE_PEND_DEL]'))
DROP TRIGGER [dbo].[TRG_EST_NF_SAI_NFE_PEND_DEL]
GO

CREATE TRIGGER [dbo].[TRG_EST_NF_SAI_NFE_PEND_DEL] ON [dbo].[EST_NFE_LOTE_SAI] 
FOR INSERT 
AS

	DECLARE @TP_LOTE INT;
	DECLARE @CD_NFE_LOTE INT;
	DECLARE @CD_NFE_LOTE_SAI INT;

	SET NOCOUNT ON
	DECLARE IDX_PEND CURSOR FAST_FORWARD FOR SELECT CD_NFE_LOTE, CD_NFE_LOTE_SAI FROM INSERTED
	OPEN IDX_PEND
	FETCH NEXT FROM IDX_PEND INTO @CD_NFE_LOTE, @CD_NFE_LOTE_SAI
	WHILE @@FETCH_STATUS = 0
	BEGIN

	 SET @TP_LOTE = ISNULL((SELECT TOP 1 TP_LOTE FROM EST_NFE_LOTE WHERE EST_NFE_LOTE.CD_NFE_LOTE = @CD_NFE_LOTE), -1);

	 IF @TP_LOTE = 0    
	 BEGIN
		--Apgando a pendência de saída de nota fiscal eletronica
		DELETE
			d
		FROM
			EST_NF_SAI_NFE_PEND d 
		INNER JOIN INSERTED t ON
				t.CD_EMP = d.CD_EMP 
			AND t.CD_FILIAL = d.CD_FILIAL
			AND t.CD_NF = d.CD_NF
			AND t.CD_NFE_LOTE = @CD_NFE_LOTE
			AND t.CD_NFE_LOTE_SAI = @CD_NFE_LOTE_SAI
	 END    
	    
	 IF @TP_LOTE = 1    
	 BEGIN    
		--Apgando a pendência cancelamSAIo de saída de nota fiscal eletronica
		DELETE
			d
		FROM
			EST_NF_SAI_NFE_CANCEL_PEND d 
		INNER JOIN INSERTED t ON
				t.CD_EMP = d.CD_EMP
			AND t.CD_FILIAL = d.CD_FILIAL
			AND t.CD_NF = d.CD_NF  
			AND t.CD_NFE_LOTE = @CD_NFE_LOTE
			AND t.CD_NFE_LOTE_SAI = @CD_NFE_LOTE_SAI
	 END

	 FETCH NEXT FROM IDX_PEND INTO @CD_NFE_LOTE, @CD_NFE_LOTE_SAI
	 END

	 --FECHANDO CURSOS
	 CLOSE IDX_PEND;
	 --DESALOCANDO CURSOS DA MEMORIA
	 DEALLOCATE IDX_PEND;
GO

PRINT '    < [OK]';
