在更新中使用replace()函数来更改一列的多个子字符串

use*_*426 4 sql postgresql pattern-matching sql-update

假设我有student一个带有列的表name
name列的值为“studenttone”、“studenttwo”、“student Three”
,我想将它们替换为“student1”、“student2”、“student3”。

对于单个替换来说非常简单:

update student set name = replace(name, 'one', '1')
Run Code Online (Sandbox Code Playgroud)

但是多次替换呢?任何想法?

Boh*_*ian 6

我只会使用多个更新语句,但如果您绝对必须在一个语句中执行此操作,只需嵌套替换调用即可:

update student set
  name = replace(replace(replace(name, 'one', '1'), 'two', '2'), 'three', '3')
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为(尽管效率低下)replace()如果未找到搜索项,则调用不会产生任何效果。