można użyć rekurencyjnej faktoring podzapytania (rekurencyjne 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;
Co dowcip h Twoje dane zawierają:
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 z dwoma adresami.
Możesz także przekonwertować te częściowe wartości na kolumny, co według mnie jest Twoim celem docelowym, np. jako widok:
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.
Warto zauważyć, że jeśli długość street_address
zbliża się do 120 znaków, może nie pasować do 3 bloków 40-znakowych - tracisz kilka znaków w zależności od długości słowa zawijanego do następnej "linii" . Takie podejście wygeneruje więcej niż 3 linie, ale widok używa tylko pierwszych trzech, więc możesz stracić koniec adresu. Możesz chcieć, aby pola były dłuższe lub mieć address_4
w takich sytuacjach ...
Gdzie będą wyświetlane te kolumny? Dlaczego nie podzielisz go na poziomie aplikacji? – bjan