第一种方式建立函数:
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;
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 dbms_lob.substr(regexp_substr('abc,def,ggg,1,2,3,4,5', '[^,]+', 1, x.n)) as player_guid
from dual a, (select rownum n from dual connect by rownum < 100) x
这里利用了函数 regexp_substr和connect by
其中rownum < 100 会连接限制split的次数 '[^,]+'为split拆分的正则表达式,这里为【,】逗号
上面sql语句结果是:
abc
def
ggg
1
2
3
4
5
REGEXP_SUBSTR函数格式如下:
function REGEXP_SUBSTR(String, pattern, position, occurrence, modifier)
__srcstr :需要进行正则处理的字符串
__pattern :进行匹配的正则表达式
__position :起始位置,从第几个字符开始正则表达式匹配(默认为1)
__occurrence :标识第几个匹配组,默认为1
__modifier :模式('i'不区分大小写进行检索;'c'区分大小写进行检索。默认为'c'。)
第三种:
查询使用正则分割后的第一个值,也就是17
[sql]
SELECT REGEXP_SUBSTR('17,20,23','[^,]+',1,1,'i') AS STR FROM DUAL;
结果: www.2cto.com
STR
-----
17
获取一个多个数值的列,从而能够让结果以多行的形式展示出来
[sql]
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <=7;
结果: www.2cto.com
LEVEL
----
1
2
3
4
5
6
7
将上面REGEXP_SUBSTR的occurrence关联
[sql]
SELECT NVL(REGEXP_SUBSTR('17,20,23', '[^,]+', 1, LEVEL, 'i'), 'NULLL') AS STR
FROM DUAL
CONNECT BY LEVEL <= 7;
STR www.2cto.com
----
17
20
23
NULL
NULL
NULL
NULL
优化上面的SQL语句,让生成的行的数量符合实际情况
[sql]
SELECT REGEXP_SUBSTR('17,20,23', '[^,]+', 1, LEVEL, 'i') AS STR
FROM DUAL
CONNECT BY LEVEL <=
LENGTH('17,20,23') - LENGTH(REGEXP_REPLACE('17,20,23', ',', ''))+1;
STR
----
17
20
23