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


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[TRG_EST_NF_SAI_IT_SNGPC_PENDENTE] ON [dbo].[EST_NF_SAI_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_SAI_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 AND
						E.CD_IT     = I.CD_IT)	
	BEGIN
		--PEDENCIA DE LANCAMENTO SNGPC
		INSERT INTO EST_NF_SAI_IT_EST_SNGPC_PENDENTE
			SELECT 
				I.CD_EMP, 
				I.CD_FILIAL,
				I.CD_NF,
				I.CD_PROD,
				I.CD_IT,
				GETDATE()
			FROM 
				INSERTED I INNER JOIN EST_PROD P ON
				I.CD_EMP = P.CD_EMP AND
				I.CD_PROD = P.CD_PROD
			WHERE
				p.CONTROLE_SNGPC = 1 OR
				p.FLAG_PRODUTO_CONTROLADO = 1 OR
				P.ANTIBIOTICO=1
	END
END

GO