Keshan Fernando
Keshan Fernando

Reputation: 367

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

How to Split the given String for the given Delimiter.

Ex:

INPUT

String => '1,2,3,4,5' Delimiter => ','

OUTPUT

1 2 3 4 5

Upvotes: 0

Views: 31043

Answers (3)

Madhuka Dilhan
Madhuka Dilhan

Reputation: 1416

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;

Upvotes: 1

Gary_W
Gary_W

Reputation: 10360

What about this? The regular expression allows for null list elements too.

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>

See this post for a function that returns a list element: REGEX to select nth value from a list, allowing for nulls

Upvotes: 7

Keshan Fernando
Keshan Fernando

Reputation: 367

I have found my own way to split the given String using a FUNCTION

A TYPE should be declared as belows:

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

And the FUNCTION should be written like this:

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;

This FUNCTION can be used as belows:

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;

Upvotes: 5

Related Questions