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

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