I was looking for a similar solution where I had multi-byte characters (hyphen, whitespace, underscore) in comma separated lists. So dbms_utility.comma_to_table didn't work for me.
I particularly like this one, which converts the delimited list into a temporary table you can run queries against:
/* Create the output TYPE, here using a VARCHAR2(100) nested table type */
SQL> CREATE TYPE test_type AS TABLE OF VARCHAR2(100);
2 /
Type created.
/* Now, create the function.*/
SQL> CREATE OR REPLACE FUNCTION f_convert(p_list IN VARCHAR2)
2 RETURN test_type
3 AS
4 l_string VARCHAR2(32767) := p_list || ',';
5 l_comma_index PLS_INTEGER;
6 l_index PLS_INTEGER := 1;
7 l_tab test_type := test_type();
8 BEGIN
9 LOOP
10 l_comma_index := INSTR(l_string, ',', l_index);
11 EXIT WHEN l_comma_index = 0;
12 l_tab.EXTEND;
13 l_tab(l_tab.COUNT) := SUBSTR(l_string, l_index, l_comma_index - l_index);
14 l_index := l_comma_index + 1;
15 END LOOP;
16 RETURN l_tab;
17 END f_convert;
18 /
Function created.
/* Prove it works */
SQL> SELECT * FROM TABLE(f_convert('AAA,BBB,CCC,D'));
COLUMN_VALUE
--------------------------------------------------------------------------------
AAA
BBB
CCC
D
4 rows selected.
TYPE string_aa IS TABLE OF VARCHAR2(32767) INDEX BY PLS_INTEGER;
FUNCTION string_to_list(p_string_in IN VARCHAR2)
RETURN string_aa
IS
TYPE ref_cursor IS ref cursor;
l_cur ref_cursor;
l_strlist string_aa;
l_x PLS_INTEGER;
BEGIN
IF p_string_in IS NOT NULL THEN
OPEN l_cur FOR
SELECT regexp_substr(p_string_in,'[^,]+', 1, level) FROM dual
CONNECT BY regexp_substr(p_string_in, '[^,]+', 1, level) IS NOT NULL;
l_x := 1;
LOOP
FETCH l_cur INTO l_strlist(l_x);
EXIT WHEN l_cur%notfound;
-- excludes NULL items e.g. 1,2,,,,5,6,7
l_x := l_x + 1;
END LOOP;
END IF;
RETURN l_strlist;
END string_to_list;
I was looking for a similar solution where I had multi-byte characters (hyphen, whitespace, underscore) in comma separated lists. So
dbms_utility.comma_to_table
didn't work for me.This is not an expert answer so I hope someone would improve this answer.
I know Stack Overflow frowns on pasting URLs without explanations, but this particular page has a few really good options:
http://www.oratechinfo.co.uk/delimited_lists_to_collections.html
I particularly like this one, which converts the delimited list into a temporary table you can run queries against:
Oracle provides the builtin function DBMS_UTILITY.COMMA_TO_TABLE.
Unfortunately, this one doesn't work with numbers:
But with a little trick to prefix the elements with an 'x', it works:
Regards, Rob.
Simple Code