IF EXISTS(SELECT NAME FROM SYS.TRIGGERS WHERE NAME = 'TRG_RC_CLI_CONV_RC_CLI_AUDIT_ALTERACAO')
BEGIN
	DROP TRIGGER TRG_RC_CLI_CONV_RC_CLI_AUDIT_ALTERACAO;
END
GO
GO
CREATE TRIGGER [dbo].[TRG_RC_CLI_CONV_RC_CLI_AUDIT_ALTERACAO] ON [dbo].[RC_CLI_CONV_RC_CLI] FOR DELETE AS
BEGIN
	--Tabela de controle de alteracao de conveniados
	INSERT INTO RC_CLI_CONV_RC_CLI_AUDIT (CD_EMP,
										CD_CONV,	
										CD_CLI,	
										VLR_DEB,	
										VLR_CRED,	
										MATRICULA,	
										FLAG_N_EXP_VD_LAY,
										PERC_REC_MIN_CONV,
										PERC_REC_MAX_CONV,
										DT_CAD,
										CD_USU,
										TRANSACAO,
										NM_PROGRAMA,
										IP,
										HOST,
										STS_CRED,
										STS_ATIVO,
										FLAG_CONVENIADO_DEMISSAO,
										ID_CLI_CONV)
		SELECT 
			DELETED.CD_EMP,
			DELETED.CD_CONV,	
			DELETED.CD_CLI,	
			DELETED.VLR_DEB,	
			DELETED.VLR_CRED,	
			DELETED.MATRICULA,	
			DELETED.FLAG_N_EXP_VD_LAY,
			DELETED.PERC_REC_MIN_CONV,
			DELETED.PERC_REC_MAX_CONV,
			GETDATE(),
			DELETED.CD_USU_ALT,
			'D',
			PROGRAM_NAME(),
			'',
			HOST_NAME(),
			DELETED.STS_CRED,
			DELETED.STS_ATIVO,
			DELETED.FLAG_CONVENIADO_DEMISSAO,
			DELETED.ID_CLI_CONV
		FROM 
			DELETED INNER JOIN RC_CLI_CONV_RC_CLI ON
			DELETED.CD_EMP = RC_CLI_CONV_RC_CLI.CD_EMP AND
			DELETED.CD_CLI = RC_CLI_CONV_RC_CLI.CD_CLI AND
			((DELETED.VLR_DEB  + DELETED.VLR_CRED) <> (RC_CLI_CONV_RC_CLI.VLR_DEB  + RC_CLI_CONV_RC_CLI.VLR_CRED) 
			OR DELETED.MATRICULA <> RC_CLI_CONV_RC_CLI.MATRICULA)
END