Firebird像在Oracle中一样创建函数TRANSLATE

时间:2015-04-08 13:48:56

标签: oracle firebird firebird-3.0

我尝试使用与Oracle中的TRANSLATE函数相同的功能创建一个函数,我在O​​racle中创建了函数并且它运行良好但是当我尝试将此代码重写为Firebird时我遇到了问题。我收到的错误是表达式评估不受支持'。为什么呢?

CREATE FUNCTION TRANSLATEE
(text varchar(10000),
toReplace varchar(10000),
replacePattern varchar(10000)
)
RETURNs VARCHAR(100)
aS

declare variable cut varchar(100);
declare variable i integer;
declare variable position1  varchar(100);
declare variable resultat  varchar(100);
declare variable letter  varchar(100);
declare variable lenght integer;
BEGIN
i = 1;
resultat ='';
lenght =  char_length(:text);
while(i<lenght) do
begin
    cut = substring(:text from i for 1);
    position1 = position(:toReplace , cut);
      if (position(:toReplace , cut) >0) then
      begin
        letter = substring(:replacePattern from position1 for 1);
        resultat = resultat||''||letter;
        end
      else 
      begin
       resultat = resultat ||''|| cut;
      end
  i = i+1;
end
  RETURN resultat;
END;

2 个答案:

答案 0 :(得分:1)

主要问题是您已将position1声明为VARCHAR(100)而非INTEGER。这导致了无用的错误,因为没有带有varchar参数的子字符串版本(在此上下文中,不支持从varchar转换为整数)。

您的函数的工作(或至少:编译)版本是:

CREATE OR ALTER FUNCTION TRANSLATE_func
   (text varchar(10000), 
    toReplace varchar(10000), 
    replacePattern varchar(10000))
RETURNS VARCHAR(100)
AS
   declare variable resultat varchar(100);
   declare variable cut varchar(100);
   declare variable i integer;
   declare variable position1  integer;
   declare variable letter  varchar(100);
   declare variable lenght integer;
BEGIN
   i = 1;
   resultat ='';
   lenght =  char_length(text);
   while(i <= lenght) do
   begin
       cut = substring(text from i for 1);
       position1 = position(cut, toReplace);
       if (position1 > 0) then
       begin
           letter = substring(replacePattern from position1 for 1);
           resultat = resultat||''||letter;
       end
       else 
       begin
           resultat = resultat ||''|| cut;
       end
       i = i+1;
   end
   return resultat;
END

答案 1 :(得分:0)

对于Firebird 3

SET TERM ^ ;

create function translator (
    inp varchar(10000),
    pat varchar(1000),
    rep varchar(1000))
returns varchar(10000)
as
    declare variable tex varchar(10000);
    declare variable inp_idx integer = 1;
    declare variable cha char(1);
    declare variable pos integer;
begin
  tex = '';
  while (inp_idx <= char_length(inp)) do
  begin
    cha = substring(inp from inp_idx for 1);
    pos = position(cha, pat);
    if (pos > 0) then
      cha = substring(rep from pos for 1);
    tex = tex || cha;
    inp_idx = inp_idx + 1;
  end
  return tex;
end^

SET TERM ; ^

测试

select translator('džiná lasaí ireo dana kýrne číraž', 'ážíýč', 'AZIYC')
  from rdb$database;

结果

dZinA lasaI ireo dana kYrne CIraZ