Home  >  Article  >  php教程  >  Detailed explanation of Oracle custom split function examples

Detailed explanation of Oracle custom split function examples

高洛峰
高洛峰Original
2017-01-06 13:03:431635browse

Oracle custom split function

Oracle does not provide a split function, but you can create a function yourself to achieve this function. For example, "abc defg hijkl nmopqr stuvw xyz", the separator is a space, but the number of spaces is variable.

Source code:

CREATE OR REPLACE TYPE ty_str_split IS TABLE OF VARCHAR2 (4000);
 
CREATE OR REPLACE FUNCTION fn_var_split (
  p_str IN VARCHAR2,
  p_delimiter IN VARCHAR2
)
  RETURN ty_str_split
IS
  j INT := 0;
  len INT := 0;
  str VARCHAR2 (4000);
  str_split ty_str_split := ty_str_split ();
  v_str VARCHAR2 (4000) := RTRIM (LTRIM (p_str, p_delimiter), p_delimiter);
BEGIN
  len := LENGTH (v_str);
 
  WHILE len > 0
  LOOP
    j := INSTR (v_str, p_delimiter, 1);
 
    IF j = 0
    THEN
      str := SUBSTR (v_str, 1);
      len := 0;
      str_split.EXTEND;
      str_split (str_split.COUNT) := str;
    ELSE
      str := SUBSTR (v_str, 1, j - 1);
      v_str := LTRIM (LTRIM (v_str, str), p_delimiter);
      len := LENGTH (v_str);
      str_split.EXTEND;
      str_split (str_split.COUNT) := str;
    END IF;
  END LOOP;
 
  RETURN str_split;
END fn_var_split;
/

Test:
Result:

1
12
123
1234
12345
DECLARE
  CURSOR c
  IS
    SELECT * FROM TABLE (CAST (fn_var_split (';1;12;;123;;;1234;;;;12345;', ';') AS ty_str_split));
  r c%ROWTYPE;
BEGIN
  OPEN c;
  LOOP
    FETCH c INTO r;
    EXIT WHEN c%NOTFOUND;
    DBMS_OUTPUT.put_line (r.column_value);
  END LOOP;
  CLOSE c;
END;
/

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more Oracle custom split function examples and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn