你可以使用递归子查询分解(递归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;
哪个机智^ h你的数据得出:
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 demo有两个地址。
您也可以将这些部分值转换为列,我认为这是您的最终目标,例如,作为看法:
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;
Another SQL Fiddle。
值得注意的是,如果street_address
长度接近120个字符,它可能不适合整齐地放入3个40个字符的块中 - 根据缠绕到下一个“行”的单词的长度, 。这种方法会生成超过3行,但视图只使用前三行,因此您可能会丢失地址的末尾。您可能希望使字段更长,或者对于这些情况有address_4
...
您将在哪里显示这些列?你为什么不把它分成应用程序级别? – bjan