regexp_substr函數
regexp_substr(srcstr, pattern, position, occurrence, modifier)
-srcstr:需要處理的字符串;
-pattern:正則表達式;
-position:起始位置,從第幾個字符開始正則表達式匹配。默認爲1;
-occurrence:標識第幾個匹配組,默認爲1;
-modifier:'i’不區分大小寫檢索;‘c’區分大小寫檢索。默認爲’c’ 。
occurrence設爲level,會得到分割後的所有結果。level是oracle的關鍵字,表示查詢深度,用來實現層級查詢。
統計字符串指定字符個數
length(v_numlist) - length(replace(v_numlist, ',', ''))
v_numlist是原字符串,求出逗號的個數
通過求出原字符串長度和刪除指定字符的字符串長度,相減獲得統計個數
模擬split拆分檢索
假設表tab1中僅有一行記錄,內容如下:
Numlist | Num | Posi |
---|---|---|
23,56,90,543,91 | 91 |
其中Posi列的值爲空
求Num列的數字在Numlist列中第一次出現時是第幾個數字,並把結果更新到Posi列中。如果找不到,則寫-1。
例如,當Numlist = ‘23,56,90,543,91’,Num = 91時,Posi = 5;
當Numlist = ‘23,56,90,543,91’,Num = 54時,Posi = -1。
注意:儘管543中有54這個數字,但並不認爲54出現過。
根據這些條件,使用字符串拆分或許是最快的辦法。
drop table tab1;
create table tab1(
numlist varchar2(30),
num varchar2(30),
posi number
);
insert into tab1 values('23,56,90,543,91', '91', null);
set serveroutput on
declare
v_numlist tab1.numlist % type;
v_num tab1.num % type;
v_posi number;
begin
select numlist, num
into v_numlist, v_num
from tab1;
select index_level
into v_posi
from (
select regexp_substr(v_numlist, '[^,$]+', 1, level) str, level index_level
from dual
connect by level <= length(v_numlist) - length(replace(v_numlist, ',', '')) + 1
)
where str = v_num and rownum <= 1;
update tab1 set posi = v_posi where num = v_num;
exception
when no_data_found then
update tab1 set posi = -1 where num = v_num;
end;
/
select * from tab1;
注意一點,統計是統計指定字符個數,拆分後的字符串個數是統計值+1
所以,level <= length(v_numlist) - length(replace(v_numlist, ‘,’, ‘’)) + 1