ALTER TABLE TBMOTIVO
    ADD APP CHAR(1);

SET TERM ^ ;

CREATE OR ALTER trigger ttbmotivo_b01u for tbmotivo
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.TIPO <> NEW.TIPO) THEN
    BEGIN
        HISTORICO = HISTORICO||' TIPO: '|| OLD.TIPO||'->'||NEW.TIPO;
    END
    
    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.APP IS DISTINCT FROM NEW.APP) THEN
    BEGIN
        HISTORICO = HISTORICO||' INC.APP: '|| COALESCE(OLD.APP, '0')||'->'||COALESCE(NEW.APP, '0');
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBMOTIVO',NEW.ID, HISTORICO);
    END
END
^

SET TERM ; ^


SET TERM ^ ;

create trigger tbmotivo_bi for tbmotivo
active before insert position 0
as
begin
  if (new.id is null) then
    new.id = gen_id(gtbmotivo,1);
end
^

SET TERM ; ^

INSERT INTO TBMOTIVO (TIPO, DESCRICAO, STATUS, APP)
              VALUES ('I', 'INCLUÍDO VIA APP', 1, '1');

COMMIT WORK;


