CREATE TRIGGER TTBECD_B01I FOR TBECD
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if (new.id is null) then
    new.id = gen_id(GTBECD,1);
end;

CREATE TRIGGER TTBECD_B02I FOR TBECD
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro incluido';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBECD',NEW.ID, HISTORICO);
    END
end;

CREATE OR ALTER TRIGGER TTBECD_B01U FOR TBECD
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro ID: '||OLD.ID||', Descricao: '|| OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END

    IF ( OLD.CONTA <> NEW.CONTA) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro ID: '||OLD.ID||', Conta: '|| OLD.CONTA||'->'||NEW.CONTA;
    END

    IF ( OLD.DATINIVAL <> NEW.DATINIVAL) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro ID: '||OLD.ID||', Data inicial: '|| OLD.DATINIVAL||'->'||NEW.DATINIVAL;
    END

    IF ( OLD.DATFINVAL <> NEW.DATFINVAL) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro ID: '||OLD.ID||', Data final: '|| OLD.DATFINVAL||'->'||NEW.DATFINVAL;
    END

    IF ( OLD.TIPO <> NEW.TIPO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro ID: '||OLD.ID||', Tipo: '|| OLD.TIPO||'->'||NEW.TIPO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBECD',NEW.ID, HISTORICO);
    END
end;

CREATE TRIGGER TTBECD_B01D FOR TBECD
ACTIVE BEFORE DELETE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro Excluido: '||old.ID;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBECD',old.ID, HISTORICO);
    END
end;

ALTER SEQUENCE GTBECD RESTART WITH 1031 INCREMENT BY 1;

