CREATE OR ALTER FUNCTION FN_REPLACE_CHAR (
    STRING VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
declare variable string2 varchar(1000);
declare variable a integer;
declare variable b varchar(1);
declare variable n integer;
begin
    a = 1;
    n = CHAR_LENGTH(trim(STRING));
    string2 = STRING;
    While (a < n+1) do
    begin
        b = SUBSTRING(STRING from a for 1);
        if(POSITION(b IN '0123456789') = 0) then
        begin
            string2 = replace(string2,b,'');
        end
        a = a+1;
    end

  return string2;
end;

CREATE OR ALTER TRIGGER TTBEMPRESA_B01IU FOR TBEMPRESA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
declare variable CNPJ VARCHAR(100);
begin
  IF(NEW.CNPJ IS NOT NULL) THEN
  BEGIN
     CNPJ = FN_ELIPSES(FN_REPLACE_CHAR(NEW.CNPJ),14);
     NEW.CNPJ = CNPJ;
  END
end;

CREATE TRIGGER TTBNFS_B01IU FOR TBNFS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
declare variable CNPJ VARCHAR(100);
begin
  IF(NEW.EMPRESA_CNPJ IS NOT NULL) THEN
  BEGIN
     CNPJ = FN_ELIPSES(FN_REPLACE_CHAR(NEW.EMPRESA_CNPJ),14);
     NEW.EMPRESA_CNPJ = CNPJ;
  END
end;

CREATE TRIGGER TTBNFE_B01IU FOR TBNFE
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
declare variable CNPJ VARCHAR(100);
begin
  IF(NEW.EMPRESA_CNPJ IS NOT NULL) THEN
  BEGIN
     CNPJ = FN_ELIPSES(FN_REPLACE_CHAR(NEW.EMPRESA_CNPJ),14);
     NEW.EMPRESA_CNPJ = CNPJ;
  END
end;



