Oracle拆分字符串,字符串分割的函数。
第⼀种:oracle字符串分割和提取
分割
create or replace function Get_StrArrayLength
(
av_str varchar2,  --要分割的字符串
av_split varchar2  --分隔符号
)
return number
is
lv_str varchar2(1000);
lv_length number;
begin
lv_str:=ltrim(rtrim(av_str));
lv_length:=0;
while instr(lv_str,av_split)<>0 loop
lv_length:=lv_length+1;
lv_str:=substr(lv_str,instr(lv_str,av_split)+length(av_split),length(lv_str));
end loop;
lv_length:=lv_length+1;
return lv_length;
end Get_StrArrayLength;
提取
create or replace function Get_StrArrayStrOfIndex
(
av_str varchar2,  --要分割的字符串
av_split varchar2,  --分隔符号
av_index number --取第⼏个元素
)
return varchar2
is
lv_str varchar2(1024);
lv_strOfIndex varchar2(1024);
lv_length number;
begin
lv_str:=ltrim(rtrim(av_str));
lv_str:=concat(lv_str,av_split);
lv_length:=av_index;
if lv_length=0 then
lv_strOfIndex:=substr(lv_str,1,instr(lv_str,av_split)-length(av_split));
else
lv_length:=av_index+1;
lv_strOfIndex:=substr(lv_str,instr(lv_str,av_split,1,av_index)+length(av_split),instr(lv_str,av_split,1,lv_length)-instr(lv_str,av_split,1,av_index)-length(av_split));  end if;
return  lv_strOfIndex;
end Get_StrArrayStrOfIndex;
测试:  select Get_StrArrayStrOfIndex('songguojun$@111111537','$',0) from dual
结果:
第⼆种:
本函数可以将“⽬标字符串”以“指定字符串”进⾏拆分,并通过表结构返回结果。代码如下:
CREATE OR REPLACE TYPE str_split IS TABLE OF VARCHAR2 (4000);
CREATE OR REPLACE FUNCTION splitstr(p_string IN VARCHAR2, p_delimiter IN VARCHAR2)    RETURN str_split
PIPELINED
AS
v_length  NUMBER := LENGTH(p_string);
v_start    NUMBER := 1;
oracle 字符串转数组v_index    NUMBER;
BEGIN
WHILE(v_start <= v_length)
LOOP
v_index := INSTR(p_string, p_delimiter, v_start);
IF v_index = 0
THEN
PIPE ROW(SUBSTR(p_string, v_start));
v_start := v_length + 1;
ELSE
PIPE ROW(SUBSTR(p_string, v_start, v_index - v_start));
v_start := v_index + 1;
END IF;
END LOOP;
RETURN;
END splitstr;
创建完毕后,我们来测试⼀下,例如执⾏如下SQL:
select * from table(splitstr('Hello,Cnblogs!',','));
其输出结果为⼀个两⾏的表,如下图:
将⾏转为列显⽰:
lumn_value lumn_value v2 from
(select * from (select rownum rn,t.* from table(splitstr('Hello,Cnblogs!',',')) t)) a,
(select * from (select rownum rn,t.* from table(splitstr('Hello,Cnblogs!',',')) t)) b
=1 =2
如图:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。