CREATE OR ALTER TRIGGER TTBCLIENTE_SUBTIPO_B01U FOR TBCLIENTE_SUBTIPO
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
--DECLARE VARIABLE HISTORICO2 VARCHAR(500);
BEGIN

   HISTORICO = '';

   IF (OLD.descricao <> NEW.descricao) THEN
       BEGIN
       HISTORICO = HISTORICO||' DESC: '||OLD.descricao||'->'||NEW.descricao;
       END
   IF (OLD.status <> NEW.status) THEN
       BEGIN
       HISTORICO = HISTORICO||' STATUS: '||OLD.status||'->'||NEW.status;
       END

   IF (OLD.qtd_min <> NEW.qtd_min) THEN
       BEGIN
       HISTORICO = HISTORICO||' QTD.MIN: '||OLD.qtd_min||'->'||NEW.qtd_min;
       END
   
   IF (OLD.qtd_max <> NEW.qtd_max) THEN
       BEGIN
       HISTORICO = HISTORICO||' QTD.MAX: '||OLD.qtd_max||'->'||NEW.qtd_max;
       END

   IF (OLD.qtd_mul <> NEW.qtd_mul) THEN
       BEGIN
       HISTORICO = HISTORICO||' QTD.MUL:'||old.qtd_mul||'->'||new.qtd_mul;
       END

   IF (OLD.grade_id <> NEW.grade_id) THEN
       BEGIN
       HISTORICO = HISTORICO||' GRADE:'||old.grade_id||'->'||new.grade_id;
       END

   IF (OLD.comissao <> NEW.comissao) THEN
       BEGIN
       HISTORICO = HISTORICO||' COMISSAO:'||old.comissao||'%'||'->'||new.comissao||'%';
       END

   IF (OLD.PRECO_NF_CF_ID <> NEW.PRECO_NF_CF_ID) THEN
       BEGIN
       HISTORICO = HISTORICO||' TAB.PRECO:'||old.PRECO_NF_CF_ID||'->'||new.PRECO_NF_CF_ID;
       END

   IF (OLD.TABELA_PRECO <> NEW.TABELA_PRECO) THEN
       BEGIN
       HISTORICO = HISTORICO||' ORIGEM PRECO:'||old.TABELA_PRECO||'->'||new.TABELA_PRECO;
       END 

   IF (OLD.PERFIL_PEDIDO <> NEW.PERFIL_PEDIDO) THEN
       BEGIN
       HISTORICO = HISTORICO||' PERFIL PEDIDO:'||old.PERFIL_PEDIDO||'->'||new.PERFIL_PEDIDO;
       END

   IF (HISTORICO <> '') THEN
       BEGIN
       HISTORICO = 'SUBTIPO ALTERADO: '||HISTORICO;

       INSERT INTO TBHISTORICO (
           TABELA, TABELA_ID, USUARIO, IP, HISTORICO) VALUES (
          'TBCLIENTE_TIPO', new.cliente_tipo_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;