Oracle字符串行拆分成列的三種方式
--muphy
開發過程中經常會遇到將前台多個值用逗號連接一同傳遞到后台查詢,這個用逗號連接的字符串分隔的每個字符串分別對應Oracle數據庫表的不同行。
如下一個表table_test的內容如下:
name value
pa 5
pb 6
pc 8
需要查詢分別與pa和pb相同的行,參數字符串為:
pi_names=”pa,pb”
如何查詢呢,有以下三種方式(根據執行計划分析,效率由低到高排列):
1. 使用Oracle Database 11g Release 2及更高版本時,可以使用遞歸with子查詢:
with a(name, i)
as
(select regexp_substr(pi_names, '[^,]+') name,
substr(pi_names || ',', instr(pi_names, ',') + 1) i
from dual
union all
select regexp_substr(i, '[^,]+'), substr(i, instr(i, ',') + 1)
from a
where instr(i, ',') <> 0)
select t.name, t.value from table_test t inner join a on a.name = t.name
2. 使用connect by語句實現之方式一:
with a as
(select distinct regexp_substr(pi_names, '[^,]+', 1, level) name
from dual
connect by regexp_substr(pi_names, '[^,]+', 1, level) is not null
)
select t.name, t.value from table_test t inner join a on a.name = t.name
3. 使用connect by語句實現之方式二:
with a as
(select regexp_substr(pi_names, '[^,]+', 1, rownum) name
from dual
connect by rownum <= length(pi_names) -
length(replace(pi_names, ',')) + 1)
select t.name, t.value from table_test t inner join a on a.name = t.name