1. 程式人生 > 其它 >oracle 按指定字元拆分字串(split)

oracle 按指定字元拆分字串(split)

1.情景展示

在oracle當中,如何拆分以逗號隔開的字串?(將字串按指定字元拆分成多行資料)

比如:411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681。

2.具體分析

oracle當中專門的字串拆分函式,但是,我們可以通過REGEXP_SUBSTR()和CONNECT BY LEVEL來實現。

3.解決方案

語法:

SELECT REGEXP_SUBSTR(string,
                     '[^特定字元]+',
                     1,
                     LEVEL,
                     'i') as 分割後結果
  FROM DUAL
CONNECT BY LEVEL <= 特定字元在字串當中出現的次數 + 1;

進一步優化

SELECT REGEXP_SUBSTR(string,
                     '[^特定字元]+',
                     1,
                     LEVEL,
                     'i') as 起個別名
  FROM DUAL
CONNECT BY LEVEL <= LENGTHB(TRANSLATE(string, '特定字元' || string, '特定字元')) + 1;
檢視程式碼

SELECT REGEXP_SUBSTR('411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681',
                     '[^,]+',
                     1,
                     LEVEL,
                     'i') as 分割後結果
  FROM DUAL
CONNECT BY LEVEL <= LENGTHB(TRANSLATE('411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681', ',' || '411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681', ',')) + 1;
SELECT REGEXP_SUBSTR('411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681',
                     '[^,]+',
                     1,
                     LEVEL,
                     'i') as 分割後結果
  FROM DUAL
CONNECT BY LEVEL <= LENGTHB(TRANSLATE('411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681',
                                      ',' ||
                                      '411600,411602,411603,411606,411609,411621,411622,411623,411624,411625,411626,411627,411628,411643,411681',
                                      ',')) + 1;

 

寫在最後

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦: