IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_PDV_VD_CANCEL_TEF_POSICAO_FINANCEIRA_PROC')
BEGIN
	DROP TRIGGER TRG_PDV_VD_CANCEL_TEF_POSICAO_FINANCEIRA_PROC
END
GO
CREATE TRIGGER [dbo].[TRG_PDV_VD_CANCEL_TEF_POSICAO_FINANCEIRA_PROC] ON [dbo].[PDV_VD_CANCEL_TEF] 
FOR INSERT, UPDATE
AS
--Controle de posicao financeira
DELETE 
	P
FROM
	RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_PDV_VD_CANCEL_TEF 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,i.DT_CAD);
	
--Caso nao tenha cadastre
INSERT INTO RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_PDV_VD_CANCEL_TEF
	(CD_EMP,
	CD_FILIAL,
	DT_PROC,
	DT_CAD)
SELECT DISTINCT 
	CD_EMP,
	CD_FILIAL,
	MIN(CONVERT(DATE,i.DT_CAD)),
	GETDATE()
FROM
	INSERTED I
GROUP BY
	CD_EMP,
	CD_FILIAL