IF EXISTS( SELECT * FROM SYS.OBJECTS 
			WHERE NAME ='TRG_EST_NF_SAI_NFE_PEND_ERR'AND TYPE = 'TR')
BEGIN
	DROP TRIGGER [dbo].[TRG_EST_NF_SAI_NFE_PEND_ERR]
END
GO
GO
GO
------------------------------------INSERÇÃO EM EST_NF_ENT_NFE_PEND------------------------------------
CREATE TRIGGER [dbo].[TRG_EST_NF_SAI_NFE_PEND_ERR] ON [dbo].[EST_NFE_LOTE_SAI_ERR] FOR INSERT AS

	DECLARE @TP_LOTE INT

	SET @TP_LOTE =  ISNULL((SELECT TP_LOTE 
							FROM EST_NFE_LOTE INNER JOIN INSERTED i ON
								EST_NFE_LOTE.CD_NFE_LOTE = i.CD_NFE_LOTE),0)
	
	IF @TP_LOTE = 0
		BEGIN
			--Pendência de saída de nota fiscal eletronica 
			INSERT INTO EST_NF_SAI_NFE_PEND (CD_EMP, CD_FILIAL, CD_NF,PEND_SOLUC)
				SELECT 
					lote_it.CD_EMP, 
					lote_it.CD_FILIAL, 
					lote_it.CD_NF,
					1
			    FROM 
			    	INSERTED i INNER JOIN EST_NFE_LOTE_SAI lote_it ON
						i.CD_NFE_LOTE         = lote_it.CD_NFE_LOTE  
						AND i.CD_NFE_LOTE_SAI = lote_it.CD_NFE_LOTE_SAI 
				WHERE 				
					NOT EXISTS (SELECT 
									CD_EMP 
								FROM 
									EST_NF_SAI_NFE_PEND pend
								WHERE 
									lote_it.CD_EMP      = pend.CD_EMP AND 
									lote_it.CD_FILIAL   = pend.CD_FILIAL AND 
									lote_it.CD_NF       = pend.CD_NF);
		END
	ELSE
		BEGIN
			--Pendência de cancelamento de saida de nota fiscal eletronica 
			INSERT INTO EST_NF_SAI_NFE_CANCEL_PEND (CD_EMP, CD_FILIAL, CD_NF,PEND_SOLUC)
				SELECT 
					lote_it.CD_EMP, 
					lote_it.CD_FILIAL, 
					lote_it.CD_NF,
					1
			    FROM 
			    	INSERTED i INNER JOIN EST_NFE_LOTE_SAI lote_it ON
						i.CD_NFE_LOTE         = lote_it.CD_NFE_LOTE  
						AND i.CD_NFE_LOTE_SAI = lote_it.CD_NFE_LOTE_SAI 
				WHERE 				
					NOT EXISTS (SELECT 
									CD_EMP 
								FROM 
									EST_NF_SAI_NFE_CANCEL_PEND pend
								WHERE 
									lote_it.CD_EMP      = pend.CD_EMP AND 
									lote_it.CD_FILIAL   = pend.CD_FILIAL AND 
									lote_it.CD_NF       = pend.CD_NF);					
		END