SQL替换基于查找表

时间:2016-10-28 17:13:25

标签: sql oracle

如何根据查找表替换字符串?

我需要将来自Old_value的{​​{1}}字符串中的Lookup_Table的所有实例替换为来自Column1 Table1 New_Value的{​​{1}} }}

例如:

表1

Lookup_Table

Lookup_Table

"Column1"
'The Quick BC'
'The Quick BD'

Desired_Output

"Old_value"  | "New_Value"
'BC'         | 'Brown Cat'
'BD'         | 'Brown Dog'

1 个答案:

答案 0 :(得分:1)

显而易见的想法是在LIKE条件下加入两个表。 outer连接保证将返回没有匹配的输入(不进行任何更改)。但是,这仅在每个输入字符串在查找表中找到AT MOST一个子字符串时才有效。对于更通用的解决方案,您将需要某种递归查询以及其他规则:如果BC和BCD都出现在查找表中,并且您有像ABCDE这样的输入,该怎么办?哪个优先 - 你会取代BC还是BCD?

with
     Table1 ( Column1 ) as ( 
       select 'The Quick BC' from dual union all
       select 'The Quick BD' from dual
     ),
     Lookup_Table ( Old_value, New_Value) as (
       select 'BC', 'Brown Cat' from dual union all
       select 'BD', 'Brown Dog' from dual
     )
-- end of test data; the solution (SQL query) begins below this line
select column1, replace(t1.column1, lt.old_value, lt.new_value) as new_column1
from   table1 t1 left outer join lookup_table lt
                 on t1.column1 like '%' || lt.old_value || '%'
;


COLUMN1       NEW_COLUMN1
------------  -------------------
The Quick BC  The Quick Brown Cat
The Quick BD  The Quick Brown Dog