ALTER TABLE TBTRIBUTACAO_IPI
    ADD ID INTEGER;

CREATE SEQUENCE GTBTRIBUTACAO_IPI;

ALTER SEQUENCE GTBTRIBUTACAO_IPI RESTART WITH 15 INCREMENT BY 1;

CREATE TRIGGER TTBTRIBUTACAO_IPI_B03I FOR TBTRIBUTACAO_IPI
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBTRIBUTACAO_IPI,1);
END;

CREATE OR ALTER TRIGGER TTBTRIBUTACAO_IPI_B01I FOR TBTRIBUTACAO_IPI
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('TBTRIBUTACAO_IPI',NEW.ID, HISTORICO);
    END
end;

CREATE OR ALTER TRIGGER TTBTRIBUTACAO_IPI_B02I FOR TBTRIBUTACAO_IPI
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE CODIGO VARCHAR(500);
BEGIN
        CODIGO = COALESCE((SELECT T.CODIGO FROM TBTRIBUTACAO_IPI T WHERE CODIGO = NEW.CODIGO), '');

        IF(CODIGO <> '') THEN
        BEGIN
            EXCEPTION "..." 'Codigo ja existente na tabela, por favor insira um Codigo diferente.';
        END

end;

CREATE OR ALTER TRIGGER TTBTRIBUTACAO_IPI_B03I FOR TBTRIBUTACAO_IPI
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GTBTRIBUTACAO_IPI,1);
END;

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

    HISTORICO = '';

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

    IF ( OLD.TRIBUTACAO <> NEW.TRIBUTACAO) THEN
    BEGIN
        HISTORICO = HISTORICO||',Campo Tributacao:'|| OLD.TRIBUTACAO||'->'||NEW.TRIBUTACAO;
    END

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

CREATE OR ALTER TRIGGER TTBTRIBUTACAO_IPI_B01D FOR TBTRIBUTACAO_IPI
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('TBTRIBUTACAO_IPI',OLD.ID, HISTORICO);
    END
end;


