IF EXISTS( SELECT * FROM SYS.OBJECTS 
			WHERE NAME ='TRG_EST_NF_ENT_IT_CUSTO_DELETE_PROCESSAMENTO_PENDENTE' AND TYPE = 'TR')
BEGIN
	DROP TRIGGER dbo.TRG_EST_NF_ENT_IT_CUSTO_DELETE_PROCESSAMENTO_PENDENTE
END
GO
GO 
CREATE TRIGGER [dbo].[TRG_EST_NF_ENT_IT_CUSTO_DELETE_PROCESSAMENTO_PENDENTE] ON [dbo].[EST_NF_ENT_IT] 
FOR DELETE
AS
UPDATE
	p
SET 
	p.DT_PROC=i.DT_ENT,
	p.DT_CAD=GETDATE()
FROM
	EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p 
	INNER JOIN DELETED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD = i.CD_PROD		
	INNER JOIN EST_NF_ENT e ON
	i.CD_EMP = e.CD_EMP AND 
	i.CD_FILIAL = e.CD_FILIAL AND
	i.CD_NF = e.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	e.CD_NT_MOV = m.CD_MOV_OP
WHERE
	m.ATU_EST=1
	and p.DT_PROC > i.DT_ENT;

INSERT INTO EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE
	(CD_EMP,
	CD_FILIAL,
	CD_PROD,
	DT_PROC,
	DT_CAD,
	DT_PROC_ATUAL)
SELECT DISTINCT 
	i.CD_EMP,
	i.CD_FILIAL,
	i.CD_PROD,
	MIN(i.DT_ENT),
	GETDATE(),
	NULL
FROM
	EST_NF_ENT e  INNER JOIN DELETED i ON
	e.CD_EMP = i.CD_EMP AND 
	e.CD_FILIAL = i.CD_FILIAL AND
	e.CD_NF = i.CD_NF 
	INNER JOIN GLB_MOV_OP m ON
	e.CD_NT_MOV = m.CD_MOV_OP
	LEFT OUTER JOIN EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD = i.CD_PROD
WHERE
	m.ATU_EST=1
	AND p.CD_PROD IS NULL
GROUP BY
	i.CD_EMP,
	i.CD_FILIAL,
	i.CD_PROD


--Deletando ultimo processamento de custo medio
DELETE
	p
FROM
	EST_PROD_CPL_CUSTO_MEDIO_DT_PROC_ULTIMO p INNER JOIN DELETED d ON
	p.CD_EMP = d.CD_EMP AND
	p.CD_FILIAL = d.CD_FILIAL AND
	p.CD_PROD = d.CD_PROD;