ORACLE PL-SQL 如何使用函数拆分字符串和 RETURN 列表

ORACLE PL-SQL How to SPLIT a string and RETURN the list using a Function

如何为给定的分隔符拆分给定的字符串。

例如:

输入

字符串 => '1,2,3,4,5' 分隔符 => ','

输出

1 2个 3个 4个 5

我找到了自己的方法来使用 FUNCTION

拆分给定的字符串

一个TYPE应该声明如下:

TYPE tabsplit IS TABLE OF VARCHAR2 (50)
                     INDEX BY BINARY_INTEGER;

FUNCTION应该这样写:

FUNCTION fn_split (mp_string IN VARCHAR2, mp_delimiter IN VARCHAR2)
    RETURN tabsplit
IS
    ml_point     NUMBER (5, 0) := 1;
    ml_sub_str   VARCHAR2 (50);
    i            NUMBER (5, 0) := 1;
    taboutput    tabsplit;
    ml_count     NUMBER (5, 0) := 0;
BEGIN
    WHILE i <= LENGTH (mp_string)
    LOOP
        FOR j IN i .. LENGTH (mp_string)
        LOOP
            IF SUBSTR (mp_string, j, 1) = mp_delimiter
            THEN
                ml_sub_str := SUBSTR (mp_string, ml_point, j - ml_point);
                ml_point := j + 1;
                i := ml_point;
                i := i - 1;
                taboutput (ml_count) := ml_sub_str;
                ml_count := ml_count + 1;
                EXIT;
            END IF;
        END LOOP;

        i := i + 1;
    END LOOP;

    ml_sub_str := SUBSTR (mp_string, ml_point, LENGTH (mp_string));
    taboutput (ml_count) := ml_sub_str;

    RETURN taboutput;
END fn_split;

这个FUNCTION可以如下使用:

DECLARE
    taboutput   tabsplit;
BEGIN
    taboutput := fn_split ('1,2,3,4,5', ',');

    FOR i IN 0 .. taboutput.COUNT - 1
    LOOP
        DBMS_OUTPUT.put_line (taboutput (i));
    END LOOP;
END;

这个呢?正则表达式允许空列表元素。

SQL> with tbl(str) as (
  2    select '1,2,,4,5' from dual
  3  )
  4  select regexp_substr(str, '(.*?)(,|$)', 1, level, null, 1) element
  5  from tbl
  6  connect by level <= regexp_count(str, ',')+1;

ELEMENT
--------
1
2

4
5

SQL>

请参阅此 post 以了解 returns 列表元素的函数:REGEX to select nth value from a list, allowing for nulls

SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
   FROM dual
CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;