IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_RC_DEB_POSICAO_FINANCEIRA_PROC')
BEGIN
	DROP TRIGGER TRG_RC_DEB_POSICAO_FINANCEIRA_PROC
END
GO
				 
CREATE TRIGGER [dbo].[TRG_RC_DEB_POSICAO_FINANCEIRA_PROC] ON [dbo].[RC_DEB] FOR INSERT,UPDATE AS
--Controle de posicao financeira
delete from p
FROM
	RC_DEB_POSICAO_FINANCEIRA_PROCESSAR p 
	INNER JOIN INSERTED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL
WHERE
	p.DT_PROC > i.DT_DP;

--Caso nao tenha cadastro
INSERT INTO RC_DEB_POSICAO_FINANCEIRA_PROCESSAR
	(CD_EMP,
	CD_FILIAL,
	DT_PROC,
	DT_CAD,
	ORIGEM)
SELECT DISTINCT 
	i.CD_EMP,
	i.CD_FILIAL,
	MIN(i.DT_DP),
	GETDATE(),
	'LANCAMENTO'
FROM
	INSERTED i 
	LEFT OUTER JOIN RC_DEB_POSICAO_FINANCEIRA_PROCESSAR p ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL 
WHERE
	 p.CD_FILIAL IS NULL
GROUP BY
	i.CD_EMP,
	i.CD_FILIAL

