Oracle - replace string by appearance

走远了吗. 提交于 2021-01-29 05:37:19

问题


I have an interesting issue here, if you could share your thoughts ... I changed data a bit, but structure is same

create table TestReplace (Description varchar2(500), ParamValue1 number, ParamValue2 number, ParamValue3 number);
insert into TestReplace (Description) values ('This sentence has no parameteres, and it should be shown like this');
insert into TestReplace (Description, ParamValue1) values ('This sentence has only one parametere, and it should be shown right here {param} with rest of text', 100);
insert into TestReplace (Description, ParamValue1, ParamValue2) values ('This sentence has two parameteres, one here {param} and one here {param}, show full sentence', 100, 200);
insert into TestReplace (Description, ParamValue1, ParamValue2, ParamValue3) values ('This sentence has all parameteres, here {param} and here {param} and there {param}', 100, 200, 300);

COMMIT;

In my sentence I have occurrences of a word {param} sometimes or never ... and columns ParamValue1, ParamValue2, ParamValue3 ... How could I replace first occurences of a word {param} with value of column ParamValue1, second word {param} with value of column ParamValue2 and third with value of column ParamValue3

I tried something like this ...

select CASE WHEN ParamValue1 IS NULL 
    THEN Description 
   ELSE 
    substr(Description, 1, INSTR(Description,'{param}', 1, 1) - 1) || ParamValue1 ||
        CASE WHEN ParamValue2 IS NULL 
            THEN substr(Description, INSTR(Description,'{param}', 1, 1) + 7, LENGTH(Description) - INSTR(Description,'{param}', 1, 1) + 6)
        WHEN ParamValue2 IS NOT NULL THEN
            substr(Description, INSTR(Description,'{param}', 1, 1) + 7, INSTR(Description,'{param}', 1, 2) + 6 - INSTR(Description,'{param}', 1, 1) + 6) || ParamValue2
       END
    END
   END
from TestReplace

But it's not getting me anywhere, and personally don't think this will be pretty / fast on larger set of rows

So how could I accomplish this text replacement?


回答1:


Use nested invocations of REGEXP_REPLACE:

SELECT REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(DESCRIPTION, 
                                                    '{param}', PARAMVALUE1, 1, 1),
                                     '{param}', PARAMVALUE2, 1, 1),
                      '{param}', PARAMVALUE3, 1, 1)
  FROM TESTREPLACE

dbfiddle here



来源:https://stackoverflow.com/questions/58375951/oracle-replace-string-by-appearance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!