CREATE OR ALTER trigger ttbmodelo_cor_b02u for tbmodelo_cor
active before update position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

   HISTORICO = '';

   IF (OLD.STATUS IS DISTINCT FROM NEW.STATUS) THEN
       BEGIN
       HISTORICO = HISTORICO||'COR: '||OLD.COR_ID||' - '||COALESCE((SELECT FIRST 1 C.DESCRICAO FROM TBCOR C WHERE C.CODIGO = OLD.COR_ID),'')||' ALTERADA: STATUS:'||COALESCE(OLD.STATUS, '0')||'->'||COALESCE(NEW.STATUS, '0');
       END

   IF (OLD.PERCENTUAL_REPRESENTATIVIDADE IS DISTINCT FROM NEW.PERCENTUAL_REPRESENTATIVIDADE) THEN
       BEGIN
       HISTORICO = HISTORICO||'COR: '||OLD.COR_ID||' - '||COALESCE((SELECT FIRST 1 C.DESCRICAO FROM TBCOR C WHERE C.CODIGO = OLD.COR_ID),'')||' ALTERADA: PERCENTUAL:'||CAST(COALESCE(OLD.PERCENTUAL_REPRESENTATIVIDADE, '0') AS NUMERIC (15,2))||' % ' ||'->'|| CAST(COALESCE(NEW.PERCENTUAL_REPRESENTATIVIDADE, '0') AS NUMERIC (15,2))|| ' % ';
       END

   IF (HISTORICO <> '') THEN
       BEGIN
       INSERT INTO TBHISTORICO (
       TABELA, TABELA_ID, USUARIO, IP, HISTORICO) VALUES (
      'TBMODELO', OLD.MODELO_ID,
      (SELECT FIRST 1 MON$USER FROM MON$ATTACHMENTS WHERE MON$ATTACHMENT_ID = CURRENT_CONNECTION),
      (SELECT FIRST 1 MON$REMOTE_ADDRESS FROM MON$ATTACHMENTS WHERE MON$ATTACHMENT_ID = CURRENT_CONNECTION),
       :HISTORICO);
       END
END;

