使用查找表替换Oracle字符串

时间:2013-08-20 18:16:48

标签: oracle10g

有人可以帮我解决这个问题吗? 我将我的客户端地址存储在表(表CT)中,作为一个字符串,可能有一些缩写数据。示例:123 RD。我有另一个查找表(表LK),其中包含缩写的可能的街道名称。 RD = ROAD。 我想创建一个新表,其中包含该字符串的完整地址。

输入:

table CT:

Add1     Add2   Add3
------------------------
123 RD   APT 2  BLDG 1
test DR  null   null
main RD  null   BLDG2


table LK:

abbreviation      completestreet
----------------------------------
RD                road
APT               apartment
BLDG              building
DR                drive

我想加入这两个表来实现以下目标:

123 ROAD      APARTMENT 2    BUILDING 1
test DRIVE    null           null
main ROAD     null           BUILDING 2

1 个答案:

答案 0 :(得分:0)

您可能希望找到一个使用regexp_replace以及 regexp字边界 ^||$的解决方案:

with ct as (
  select '123 RD'          add1, 'APT 2' add2, 'BLDG 1' add3 from dual union all
  select '123 3RD street'  add1, 'APT 2' add2, 'BLDG 1' add3 from dual union all
  select 'test DR'         add1, ''      add2, ''       add3 from dual union all
  select 'main RD'         add1, ''      add2, 'BLDG2'  add3 from dual
),
lk as (
  select 'RD'    abbreviation, 'road'       completestreet from dual union all
  select 'APT'   abbreviation, 'apartment'  completestreet from dual union all
  select 'BLDG'  abbreviation, 'building'   completestreet from dual union all
  select 'DR'    abbreviation, 'drive'      completestreet from dual
),
recursion (add1, add2, add3, l) as (
  select add1, add2, add3, 1 l from ct union all
  select regexp_replace(add1, '(^| )' ||abbreviation || '( |$)', '\1' || completestreet || '\2'),
         regexp_replace(add2, '(^| )' ||abbreviation || '( |$)', '\1' || completestreet || '\2'),
         regexp_replace(add3, '(^| )' ||abbreviation || '( |$)', '\1' || completestreet || '\2'),
         l+1
    from recursion join (
            select 
               row_number() over (order by abbreviation) r, 
               abbreviation, 
               completestreet 
             from lk
         ) lk
         on l=r
)
select substrb(add1, 1, 30),
       substrb(add2, 1, 30),
       substrb(add3, 1, 30)
  from recursion
 where l=(select count(*)+1 from lk);