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

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