Oracle 子字符串去重
今天碰到一个问题,查询出一个字段值,形如: 100010,100011,100012,100013,100014,100015,100016,100011,100012,100013,100014,100015,100016
的由逗号分隔的字符串,其中后面(红色部分)的子字符串与前面子字符串重复。去除其中重复的子字符串。
1、function : fun_rep_repeat_str(),如下
create or replace function fun_rep_repeat_str(p_str varchar2,p_sep varchar2)
return varchar2 deterministic is
/*
* 字符串中,子字符串去重
* p_str: 需要去重的字符串
* p_sep: 分隔符
* 例: select fun_rep_repeat_str('100010,100011,100012,100013,100014,100015,100016,100011,100012,100013,100014,100015,100016') from dual;
*/
type v_type is table of varchar2(4000);
v_tab v_type;
v_res varchar2(4000);
cursor c_get_str is
select regexp_substr(p_str, '[^' || p_sep || ']+', 1, level) str
from dual
connect by level <= length(regexp_replace(p_str, '[^' || p_sep || ']')) + 1;
begin
open c_get_str;
fetch c_get_str bulk collect
into v_tab;
close c_get_str;
--集合去重
v_tab := set(v_tab);
for x in 1 .. v_tab.count loop
v_res := v_res || v_tab(x) || p_sep;
end loop;
return rtrim(v_res, p_sep);
end;
2、测试
select fun_rep_repeat_str('100010,100011,100012,100013,100014,100015,100016,100011,100012,100013,100014,100015,100016',',') from dual;
-- 结果: 100010,100011,100012,100013,100014,100015,100016