Oracle字符串拆分實例詳解

Oracle字符串拆分

比如把一列 a,b,c 拆分為

a
b
c

1. 使用regexp_substr()函數

1.1 拆分aaa,bbb,ccc

SELECT
	regexp_substr('aaa,bbb,ccc', '[^,]+', 1, LEVEL)
FROM
	dual
CONNECT BY
	LEVEL <= LENGTH('aaa,bbb,ccc')-LENGTH(REPLACE('aaa,bbb,ccc', ','))+ 1;

輸出結果:

1.2 拆分aaa;bbb;ccc

SELECT
	regexp_substr('aaa;bbb;ccc', '[^;]+', 1, LEVEL)
FROM
	dual
CONNECT BY
	LEVEL <= LENGTH('aaa;bbb;ccc')-LENGTH(REPLACE('aaa;bbb;ccc', ';'))+ 1;

1.3 level作用

SELECT LEVEL FROM dual CONNECT BY LEVEL<10;

2. 在oracle中實現MySQL的find_in_set()函數

2.1 使用oracle的函數定義函數FIND_IN_SET()

FIND_IN_SET(str,strlist)

CREATE OR REPLACE FUNCTION FIND_IN_SET(piv_str1 varchar2, piv_str2 varchar2, p_sep varchar2 := ',')
RETURN NUMBER IS
  l_idx    number:=0;
  str      varchar2(500);
  piv_str  varchar2(500) := piv_str2;
  res      number:=0;
  loopIndex number:=0;
BEGIN
	IF instr(piv_str, p_sep, 1) = 0 THEN
	   IF piv_str = piv_str1 THEN
	      res:= 1;
	   END IF;
	ELSE
		LOOP
			l_idx := instr(piv_str,p_sep);
			 loopIndex:=loopIndex+1;
			  IF l_idx > 0 THEN
				 str:= substr(piv_str,1,l_idx-1);
				 IF str = piv_str1 THEN
				   res:= loopIndex;
				   EXIT;
				 END IF;
				piv_str := substr(piv_str,l_idx+length(p_sep));
			  ELSE   
				IF piv_str = piv_str1 THEN
				   res:= loopIndex;
				END IF;
				EXIT;
			  END IF;
		END LOOP;
	END IF;
RETURN res;  
END FIND_IN_SET;

2.2 使用FIND_IN_SET()

查看aaa是否在aaa,bbb,ccc中

SELECT find_in_set('aaa','aaa,bbb,ccc') FROM dual;

返回1

查看bbb是否在aaa,bbb,ccc中

SELECT find_in_set('bbb','aaa,bbb,ccc') FROM dual;

返回2

查看ddd是否在aaa,bbb,ccc中

SELECT find_in_set('ddd','aaa,bbb,ccc') FROM dual;

返回0

2.3 刪除函數FIND_IN_SET()

DROP FUNCTION FIND_IN_SET;

3. 使用存儲過程輸入aaa,bbb,ccc,拆分打印出來

3.1 定義存儲過程

CREATE OR REPLACE PROCEDURE SPLIT_STR(STRLIST IN VARCHAR2)
 IS
  CURSOR CHECK_FLAG IS
    SELECT REGEXP_SUBSTR(STRLIST, '[^,]+', 1, LEVEL) F_VALUE
      FROM DUAL
    CONNECT BY LEVEL <=
               LENGTH(STRLIST) - LENGTH(REPLACE(STRLIST, ',')) + 1;
BEGIN
  FOR REC IN CHECK_FLAG LOOP
    DBMS_OUTPUT.PUT_LINE(REC.F_VALUE);
  END LOOP;
END SPLIT_STR;

3.2 使用塊執行存儲過程

DECLARE
BEGIN
  SPLIT_STR('aaa,bbb,ccc');
END;

執行結果:

3.3 刪除存儲過程

DROP PROCEDURE SPLIT_STR;

總結

到此這篇關於Oracle字符串拆分的文章就介紹到這瞭,更多相關Oracle字符串拆分內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: