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

    HISTORICO = '';
    HISTORICO_BASE = '';

    IF ( OLD.descricao <> NEW.descricao) THEN
    BEGIN
        HISTORICO = HISTORICO||'Desc:'|| OLD.descricao||'->'||NEW.descricao;
    END
    
    IF ( OLD.status <> NEW.status) THEN
    BEGIN
        HISTORICO = HISTORICO||' Status:'|| OLD.status||'->'||NEW.status;
    END
    
    IF (OLD.FISCO <> NEW.FISCO) THEN
    BEGIN
        HISTORICO = HISTORICO||' Fisco:'|| OLD.FISCO||'->'||NEW.FISCO;
    END
    
    IF (OLD.BASELEGAL <> NEW.BASELEGAL) THEN
    BEGIN
        HISTORICO_BASE = HISTORICO_BASE||'Base Legal:'||FN_ELIPSES(OLD.BASELEGAL,100)||'->'||FN_ELIPSES(NEW.BASELEGAL,100);
    END

    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO and new.STATUSEXCLUSAO = 0) THEN
    BEGIN
        HISTORICO = 'Registro Excluido';
    END
    
    IF ( OLD.STATUSEXCLUSAO <> NEW.STATUSEXCLUSAO and new.STATUSEXCLUSAO = 1) THEN
    BEGIN
        HISTORICO = 'Exclusão desfeita';
    END
    
    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBBASELEGAL',NEW.CODIGO, HISTORICO);
    END 
    
    IF (HISTORICO_BASE <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBBASELEGAL',NEW.CODIGO, HISTORICO_BASE);
    END
END;