oracle之字符串拆分

 

在工作当中发现oracle没有提供字符串切割函数,在网上找到一个比好的切割方式,记录一下:

1.新建数据类型

CREATE OR REPLACE TYPE STR_SPLIT AS TABLE OF VARCHAR2(500);

2.新建切割函数

CREATE OR REPLACE FUNCTION SPLITSTR(P_STRING
  IN VARCHAR2, 

 P_DELIMITER IN VARCHAR2) 

 RETURN STR_SPLIT 

 PIPELINED IS 

 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; 

3.进行测试

select * from table(splitstr('Hello,Cnblogs!',',')); 

4.将行转为列显示

SELECT A.COLUMN_VALUE V1, B.COLUMN_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
 WHERE A.RN = 1
   AND B.RN = 2;

待补充测试结果

posted @ 2018-08-11 19:46  王洁  阅读(554)  评论(0编辑  收藏  举报