Oracle 字符串替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1312662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 18:50:44  来源:igfitidea点击:

Oracle string replacement

oracleplsql

提问by AJM

I have a column in my oracle database which due reasons beyond my control contains a CSV string e.g.

我的 oracle 数据库中有一个列,由于我无法控制的原因包含一个 CSV 字符串,例如

Item a,Item b,Item c,Item d

项目a,项目b,项目c,项目d

I want to run an UPDATE statement to get rid of item c. Thus ending up with

我想运行一个 UPDATE 语句来摆脱项目 c。从而结束

Item a,Item b,Item d

项目a,项目b,项目d

How can I achieve this

我怎样才能做到这一点

回答by Chris Cameron-Mills

You could use the Oracle REPLACEfunction:

您可以使用 Oracle REPLACE函数:

UPDATE table
SET col = replace(col, 'item c', '')

You just need to be careful handling it as part of a CSV, e.g stripping a following comma. This could mean replacing 'item c,' first and then replacing 'item c' to capture both cases.

您只需要小心地将其作为 CSV 的一部分进行处理,例如去除以下逗号。这可能意味着首先替换“item c”,然后替换“item c”以捕获这两种情况。



EDIT: ah, I might have misunderstood. My solution is based on removing a particular string from your CSV - if you are looking to always replace the 3rd item then Vincent's answer is the one you'll need

编辑:啊,我可能误解了。我的解决方案基于从 CSV 中删除特定字符串 - 如果您希望始终替换第 3 项,那么 Vincent 的答案就是您需要的答案

回答by andri

If you have a fairly recent version of Oracle (I believe regular expressions were introduced in Oracle 10), you can use REGEXP_REPLACE:

如果你有一个相当新版本的 Oracle(我相信正则表达式是在 Oracle 10 中引入的),你可以使用REGEXP_REPLACE

UPDATE table SET column = REGEXP_REPLACE(column,'[^\,]+,','',1,3)

(Also, please do violent things to the genius who stored CSV this way in a relational database.)

(另外,请对以这种方式将CSV存储在关系数据库中的天才做暴力。)

回答by Vincent Malgrat

you could use a combination of INSTR and SUBSTR to remove the third field:

您可以使用 INSTR 和 SUBSTR 的组合来删除第三个字段:

SQL> WITH a AS (SELECT 'Item a,Item b,Item c,Item d' col FROM dual)
  2   SELECT substr(col, 1, instr(col, ',', 1, 2))
  3          || substr(col, instr(col, ',', 1, 3) + 1) sub
  4     FROM a;

SUB
--------------------
Item a,Item b,Item d