/****** Object:  Trigger [TRG_PG_CRED_POSICAO_FINANCEIRA_PROC]    Script Date: 20/07/2016 13:57:54 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_PG_CRED_POSICAO_FINANCEIRA_PROC]'))
 DROP TRIGGER [dbo].[TRG_PG_CRED_POSICAO_FINANCEIRA_PROC]
 go
CREATE TRIGGER [dbo].[TRG_PG_CRED_POSICAO_FINANCEIRA_PROC] ON [dbo].[PG_CRED] FOR INSERT,UPDATE AS
--Controle de posicao financeira
DELETE P
FROM
	RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_PG_CRED p 
	INNER JOIN INSERTED i ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL
--Caso nao tenha cadastre
INSERT INTO RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_PG_CRED
	(CD_EMP,
	CD_FILIAL,
	DT_PROC,
	DT_CAD)
SELECT DISTINCT 
	i.CD_EMP,
	i.CD_FILIAL,
	MIN(i.DT_EMIS),
	GETDATE()
FROM
	INSERTED i 
	LEFT OUTER JOIN RC_DEB_POSICAO_FINANCEIRA_PROCESSAR_PG_CRED p ON
	p.CD_EMP = i.CD_EMP AND
	p.CD_FILIAL = i.CD_FILIAL 
GROUP BY
	i.CD_EMP,
	i.CD_FILIAL


