IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_RC_PGTO_PDV_RC_CREDIARIO_PARC_CRED_PENDENTE_SALDO]'))
DROP TRIGGER [dbo].[TRG_RC_PGTO_PDV_RC_CREDIARIO_PARC_CRED_PENDENTE_SALDO]
GO

/****** Object:  Trigger [dbo].[TRG_RC_PGTO_PDV_RC_CREDIARIO_PARC_CRED_PENDENTE_SALDO]    Script Date: 16/02/2018 17:17:26 ******/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

CREATE TRIGGER [dbo].[TRG_RC_PGTO_PDV_RC_CREDIARIO_PARC_CRED_PENDENTE_SALDO] ON 
	[dbo].[RC_PGTO_PDV_RC_CREDIARIO_PARC_CRED]
FOR INSERT, UPDATE, DELETE
AS

------------------------------------------------------------------------------------------------------
-- Tabela auxiliar

	 CREATE TABLE #TmpCli (CdEmp Tinyint, CdCli INT);

------------------------------------------------------------------------------------------------------
--Insere vinculos removidos para recalculo de saldo

	 INSERT INTO #TmpCli
	 SELECT
			P.CD_EMP
		  , P.CD_CLI
	 FROM
		 DELETED d
		 INNER JOIN RC_CREDIARIO_PARC p ON d.CD_CTR = p.CD_CTR;

------------------------------------------------------------------------------------------------------
--Insere novos clientes

	 INSERT INTO #TmpCli
	 SELECT
			p.CD_EMP
		  , p.CD_CLI
	 FROM
		 INSERTED i
		 INNER JOIN RC_CREDIARIO_PARC p ON i.CD_CTR = p.CD_CTR;

------------------------------------------------------------------------------------------------------
--Remove registros que ja estao pendentes
	 DELETE FROM t
	 FROM #TmpCli t
		  JOIN RC_CLI_CREDIARIO_PENDENTE_SALDO pend ON t.CDEMP = pend.CD_EMP
													   AND t.CDCLI = pend.CD_CLI;

------------------------------------------------------------------------------------------------------		 
--Inserindo pendencia

	 INSERT INTO RC_CLI_CREDIARIO_PENDENTE_SALDO( CD_EMP, CD_CLI , DT_CAD)
	 SELECT DISTINCT
			CdEmp
		  , CdCli
		  , CONVERT(DATE, GETDATE())
	 FROM
		 #TmpCli;

------------------------------------------------------------------------------------------------------		 

GO


