CREATE TABLE TBEPI (
    ID INTEGER NOT NULL,
    DATA DATE,
    DESCRICAO VARCHAR(100),
    PRODUTO_ID INTEGER,
    CA INTEGER,
    ASSINATURA VARCHAR(50),
    COLABORADOR_ID INTEGER,
    CARGO_ID INTEGER,
    DATA_TROCA DATE);

ALTER TABLE TBEPI
ADD CONSTRAINT PK_TBEPI
PRIMARY KEY (ID);

CREATE SEQUENCE GTBEPI;


CREATE trigger ttbepi_b01i for tbepi
active before insert position 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBEPI,1);
END;


CREATE trigger ttbepi_b02i for tbepi
active before insert position 1
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('TBEPI',NEW.ID, HISTORICO);
    END
END;


CREATE trigger ttbepi_b01u for tbepi
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

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

    IF ( NEW.PRODUTO_ID <> OLD.PRODUTO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' PROD:'||OLD.PRODUTO_ID||'->'||NEW.PRODUTO_ID;
    END

    IF ( NEW.CA <> OLD.CA) THEN
    BEGIN
        HISTORICO = HISTORICO||' CA:'||OLD.CA||'->'||NEW.CA;
    END

    IF ( NEW.COLABORADOR_ID <> OLD.COLABORADOR_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' COLAB:'||OLD.COLABORADOR_ID||'->'||NEW.COLABORADOR_ID;
    END

    IF ( NEW.CARGO_ID <> OLD.CARGO_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' CARGO:'||OLD.CARGO_ID||'->'||NEW.CARGO_ID;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = ' REGISTRO ALTERADO: '||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBEPI',NEW.ID, HISTORICO);
    END
END;

CREATE trigger tbepi_b01d for tbepi
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF (OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'REGISTRO EXCLUIDO';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBEPI',OLD.ID, HISTORICO);
    END
END;






