1 首先,定义一个Oracle数据类型,为了被函数(Function)引用
create or replace TYPE TYP_STR_SPLIT
-- 参考需求定义Size大小
AS TABLE OF VARCHAR2 (4000);
2 定义函数(Function)
create or replace FUNCTION fnc_str_split (
p_list VARCHAR2,
p_sep VARCHAR2
) RETURN typ_str_split
PIPELINED
IS
l_idx PLS_INTEGER;
-- 参考需求定义Size大小, 与 TYPE TYP_STR_SPLIT 对应
v_list VARCHAR2(4000) := p_list;
BEGIN
IF v_list IS NULL OR LENGTH(v_list) <= 0 then
return;
END IF;
LOOP
l_idx := instr(v_list, p_sep);
IF l_idx > 0 THEN
PIPE ROW ( substr(v_list, 1, l_idx - 1) );
v_list := substr(v_list, l_idx + length(p_sep));
ELSE
PIPE ROW ( v_list );
EXIT;
END IF;
END LOOP;
return;
END fnc_str_split;
3 测试结果
4 在存储过程中使用,循环遍历split后的字符串集合(table)
--省略存储过程定义语句....
IS
--定义type在IS语句块中
test_split_list TYP_STR_SPLIT;
BEGIN
select FNC_STR_SPLIT('aaa,bbb,ccc ,ddd, e e e', ',') into test_split_list from dual;
FOR v_index IN test_split_list.first .. test_split_list.last LOOP
dbms_output.put_line('test_split_list index: ' || test_split_list || ', value:' || test_split_list(v_index));
END LOOP;