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

/****** Object:  Trigger [dbo].[TRG_EST_NF_SAI_NF_ENT_EXCLUI_PENDENCIA]    Script Date: 13/08/2015 19:10:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[TRG_EST_NF_SAI_NF_ENT_EXCLUI_PENDENCIA] ON [dbo].[EST_NF_SAI_NF_ENT] 
FOR INSERT AS

	--Proibe alterao na nota fiscal de sada quando j existe registro da transferncia
	IF EXISTS (SELECT top 1
					t.CD_FIL_ORIG
					FROM 
						EST_NF_ENT_EST_NF_SAI_TRANSF t 
						INNER JOIN INSERTED s  ON 
						t.CD_FIL_ORIG	=s.CD_FILIAL AND 
						t.CD_EMP		=s.CD_EMP AND 
						t.CD_NF_SAI		=s.CD_NF_SAI
						
						--Validar apenas notas que sejam emissao propria
						INNER JOIN (select  
										c.CD_EMP,
										c.CD_FILIAL,
										c.CD_NF_ENT
									From 
										EST_NF_ENT_EF_NF_CTR_NF c 
										INNER JOIN EST_NF_ENT e on 
										c.CD_EMP	=	e.CD_EMP AND
										c.CD_FILIAL	=	e.CD_FILIAL AND
										c.CD_NF_ENT =	e.CD_NF) p ON 
						s.CD_EMP	= p.CD_EMP and
						s.CD_FILIAL = p.CD_FILIAL and
						s.CD_NF_ENT = p.CD_NF_ENT )
	begin
		RAISERROR ('Nota fiscal com confirmacao de entrada no destino, operacao cancelada.',16, 1); 
		RETURN;
	end  

	--Exclui pendncia de entrada de nota fiscal 
	DELETE p  
	FROM 
		EST_NF_SAI_PENDENCIA p 
		INNER JOIN INSERTED i ON
		i.CD_EMP	=p.CD_EMP AND 
		i.CD_FILIAL	=p.CD_FILIAL AND 
		i.CD_NF_SAI	=p.CD_NF; 
	
GO
