Oracle字符串行拆分成列的三種方式


Oracle字符串行拆分成列的三種方式

     --muphy

開發過程中經常會遇到將前台多個值用逗號連接一同傳遞到后台查詢,這個用逗號連接的字符串分隔的每個字符串分別對應Oracle數據庫表的不同行。

 

 

如下一個表table_test的內容如下:

name       value

pa           5

pb           6

pc           8

 

 

需要查詢分別與papb相同的行,參數字符串為:

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, '[^,]+'1levelname

   from dual

 connect by regexp_substr(pi_names, '[^,]+'1levelis 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, '[^,]+'1rownum) 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM