IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_CHQ_REPA_CPL_POSICAO_FINANCEIRA_PROC')
BEGIN
	DROP TRIGGER TRG_CHQ_REPA_CPL_POSICAO_FINANCEIRA_PROC
END
GO

CREATE TRIGGER [dbo].[TRG_CHQ_REPA_CPL_POSICAO_FINANCEIRA_PROC] ON [dbo].[CHQ_REPA_CPL] FOR INSERT,UPDATE AS
--Controle de posicao financeira
delete from p
FROM
	RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_CHQ_REPA_CPL p 
	INNER JOIN INSERTED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = 0
	INNER JOIN CHQ_REPA ON
	I.CD_EMP = CHQ_REPA.CD_EMP AND
	I.CD_REPA = CHQ_REPA.CD_REPA
WHERE
	p.DT_PROC > CHQ_REPA.DT_REPA;
--Caso nao tenha cadastre
INSERT INTO RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_CHQ_REPA_CPL
	(CD_EMP,
	CD_FILIAL,
	DT_PROC,
	DT_CAD)
SELECT DISTINCT 
	i.CD_EMP,
	0,
	MIN(CHQ_REPA.DT_REPA),
	getdate()
FROM
	INSERTED i 
	LEFT OUTER JOIN RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_CHQ_REPA_CPL p ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = 0 
	INNER JOIN CHQ_REPA ON
	I.CD_EMP = CHQ_REPA.CD_EMP AND
	I.CD_REPA = CHQ_REPA.CD_REPA
WHERE
	 p.CD_FILIAL IS NULL
GROUP BY
	i.CD_EMP