IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_RC_VD_CONV_RC_DEB_POSICAO_FINANCEIRA_PROC')
BEGIN
	DROP TRIGGER TRG_RC_VD_CONV_RC_DEB_POSICAO_FINANCEIRA_PROC
END
GO
CREATE TRIGGER [dbo].[TRG_RC_VD_CONV_RC_DEB_POSICAO_FINANCEIRA_PROC] ON [dbo].[RC_VD_CONV_RC_DEB] 
FOR INSERT, UPDATE
AS
--Controle de posicao financeira
DELETE 
	P
FROM
	RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_RC_VD_CONV p 
	INNER JOIN INSERTED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL
WHERE
	p.DT_PROC >= CONVERT(DATE,GETDATE());
	
--Caso nao tenha cadastre
INSERT INTO RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_RC_VD_CONV
	(CD_EMP,
	CD_FILIAL,
	DT_PROC,
	DT_CAD)
SELECT DISTINCT 
	CD_EMP,
	CD_FILIAL,
	CONVERT(DATE,GETDATE()),
	GETDATE()
FROM
	INSERTED I
GROUP BY
	CD_EMP,
	CD_FILIAL