如何在Postgres 9.5中替换多个特殊字符

问题描述:

我有一个表,其中包含一个可能包含特殊字符的名称列表:

I have a table containing a list of name which might contain special character:

id   name
1    Johän
2    Jürgen
3    Janna
4    Üdyr
...

是否存在将每个字符替换为另一个特定字符的功能? (未必是一个不加强调的人)。像这样的东西:

Is there a function that replaces each character for another specific one? (Not necessarily an unaccented one). Something like this:

SELECT id, function('ä,ü',name,'ae,ue');
Result:

    id   name
    1    Johaen
    2    Juergen
    3    Janna
    4    UEdyr
    ...


不,没有此功能。可能不难编写优化的C扩展。但是C语言不一定总是必需的。您可以尝试使用SQL或PLpgSQL函数:

No, there are no this function. Probably is not to hard to write optimized C extension what does it. But C language is not necessary always. You can try SQL or PLpgSQL function:

CREATE OR REPLACE FUNCTION xx(text, text[], text[])
RETURNS text AS $$
   SELECT string_agg(coalesce($3[array_position($2, c)],c),'')
      FROM regexp_split_to_table($1,'') g(c)
$$ LANGUAGE sql;

postgres=# select xx('Jürgen', ARRAY['ä','ü'], ARRAY['ae','ue']);
┌─────────┐
│   xx    │
╞═════════╡
│ Juergen │
└─────────┘
(1 row)

在我的电脑上在200毫秒内完成6000次转换(但我有PostgreSQL开发人员版本-速度较慢)。

On my comp it does 6000 transformation under 200ms (but I have developer build of PostgreSQL - it is slower).