Skip to content
Advertisement

Oracle : replace string of options based on data set – is this possible?

I have column in table looking like this:

Every option has a number of value. There is a table – let’s call it option_set and records look like

I want to replace option name to number in 1st table, if exists of course, if not exists then =0. I have done this in PLSQL (get the pattern, go through every option, and if exists – regexp_replace), but I am wondering if this could be done in SQL?? My goal is to replace values for all patterns for current OPTION_SET and get only records, where all equations would be greater than 0. Of course – I couldn’t run this equation in SQL, so I think of something like

Any ideas would be appreciated

Advertisement

Answer

You can do a loop-like query in SQL with the recursive CTE, replacing new token on each iteration, so this will let you to replace all the tokens. The only way I know to execute a dynamic query inside SQL statement in Oracle is DBMS_XMLGEN package, so you can evaluate the expression and filter by the result value without PL/SQL. But all this is viable for low cardinality tables with patterns and options.

Here’s the code:

ID | PATTERN                                                             | REPL_PATTERN                              | CALCULATED_VALUE
-: | :------------------------------------------------------------------ | :---------------------------------------- | :---------------
 1 | {([option1]+[option2])*([option3]+[option4])}                       | {(3653265+26452)*(73552+1235)}            | 275194995279    
 2 | {([option1]+[option2])*([option3]+[option4])*([option6]+[option7])} | {(3653265+26452)*(73552+1235)*(2330+544)} | 790910416431846 
 3 | {[option1]+[option6]}                                               | {3653265+2330}                            | 3655595         
 5 | {([option1]+[option2])*[option4]}                                   | {(3653265+26452)*1235}                    | 4544450495      

db<>fiddle here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement