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