1. 程式人生 > >Oracle擷取字串函式function

Oracle擷取字串函式function

1.

CREATE OR REPLACE FUNCTION split (p_list CLOB, p_sep VARCHAR2 := ',')
RETURN tabletype
PIPELINED
/**************************************
* Name: split
* Author: Zyj.
* Date: 2016-12-03.
* Function: 返回字串被指定字元分割後的表型別。
* Parameters: p_list: 待分割的字串。
p_sep: 分隔符,預設逗號,也可以指定字元或字串。
* Example: SELECT *
FROM
users WHERE u_id IN (SELECT COLUMN_VALUE FROM table (split ('1,2'))) 返回u_id為12的兩行資料。 **************************************/ IS l_idx PLS_INTEGER; v_list VARCHAR2 (4000) := p_list; BEGIN LOOP l_idx := INSTR (v_list, p_sep); IF l_idx > 0 THEN PIPE ROW (SUBSTR (v_list, 1, l_idx - 1)); v_list := SUBSTR (v_list, l_idx + LENGTH (p_sep)); ELSE
PIPE ROW (v_list); EXIT; END IF; END LOOP; END;

2.

CREATE OR REPLACE TYPE "TABLETYPE" as table of VARCHAR2(4000);

3.

create or replace function splitStr(str in clob,
                                    i  in number := 0,
                                    sep in varchar2 := ',') return varchar2 is
t_i number; t_count number; t_str varchar2(4000); begin if i = 0 then t_str := str; elsif instr(str, sep) = 0 then t_str := sep; else select count(*) into t_count from table(split(str, sep)); if i <= t_count then select str into t_str from (select rownum as item, column_value as str from table(split(str, sep))) where item = i; end if; end if; return t_str; end /** @author ZYJ 2016-06-12 擷取字串 ex:splitStr('2016-05',1,'-') return 2016; */;