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

GO

CREATE TRIGGER [dbo].[TRG_RC_CLI_CRED_RC_CLI_ALT_STS_CRED] ON [dbo].[RC_CLI_CREDIARIO] AFTER  UPDATE
AS

BEGIN TRY
	IF UPDATE(STS_CRED) OR UPDATE(CD_MOT_BLOQ_CLI) OR UPDATE(CD_MDL_VD) OR UPDATE(FLAG_N_GERA_FAT) OR UPDATE(FLAG_N_CARTA_COB) OR UPDATE(FLAG_N_TEL_COB) OR UPDATE(DIAS_CAREN_ATRASO) OR UPDATE(DIAS_CAREN_BLOQ) 
		BEGIN
			INSERT INTO RC_CLI_CRED_RC_CLI_AUDITORIA (CD_EMP,CD_CLI,CD_USU_ALT,STS_CRED,DT_ALT,CD_MOT_BLOQ_CLI,CD_MDL_VD,FLAG_N_GERA_FAT,FLAG_N_CARTA_COB,FLAG_N_TEL_COB,DIAS_CAREN_ATRASO,DIAS_CAREN_BLOQ) 
			SELECT       
				A.CD_EMP,
				A.CD_CLI,
				ISNULL(A.CD_USU_ALT,C.CD_USU_ALT) AS CD_USU_ALT,
				A.STS_CRED,
				GETDATE() AS DT_ALT
				,CD_MOT_BLOQ_CLI,
				CD_MDL_VD,
				FLAG_N_GERA_FAT,
				FLAG_N_CARTA_COB,
				FLAG_N_TEL_COB,
				DIAS_CAREN_ATRASO,
				DIAS_CAREN_BLOQ
			FROM       
			INSERTED A INNER JOIN RC_CLI C ON
			A.CD_EMP=C.CD_EMP AND
			A.CD_CLI=C.CD_CLI 
		END

END TRY
BEGIN CATCH
	ROLLBACK TRAN
	INSERT INTO ADM_ERRO (numero, severidade, estado, rotina, linha, mensagem, dtErro)
		SELECT
			ERROR_NUMBER() AS numero,
			ERROR_SEVERITY() AS severidade,
			ERROR_STATE() AS estado,
			ERROR_PROCEDURE() AS rotina,
			ERROR_LINE() AS linha,
			ERROR_MESSAGE() AS mensagem,
			GETDATE() AS dtErro;	
END CATCH


GO




