oracle - replace value in string by excluding case when value is between parentheses

54 Views Asked by At

i would like to do an automatic replace with an oracle query in multiple strings available in an oracle table, by changing fields separator ','between first occurrence of 'select' and first occurrence of 'from' without having impact in case is in place a function:

AS IS:

with result as (select column_a, column_b, count(*)  from (select column1, column2, column3 ..
select column1, count(distinct coalesce(column2, cast('zz' as nvarchar2(2)))) as value from ...
select count(*) from (select ....

EXPECTED:

with result as (select column_a || column_b || count(*) from (select column1, column2, column3 ..
select column1 || count(distinct coalesce(column2, cast('zz' as nvarchar2(2)))) as value from ...
select count(*) from (select column1, column2, column3 ..
1

There are 1 best solutions below

3
PKey On

How about not even using replace_regexp, just use instr , substr and replace

with dt as (select 
'with result as (select column_a, column_b, count(*)  from (select column1, column2, column3 ..
select column1, count(distinct coalesce(column2, cast("zz" as nvarchar2(2)))) as value from ...
select count(*) from (select ....' as str from dual ),
 temp as ( 
select instr(str,'select'), instr(str,'from'), replace(substr(str,instr(str,'select')+length('select'),instr(str,'from')-instr(str,'select')-length('select')),',' ,' || ') fixed,
substr(str,0,instr(str,'select')+length('select')) astart ,
substr(str,instr(str,'select')+length('select'),instr(str,'from')-instr(str,'select')-length('select')) middle,
substr(str,instr(str,'from')) theend 
 from dt
 )
 select astart || middle || theend as  original, astart || fixed || theend as res
  from temp 

Here is the result, all you'll need later is to write an appropriate update statement.

original 

with result as (select  column_a, column_b, count(*)  from (select column1, column2, column3 ..
select column1, count(distinct coalesce(column2, cast("zz" as nvarchar2(2)))) as value from ...
select count(*) from (select ....

result

with result as (select  column_a ||  column_b ||  count(*)  from (select column1, column2, column3 ..
select column1, count(distinct coalesce(column2, cast("zz" as nvarchar2(2)))) as value from ...
select count(*) from (select ....