CREATE OR ALTER trigger ttbremessa_item_processado_b99u for tbremessa_item_processado
active before update position 99
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( NEW.UP_ID <> OLD.UP_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' TALAO ' || LPAD(NEW.CONTROLE,4,'0') || ' REPROGRAMADO UP:'||OLD.UP_ID||'->'||NEW.UP_ID;
    END

    IF ( NEW.programacao_esteira <> OLD.programacao_esteira) THEN
    BEGIN
      update tbprogramacao p
        set p.gp_id = new.programacao_esteira,
        p.up_id = coalesce((select first 1 g.up_id from tbgp_up g where g.gp_id = new.programacao_esteira),0)
        where true
        and p.gp_id = old.programacao_esteira
        and p.tabela_id = new.id
        and p.tipo = 'A';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBREMESSA',NEW.REMESSA,HISTORICO);
    END
END;