IF EXISTS(SELECT NAME FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PED_CP_IT_DESC_FINAN')
BEGIN
	DROP TRIGGER TRG_EST_PED_CP_IT_DESC_FINAN;
END
GO
GO
CREATE TRIGGER [dbo].[TRG_EST_PED_CP_IT_DESC_FINAN] ON [dbo].[EST_PED_CP_IT] 
FOR INSERT
AS
DECLARE @RSFORN TABLE(CD_EMP INT, CD_PROD INT, CD_FORN INT)
DECLARE @PERC_DESC_FINAN AS MONEY
--Pegando os dados da nota fiscal para buscar o desconto financeiro
INSERT INTO @RSFORN
	SELECT 
		c.CD_EMP,
		i.CD_PROD,
		c.CD_FORN
	FROM 
		EST_PED_CP c INNER JOIN INSERTED i ON
		c.CD_EMP = i.CD_EMP AND
		c.CD_FILIAL = i.CD_FILIAL AND
		c.CD_PED = i.CD_PED

--Buscando o desconto financeiro do produto no fornecedor se houver
SET @PERC_DESC_FINAN=ISNULL((SELECT
						ISNULL(MAX(PERC_DESC_FINAN),0)
					  FROM
						@RSFORN f INNER JOIN EST_PROD_DESC_FINAN d ON
						f.CD_EMP = d.CD_EMP AND
						f.CD_PROD = d.CD_PROD AND
						f.CD_FORN = d.CD_FORN
					  WHERE
					     d.FLAG_SOMENTE_MELHOR_CONDICAO =0),0)

IF @PERC_DESC_FINAN > 0
begin
--Atualizando o item da entrada da nota fiscal
UPDATE
	i
SET
	i.PERC_DESC_FINAN =@PERC_DESC_FINAN
FROM
	EST_PED_CP_IT i INNER JOIN  INSERTED  ON
	i.CD_EMP = INSERTED.CD_EMP AND
	i.CD_FILIAL = INSERTED.CD_FILIAL AND
	i.CD_PED = INSERTED.CD_PED AND
	i.CD_PROD = INSERTED.CD_PROD
end