ALTER TABLE TBHISTPADRAO
    ADD STATUS INTEGER;
	
CREATE TRIGGER TTBHISTPADRAO_B01I FOR TBHISTPADRAO
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('TBHISTPADRAO',NEW.ID, HISTORICO);
    END
end;

CREATE TRIGGER TTBHISTPADRAO_B01D FOR TBHISTPADRAO
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('TBHISTPADRAO',old.ID, HISTORICO);
    END
end;

CREATE TRIGGER TTBHISTPADRAO_B01U FOR TBHISTPADRAO
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 (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBHISTPADRAO',NEW.ID, HISTORICO);
    END
end;

CREATE TRIGGER TTBHISTPADRAO_B02U FOR TBHISTPADRAO
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

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

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

CREATE OR ALTER trigger ttbhistpadrao_b01u for tbhistpadrao
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.STATUS <> NEW.STATUS) THEN
    BEGIN
        HISTORICO = HISTORICO||', Status:'|| OLD.STATUS||'->'||NEW.STATUS;
    END

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

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

