1.首先需要定义一个集合类型,我这里定义的是变长数组类型(VARRAY)
create type type_splitstr is varray(1024) of varchar2(128);
--注意,我这里之所以不用嵌套表类型(NESTED TABLE),是因为oracle官方文档有如下说明。
--Nested Tables: The indexes and row order of a nested table might not remain stable as you store and retrieve the nested table from the database.
--Varrays (Variable-Size Arrays): When you store and retrieve a varray from the database,its indexes and element order remain stable.
2.创建自定义函数,实现字符串的拆分
create or replace function func_splitstr
(var_str in varchar2,--要拆分的字符串
var_split in varchar2--分隔符
) return type_splitstr
is
var_out type_splitstr;
var_tmp varchar2(4000);
var_element varchar2(128);
begin
var_tmp := var_str;
var_out:=type_splitstr();
while instr(var_tmp,var_split) > 0 --如果存在匹配的分割符
loop
var_element := substr(var_tmp,1,instr(var_tmp,var_split) - 1); --截取一个元素
var_tmp := substr(var_tmp,
instr(var_tmp,var_split) + length(var_split),
length(var_tmp)); --获取截取后剩下的字符串
var_out.extend;
var_out(var_out.count) := var_element; --向数组的末尾添加一个元素
end loop;
var_out.extend;
var_out(var_out.count) := var_tmp;
return var_out;
end func_splitstr;
/
使用:
sql> select * from table(func_splitstr('1|2|3,4|5|6',','));
COLUMN_VALUE
--------------------------------------------------------------
1|2|3
4|5|6
sql>