CREATE trigger ttbregiao_b02i for tbregiao
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('TBREGIAO',NEW.ID, HISTORICO);
    END
END;


CREATE trigger ttbregiao_b01d for tbregiao
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('TBREGIAO',OLD.ID, HISTORICO);
    END
END;


CREATE trigger ttbregiao_b01u for tbregiao
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.UF IS DISTINCT FROM OLD.UF) THEN
    BEGIN
        HISTORICO = HISTORICO||' UF:'||COALESCE(OLD.UF, '')||'->'||COALESCE(NEW.UF, '');
    END

    IF ( NEW.CIDADE IS DISTINCT FROM OLD.CIDADE) THEN
    BEGIN
        HISTORICO = HISTORICO||' CIDADE:'||COALESCE(OLD.CIDADE, '')||'->'||COALESCE(NEW.CIDADE, '');
    END

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

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