您可以使用递归子查询分解(递归 CTE):
with s (street_address, line, part_address, remaining) as (
select street_address, 0 as line,
null as part_address, street_address as remaining
from address
union all
select street_address, line + 1 as line,
case when length(remaining) <= 40 then remaining else
substr(remaining, 1, instr(substr(remaining, 1, 40), ' ', -1, 1)) end
as part_address,
case when length(remaining) <= 40 then null else
substr(remaining, instr(substr(remaining, 1, 40), ' ', -1, 1) + 1) end
as remaining
from s
)
cycle remaining set is_cycle to 'Y' default 'N'
select line, part_address
from s
where part_address is not null
order by street_address, line;
你的数据给出了:
LINE PART_ADDRESS
---------- ----------------------------------------
1 152 Main st North Pole Factory 44, near
2 the rear entrance cross the street and
3 turn left and keep walking straight.
带有两个地址的SQL Fiddle 演示。
您还可以将这些部分值转换为列,我认为这是您的最终目标,例如作为视图:
create or replace view v_address as
with cte (street_address, line, part_address, remaining) as (
select street_address, 0 as line,
null as part_address, street_address as remaining
from address
union all
select street_address, line + 1 as line,
case when length(remaining) <= 40 then remaining else
substr(remaining, 1, instr(substr(remaining, 1, 40), ' ', -1, 1)) end
as part_address,
case when length(remaining) <= 40 then null else
substr(remaining, instr(substr(remaining, 1, 40), ' ', -1, 1) + 1) end
as remaining
from cte
)
cycle remaining set is_cycle to 'Y' default 'N'
select street_address,
cast (max(case when line = 1 then part_address end) as varchar2(40))
as address_1,
cast (max(case when line = 2 then part_address end) as varchar2(40))
as address_2,
cast (max(case when line = 3 then part_address end) as varchar2(40))
as address_3
from cte
where part_address is not null
group by street_address;
另一个 SQL Fiddle。
可能值得注意的是,如果street_address
长度接近 120 个字符,它可能无法整齐地放入 3 个 40 个字符的块中 - 您会丢失一些字符,具体取决于包裹到下一个“行”的单词的长度。这种方法会生成多于 3 行,但视图只使用前三行,因此您可能会丢失地址的结尾。您可能希望使字段更长,或者在address_4
这些情况下使用...