IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_PROD_REQ_TRANSF_LIB_ITENS_PENDENTE]'))
	DROP TRIGGER [dbo].[TRG_EST_PROD_REQ_TRANSF_LIB_ITENS_PENDENTE]
GO
--Versao 2700
CREATE TRIGGER [dbo].[TRG_EST_PROD_REQ_TRANSF_LIB_ITENS_PENDENTE] ON [dbo].[EST_PROD_REQ_TRANSF_LIB_ITENS] 
FOR INSERT,UPDATE
AS
UPDATE
	p
SET 
	p.DT_PROC=l.DT_CAD,
	p.DT_CAD=GETDATE()
FROM
	EST_PROD_CPL_CUSTO_MEDIO_PROCESSAMENTO_PENDENTE p INNER JOIN  INSERTED 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_PROD_REQ_TRANSF_LIB  l ON   
	i.CD_EMP = l.CD_EMP AND   
	i.CD_FILIAL = l.CD_FILIAL AND   
	i.CD_REQ = l.CD_REQ 
WHERE
	p.DT_PROC > l.DT_CAD;

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(l.DT_CAD),
	GETDATE(),
	NULL
FROM
	EST_PROD_REQ_TRANSF_LIB l INNER JOIN INSERTED i ON   
	l.CD_EMP = i.CD_EMP AND   
	l.CD_FILIAL = i.CD_FILIAL AND   
	l.CD_REQ = i.CD_REQ 
	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
	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 INSERTED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL AND
	p.CD_PROD = i.CD_PROD;
