
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_RC_CRED_POSICAO_FINANCEIRA_PROC]'))
DROP TRIGGER [dbo].[TRG_RC_CRED_POSICAO_FINANCEIRA_PROC]
GO
/****** Object:  Trigger [dbo].[TRG_RC_CRED_POSICAO_FINANCEIRA_PROC]    Script Date: 02/03/2017 11:39:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
				 
CREATE TRIGGER [dbo].[TRG_RC_CRED_POSICAO_FINANCEIRA_PROC] ON 
    [dbo].[RC_CRED] FOR INSERT,
    UPDATE AS


/*****************************************************************************************/

CREATE TABLE #INSERT (CD_EMP TINYINT,
				    CD_FILIAL INT,
				    DATA_PGTO	 DATE);
INSERT INTO #INSERT
SELECT
     I.CD_EMP,
	I.CD_FILIAL,
	MIN(I.DT_PAG)
FROM
	INSERTED I 
GROUP BY 	
     I.CD_EMP,
	I.CD_FILIAL

/*****************************************************************************************/ 

--Controle de posicao financeira
DELETE FROM P
FROM
	RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_RC_CRED P 
	INNER JOIN #INSERT I ON
	P.CD_EMP    = I.CD_EMP AND
	P.CD_FILIAL = I.CD_FILIAL
WHERE
	P.DT_PROC > I.DATA_PGTO;

/*****************************************************************************************/

--Caso nao tenha cadastre
INSERT INTO RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_RC_CRED (CD_EMP, CD_FILIAL, DT_PROC, DT_CAD)
SELECT DISTINCT 
	i.CD_EMP,
	i.CD_FILIAL,
	i.DATA_PGTO,
	GETDATE()
FROM
	#Insert i 
	LEFT OUTER JOIN RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_RC_CRED p ON
	p.CD_EMP		= i.CD_EMP AND
	p.CD_FILIAL	= i.CD_FILIAL AND 
	p.DT_PROC		= i.DATA_PGTO	
WHERE
	p.CD_FILIAL IS NULL

drop table #Insert;
GO
ALTER TABLE [dbo].[RC_CRED] ENABLE TRIGGER [TRG_RC_CRED_POSICAO_FINANCEIRA_PROC]
GO

