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

CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_IT_SNGPC_PENDENTE] ON [dbo].[EST_NF_ENT_IT] FOR  INSERT AS
Begin
	--Testando se a nota fiscal já esta em pendencia de
	--lancamento do SNGPC
	IF NOT EXISTS (SELECT 
						* 
				    FROM 
						EST_NF_ENT_IT_EST_SNGPC_PENDENTE e INNER JOIN INSERTED i ON
						e.CD_EMP    = i.CD_EMP AND
						e.CD_FILIAL = i.CD_FILIAL AND
						e.CD_NF     = i.CD_NF AND
						e.CD_PROD   = i.CD_PROD)	
	Begin
		--Pedencia de lancamento SNGPC
		INSERT INTO EST_NF_ENT_IT_EST_SNGPC_PENDENTE
			SELECT 
				i.CD_EMP, 
				i.CD_FILIAL,
				i.CD_NF,
				i.CD_PROD,
				GETDATE()
			FROM 
				INSERTED i INNER JOIN EST_PROD p ON
				i.CD_PROD = p.CD_PROD AND
				i.CD_EMP = p.CD_EMP
				
			WHERE
				p.CONTROLE_SNGPC = 1 OR
				p.FLAG_PRODUTO_CONTROLADO = 1 OR
				P.ANTIBIOTICO=1
	End
End

GO
