Convert comma separated string to array in PL/SQL - oracle

How do I convert a comma separated string to a array?
I have the input '1,2,3' , and I need to convert it into an array.

here is another easier option
select to_number(column_value) as IDs from xmltable('1,2,3,4,5');

Oracle provides the builtin function DBMS_UTILITY.COMMA_TO_TABLE.
Unfortunately, this one doesn't work with numbers:
SQL> declare
2 l_input varchar2(4000) := '1,2,3';
3 l_count binary_integer;
4 l_array dbms_utility.lname_array;
5 begin
6 dbms_utility.comma_to_table
7 ( list => l_input
8 , tablen => l_count
9 , tab => l_array
10 );
11 dbms_output.put_line(l_count);
12 for i in 1 .. l_count
13 loop
14 dbms_output.put_line
15 ( 'Element ' || to_char(i) ||
16 ' of array contains: ' ||
17 l_array(i)
18 );
19 end loop;
20 end;
21 /
declare
*
ERROR at line 1:
ORA-00931: missing identifier
ORA-06512: at "SYS.DBMS_UTILITY", line 132
ORA-06512: at "SYS.DBMS_UTILITY", line 164
ORA-06512: at "SYS.DBMS_UTILITY", line 218
ORA-06512: at line 6
But with a little trick to prefix the elements with an 'x', it works:
SQL> declare
2 l_input varchar2(4000) := '1,2,3';
3 l_count binary_integer;
4 l_array dbms_utility.lname_array;
5 begin
6 dbms_utility.comma_to_table
7 ( list => regexp_replace(l_input,'(^|,)','\1x')
8 , tablen => l_count
9 , tab => l_array
10 );
11 dbms_output.put_line(l_count);
12 for i in 1 .. l_count
13 loop
14 dbms_output.put_line
15 ( 'Element ' || to_char(i) ||
16 ' of array contains: ' ||
17 substr(l_array(i),2)
18 );
19 end loop;
20 end;
21 /
3
Element 1 of array contains: 1
Element 2 of array contains: 2
Element 3 of array contains: 3
PL/SQL procedure successfully completed.
Regards,
Rob.

We can never run out of alternatives of doing the same thing differently, right?
I recently found this is pretty handy:
DECLARE
BAR VARCHAR2 (200) := '1,2,3';
BEGIN
FOR FOO IN ( SELECT REGEXP_SUBSTR (BAR,
'[^,]+',
1,
LEVEL)
TXT
FROM DUAL
CONNECT BY REGEXP_SUBSTR (BAR,
'[^,]+',
1,
LEVEL)
IS NOT NULL)
LOOP
DBMS_OUTPUT.PUT_LINE (FOO.TXT);
END LOOP;
END;
Outputs:
1
2
3

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:
/* 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.

Simple Code
create or replace function get_token(text_is varchar2, token_in number, delim_is varchar2 := ';') return varchar2 is
text_ls varchar2(2000);
spos_ln number;
epos _ln number;
begin
text_ls := delim_is || text_is || rpad(delim_is, token_in, delim_is);
spos_ln := instr(text_ls, delim_is, 1, token_in);
epos_ln := instr(text_ls, delim_is, 1, token_in+1);
return substr(text_ls, spos_ln+1, epos_ln-spos_ln-1);
end get_token;

Yes, it is very frustrating that dbms_utility.comma_to_table only supports comma delimieted lists and then only when elements in the list are valid PL/SQL identifies (so numbers cause an error).
I have created a generic parsing package that will do what you need (pasted below). It is part of my "demo.zip" file, a repository of over 2000 files that support my training materials, all available at PL/SQL Obsession: www.toadworld.com/SF.
Regards,
Steven Feuerstein
www.plsqlchallenge.com
(daily PL/SQL quiz)
CREATE OR REPLACE PACKAGE parse
/*
Generalized delimited string parsing package
Author: Steven Feuerstein, steven#stevenfeuerstein.com
Latest version always available on PL/SQL Obsession:
www.ToadWorld.com/SF
Click on "Trainings, Seminars and Presentations" and
then download the demo.zip file.
Modification History
Date Change
10-APR-2009 Add support for nested list variations
Notes:
* This package does not validate correct use of delimiters.
It assumes valid construction of lists.
* Import the Q##PARSE.qut file into an installation of
Quest Code Tester 1.8.3 or higher in order to run
the regression test for this package.
*/
IS
SUBTYPE maxvarchar2_t IS VARCHAR2 (32767);
/*
Each of the collection types below correspond to (are returned by)
one of the parse functions.
items_tt - a simple list of strings
nested_items_tt - a list of lists of strings
named_nested_items_tt - a list of named lists of strings
This last type also demonstrates the power and elegance of string-indexed
collections. The name of the list of elements is the index value for
the "outer" collection.
*/
TYPE items_tt IS TABLE OF maxvarchar2_t
INDEX BY PLS_INTEGER;
TYPE nested_items_tt IS TABLE OF items_tt
INDEX BY PLS_INTEGER;
TYPE named_nested_items_tt IS TABLE OF items_tt
INDEX BY maxvarchar2_t;
/*
Parse lists with a single delimiter.
Example: a,b,c,d
Here is an example of using this function:
DECLARE
l_list parse.items_tt;
BEGIN
l_list := parse.string_to_list ('a,b,c,d', ',');
END;
*/
FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
RETURN items_tt;
/*
Parse lists with nested delimiters.
Example: a,b,c,d|1,2,3|x,y,z
Here is an example of using this function:
DECLARE
l_list parse.nested_items_tt;
BEGIN
l_list := parse.string_to_list ('a,b,c,d|1,2,3,4', '|', ',');
END;
*/
FUNCTION string_to_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
RETURN nested_items_tt;
/*
Parse named lists with nested delimiters.
Example: letters:a,b,c,d|numbers:1,2,3|names:steven,george
Here is an example of using this function:
DECLARE
l_list parse.named_nested_items_tt;
BEGIN
l_list := parse.string_to_list ('letters:a,b,c,d|numbers:1,2,3,4', '|', ':', ',');
END;
*/
FUNCTION string_to_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, name_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
RETURN named_nested_items_tt;
PROCEDURE display_list (string_in IN VARCHAR2
, delim_in IN VARCHAR2:= ','
);
PROCEDURE display_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
);
PROCEDURE display_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, name_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
);
PROCEDURE show_variations;
/* Helper function for automated testing */
FUNCTION nested_eq (list1_in IN items_tt
, list2_in IN items_tt
, nulls_eq_in IN BOOLEAN
)
RETURN BOOLEAN;
END parse;
/
CREATE OR REPLACE PACKAGE BODY parse
IS
FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
RETURN items_tt
IS
c_end_of_list CONSTANT PLS_INTEGER := -99;
l_item maxvarchar2_t;
l_startloc PLS_INTEGER := 1;
items_out items_tt;
PROCEDURE add_item (item_in IN VARCHAR2)
IS
BEGIN
IF item_in = delim_in
THEN
/* We don't put delimiters into the collection. */
NULL;
ELSE
items_out (items_out.COUNT + 1) := item_in;
END IF;
END;
PROCEDURE get_next_item (string_in IN VARCHAR2
, start_location_io IN OUT PLS_INTEGER
, item_out OUT VARCHAR2
)
IS
l_loc PLS_INTEGER;
BEGIN
l_loc := INSTR (string_in, delim_in, start_location_io);
IF l_loc = start_location_io
THEN
/* A null item (two consecutive delimiters) */
item_out := NULL;
ELSIF l_loc = 0
THEN
/* We are at the last item in the list. */
item_out := SUBSTR (string_in, start_location_io);
ELSE
/* Extract the element between the two positions. */
item_out :=
SUBSTR (string_in
, start_location_io
, l_loc - start_location_io
);
END IF;
IF l_loc = 0
THEN
/* If the delimiter was not found, send back indication
that we are at the end of the list. */
start_location_io := c_end_of_list;
ELSE
/* Move the starting point for the INSTR search forward. */
start_location_io := l_loc + 1;
END IF;
END get_next_item;
BEGIN
IF string_in IS NULL OR delim_in IS NULL
THEN
/* Nothing to do except pass back the empty collection. */
NULL;
ELSE
LOOP
get_next_item (string_in, l_startloc, l_item);
add_item (l_item);
EXIT WHEN l_startloc = c_end_of_list;
END LOOP;
END IF;
RETURN items_out;
END string_to_list;
FUNCTION string_to_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
RETURN nested_items_tt
IS
l_elements items_tt;
l_return nested_items_tt;
BEGIN
/* Separate out the different lists. */
l_elements := string_to_list (string_in, outer_delim_in);
/* For each list, parse out the separate items
and add them to the end of the list of items
for that list. */
FOR indx IN 1 .. l_elements.COUNT
LOOP
l_return (l_return.COUNT + 1) :=
string_to_list (l_elements (indx), inner_delim_in);
END LOOP;
RETURN l_return;
END string_to_list;
FUNCTION string_to_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, name_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
RETURN named_nested_items_tt
IS
c_name_position constant pls_integer := 1;
c_items_position constant pls_integer := 2;
l_elements items_tt;
l_name_and_values items_tt;
l_return named_nested_items_tt;
BEGIN
/* Separate out the different lists. */
l_elements := string_to_list (string_in, outer_delim_in);
FOR indx IN 1 .. l_elements.COUNT
LOOP
/* Extract the name and the list of items that go with
the name. This collection always has just two elements:
index 1 - the name
index 2 - the list of values
*/
l_name_and_values :=
string_to_list (l_elements (indx), name_delim_in);
/*
Use the name as the index value for this list.
*/
l_return (l_name_and_values (c_name_position)) :=
string_to_list (l_name_and_values (c_items_position), inner_delim_in);
END LOOP;
RETURN l_return;
END string_to_list;
PROCEDURE display_list (string_in IN VARCHAR2
, delim_in IN VARCHAR2:= ','
)
IS
l_items items_tt;
BEGIN
DBMS_OUTPUT.put_line (
'Parse "' || string_in || '" using "' || delim_in || '"'
);
l_items := string_to_list (string_in, delim_in);
FOR indx IN 1 .. l_items.COUNT
LOOP
DBMS_OUTPUT.put_line ('> ' || indx || ' = ' || l_items (indx));
END LOOP;
END display_list;
PROCEDURE display_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
IS
l_items nested_items_tt;
BEGIN
DBMS_OUTPUT.put_line( 'Parse "'
|| string_in
|| '" using "'
|| outer_delim_in
|| '-'
|| inner_delim_in
|| '"');
l_items := string_to_list (string_in, outer_delim_in, inner_delim_in);
FOR outer_index IN 1 .. l_items.COUNT
LOOP
DBMS_OUTPUT.put_line( 'List '
|| outer_index
|| ' contains '
|| l_items (outer_index).COUNT
|| ' elements');
FOR inner_index IN 1 .. l_items (outer_index).COUNT
LOOP
DBMS_OUTPUT.put_line( '> Value '
|| inner_index
|| ' = '
|| l_items (outer_index) (inner_index));
END LOOP;
END LOOP;
END display_list;
PROCEDURE display_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, name_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
IS
l_items named_nested_items_tt;
l_index maxvarchar2_t;
BEGIN
DBMS_OUTPUT.put_line( 'Parse "'
|| string_in
|| '" using "'
|| outer_delim_in
|| '-'
|| name_delim_in
|| '-'
|| inner_delim_in
|| '"');
l_items :=
string_to_list (string_in
, outer_delim_in
, name_delim_in
, inner_delim_in
);
l_index := l_items.FIRST;
WHILE (l_index IS NOT NULL)
LOOP
DBMS_OUTPUT.put_line( 'List "'
|| l_index
|| '" contains '
|| l_items (l_index).COUNT
|| ' elements');
FOR inner_index IN 1 .. l_items (l_index).COUNT
LOOP
DBMS_OUTPUT.put_line( '> Value '
|| inner_index
|| ' = '
|| l_items (l_index) (inner_index));
END LOOP;
l_index := l_items.NEXT (l_index);
END LOOP;
END display_list;
PROCEDURE show_variations
IS
PROCEDURE show_header (title_in IN VARCHAR2)
IS
BEGIN
DBMS_OUTPUT.put_line (RPAD ('=', 60, '='));
DBMS_OUTPUT.put_line (title_in);
DBMS_OUTPUT.put_line (RPAD ('=', 60, '='));
END show_header;
BEGIN
show_header ('Single Delimiter Lists');
display_list ('a,b,c');
display_list ('a;b;c', ';');
display_list ('a,,b,c');
display_list (',,b,c,,');
show_header ('Nested Lists');
display_list ('a,b,c,d|1,2,3|x,y,z', '|', ',');
show_header ('Named, Nested Lists');
display_list ('letters:a,b,c,d|numbers:1,2,3|names:steven,george'
, '|'
, ':'
, ','
);
END;
FUNCTION nested_eq (list1_in IN items_tt
, list2_in IN items_tt
, nulls_eq_in IN BOOLEAN
)
RETURN BOOLEAN
IS
l_return BOOLEAN := list1_in.COUNT = list2_in.COUNT;
l_index PLS_INTEGER := 1;
BEGIN
WHILE (l_return AND l_index IS NOT NULL)
LOOP
l_return := list1_in (l_index) = list2_in (l_index);
l_index := list1_in.NEXT (l_index);
END LOOP;
RETURN l_return;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
RETURN FALSE;
END nested_eq;
END;
/

Using a pipelined table function:
SQL> CREATE OR REPLACE TYPE test_type
2 AS
3 TABLE OF VARCHAR2(100)
4 /
Type created.
SQL> CREATE OR REPLACE FUNCTION comma_to_table(
2 p_list IN VARCHAR2)
3 RETURN test_type PIPELINED
4 AS
5 l_string LONG := p_list || ',';
6 l_comma_index PLS_INTEGER;
7 l_index PLS_INTEGER := 1;
8 BEGIN
9 LOOP
10 l_comma_index := INSTR(l_string, ',', l_index);
11 EXIT
12 WHEN l_comma_index = 0;
13 PIPE ROW ( TRIM(SUBSTR(l_string, l_index, l_comma_index - l_index)));
14 l_index := l_comma_index + 1;
15 END LOOP;
16 RETURN;
17 END comma_to_table;
18 /
Function created.
Let's see the output:
SQL> SELECT *
2 FROM TABLE(comma_to_table('12 3,456,,,,,abc,def'))
3 /
COLUMN_VALUE
------------------------------------------------------------------------------
12 3
456
abc
def
8 rows selected.
SQL>

A quick search on my BBDD took me to a function called split:
create or replace function split
(
p_list varchar2,
p_del varchar2 := ','
)
return split_tbl pipelined
is
l_idx pls_integer;
l_list varchar2(32767) := p_list;AA
l_value varchar2(32767);
begin
loop
l_idx := instr(l_list,p_del);
if l_idx > 0 then
pipe row(substr(l_list,1,l_idx-1));
l_list := substr(l_list,l_idx+length(p_del));
else
pipe row(l_list);
exit;
end if;
end loop;
return;
end split;
I don't know if it'll be of use, but we found it here...

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.
declare
curr_val varchar2 (255 byte);
input_str varchar2 (255 byte);
remaining_str varchar2 (255 byte);
begin
remaining_str := input_str || ',dummy'; -- this value won't output
while (regexp_like (remaining_str, '.+,.+'))
loop
curr_val := substr (remaining_str, 1, instr (remaining_str, ',') - 1);
remaining_str = substr (remaining_str, instr (remaining_str, ',') + 1);
dbms_output.put_line (curr_val);
end loop;
end;
This is not an expert answer so I hope someone would improve this answer.

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 just want to write more clearly Richard and Mike's answers.
Method 1: VARRAY USAGE
DECLARE
TYPE v_array_type IS VARRAY (10) OF NUMBER;
var v_array_type;
begin
select to_number(column_value) BULK COLLECT into var from
xmltable('1,2,3,4,5,6,7,8,9,10');
for i in 1..var.count LOOP
dbms_output.put_line(var(i));
END LOOP;
end;
But in this method you must declare array size. If you want more dynamic method you could use Mike's method.
METHOD 2:
begin
FOR obj IN (SELECT TO_NUMBER(column_value) as ID FROM
xmltable('1,2,3,4,5,6,7,8,9,10,11')) LOOP
dbms_output.put_line(obj.ID);
END LOOP;
end;

you can use oracle method
declare
myarray apex_application_global.vc_arr2;
begin
myarray = apex_util.string_to_table('1,2,3', ',');//you can use any symbols instead of ',' for split
for i in 1..myarray.COUNT
loop
dbms_output.put_line(myarray(i));
end loop;

Another possibility is:
create or replace FUNCTION getNth (
input varchar2,
nth number
) RETURN varchar2 AS
nthVal varchar2(80);
BEGIN
with candidates (s,e,n) as (
select 1, instr(input,',',1), 1 from dual
union all
select e+1, instr(input,',',e+1), n+1
from candidates where e > 0)
select substr(input,s,case when e > 0 then e-s else length(input) end)
into nthVal
from candidates where n=nth;
return nthVal;
END getNth;
It's a little too expensive to run, as it computes the complete split every time the caller asks for one of the items in there...

The solution presented below by Stewart Ashton in this link is pretty handy.
He eliminates the need for the value list to be integer, so you can use string list.
In the WITH clause, he surrounds the values with single quotes then converts it to a table having a single column of type VARCHAR2.
https://stewashton.wordpress.com
with data as (
select '"'||replace(:txt, ',', '","')||'"' str from dual
)
select xmlcast(column_value as varchar2(4000)) subs
from data, xmltable(str);

declare
seprator varchar2(1):=',';
dosweeklist varchar2(4000):='a,b,c';
begin
for i in (SELECT SUBSTR(dosweeklist,
case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end,
NVL(NULLIF(INSTR(dosweeklist,seprator,1,LEVEL),0),length(dosweeklist)+1) - case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end) dat
FROM dual
CONNECT BY LEVEL <= LENGTH(dosweeklist) - LENGTH(REPLACE(dosweeklist,seprator,'')) +1)
loop
dbms_output.put_line(i.dat);
end loop;
end;
/
so select query only in for loop can do the trick, by replacing dosweeklist as your delimited string and seprator as your delimited character.
Lets see output
a
b
c

declare
v_str varchar2(100) := '1,2,3,4,6,7,8,9,0,';
v_str1 varchar2(100);
v_comma_pos number := 0;
v_start_pos number := 1;
begin
loop
v_comma_pos := instr(v_str,',',v_start_pos);
v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos));
dbms_output.put_line(v_str1);
if v_comma_pos = 0 then
v_str1 := substr(v_str,v_start_pos);
dbms_output.put_line(v_str1);
exit;
end if;
v_start_pos := v_comma_pos + 1;
if v_comma_pos = 0 then
exit;
end if;
end loop;
end;

You can use Replace Function to replace comma easily.
To Do this-
The syntax for the REPLACE function in SQL Server (Transact-SQL) is:
REPLACE( string, string_to_replace, replacement_string )
Parameters or Arguments
string : The source string from which a sequence of characters will be replaced by another set of characters.
string_to_replace : The string that will be searched for in string1.
replacement_string : The replacement string. All occurrences of string_to_replace will be replaced with replacement_string in string1.
Note :
The REPLACE function performs a replacement that is not
case-sensitive. So all occurrences of string_to_replace will be
replaced with replacement_string regardless of the case of
string_to_replace or replacement_string
For Example :
SELECT REPLACE('Kapil,raj,chouhan', ',' , ' ') from DUAL;
Result : Kapil raj chouhan
SELECT REPLACE('I Live In India', ' ' , '-') from DUAL;
Result : I-Live-In-India
SELECT REPLACE('facebook.com', 'face' , 'friends') from DUAL;
Result : friendsbook.com
I Hope it will be usefull for you.

Related

How do we split a CLOB (with some lines with more than 32K characters) line by line via PLSQL?

I am trying to split a huge CLOB which contains lines with more than 32K characters.
I tried to use this
SELECT REGEXP_SUBSTR(file_cont, '[^'||chr(10)||']+', 1, LEVEL) AS substr
from data_tab where interface = 'Historical'
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(file_cont, '[^'||chr(10)||']+')) + 1
The table data_tab contains some files with pipe as a separator.
The column file_cont is a clob which contains the file we are interested in.
However, when I try to execute the above query, it looks like there is an infinite loop.
For information, the CLOB contains more than 600 lines.
What I want to do is to split the clob, line by line into distinct CLOB.
Do you know a query that can display this result without falling into an infinite loop?
EDIT : The file's size is 22MB.
Thank you in advance.
I have a special package for split and PCRE regular expressions:
https://github.com/xtender/XT_REGEXP
You can find this function in https://github.com/xtender/XT_REGEXP/blob/master/xt_regexp.pck
/**
* Clob simple split
*/
function clob_split_simple(p_clob in clob,p_delim in varchar2)
return clob_table pipelined is
row clob;
l_b number:=1;
l_e number:=1;
$IF DBMS_DB_VERSION.ver_le_11 $THEN
$ELSE
pragma UDF;
$END
begin
while l_e>0
loop
l_e:=instr(p_clob,p_delim,l_b);
pipe row(substr(p_clob,l_b,case when l_e>0 then l_e-l_b else length(p_clob)+length(p_delim)-l_b end));
l_b:=l_e+length(p_delim);
end loop;
end clob_split_simple;
So you can either use this pipelined function:
select *
from table(xt_regexp.clob_split_simple(:clob,chr(10));
or take this code as an example.
clob_table is just a table of clob:
https://github.com/xtender/XT_REGEXP/blob/master/types.sql
create or replace type clob_table as table of clob;
/
create or replace type date_table as table of date;
/
create or replace type number_table as table of number;
/
create or replace type varchar2_table as table of varchar2(4000);
/
create or replace type xml_table as table of xmltype;
/
Update: fixed a bug with long matches: dbms_lob.substr which returns varchar2, replaced with substr(clob) which return clob.
You can use a PL/SQL function to read the and split the value:
If you have the data type:
CREATE TYPE clob_table AS TABLE OF CLOB;
Then the function:
CREATE FUNCTION split_clob(
p_value IN CLOB,
p_delimiter IN VARCHAR2 DEFAULT ','
) RETURN clob_table PIPELINED
IS
v_start PLS_INTEGER;
v_next PLS_INTEGER;
v_len PLS_INTEGER;
BEGIN
v_start := 1;
LOOP
v_next := DBMS_LOB.INSTR( p_value, p_delimiter, v_start );
v_len := CASE v_next WHEN 0 THEN LENGTH( p_value ) + 1 ELSE v_next END - v_start;
PIPE ROW ( SUBSTR( p_value, v_start, v_len ) );
EXIT WHEN v_next = 0;
v_start := v_next + LENGTH(p_delimiter);
END LOOP;
END;
/
For the sample data:
CREATE TABLE table_name ( value CLOB );
DECLARE
v_value TABLE_NAME.VALUE%TYPE := EMPTY_CLOB();
BEGIN
FOR ch IN 65 .. 68 LOOP
FOR i IN 1 .. 10 LOOP
v_value := v_value || RPAD( CHR(ch), 4000, CHR(ch) );
END LOOP;
IF ch < 68 THEN
v_value := v_value || CHR(10);
END IF;
END LOOP;
INSERT INTO table_name ( value ) VALUES ( v_value );
END;
/
Then the output of:
SELECT SUBSTR( s.column_value, 1, 10 ) AS value,
LENGTH( s.column_value ) AS len
FROM table_name t
CROSS APPLY TABLE( split_clob( t.value, CHR(10) ) ) s
Is:
VALUE
LEN
AAAAAAAAAA
40000
BBBBBBBBBB
40000
CCCCCCCCCC
40000
DDDDDDDDDD
40000
db<>fiddle here

Work with associative arrays INDEXED BY VARCHAR2 based on different record types where not all elements may not be present

I am trying to work with with parsed data and place into structures to work with.
I have found a Steve Feuersteins package that takes a string, and given seperator(s) will split it out into associative arrays and nested associative arrays.
With some tweaking I have fit it to some additional things I need. It is initally setup to index the AAs by PLS_INTEGER. In my case the values that I will be parsing will have identifiers for a given field and I thought it would be good to INDEX BY VARCHAR2 and use the field identifers. The downfall I see of indexing VARCHAR2 is that if I reference a index that does not exist, I get a NO_DATA_FOUND exception which I don't want.
The setup of the text string by SEPARATORS is:
GROUP/SEGMENT/FIELD/FIELD/FIELD/SEGMENT/FIELD/FIELD/FIELD/SEGMENT/FIELD/GROUP
So for a given segment there are a definitive potential fields but all may not be present so I cannot guarantee that all indexes that I would potentially try to access would be there.
So the current structure of the collection is:
SUBTYPE maxvarchar2_t IS VARCHAR2 (4000);
TYPE items_tt IS TABLE OF maxvarchar2_t
INDEX BY PLS_INTEGER;
TYPE nested_items_tt IS TABLE OF items_tt
INDEX BY PLS_INTEGER;
TYPE second_nested_items_tt IS TABLE OF nested_items_tt
INDEX BY PLS_INTEGER;
So in the example above
I would declare a second_nested_items_tt and it would be assigned:
1 to many GROUPs
each GROUP would have 1 to many SEGMENTs
each segment would have 1 to many FIELDs
Here is an example:
DECLARE
group_seperator CONSTANT VARCHAR2 (1) := CHR (29);
segment_seperator CONSTANT VARCHAR2 (1) := CHR (30);
field_seperator CONSTANT VARCHAR2 (1) := CHR (28);
loc_string VARCHAR2(4000);
-- field_id VARCHAR2(2);
idx VARCHAR2(2);
TYPE field_id_value_type IS TABLE OF VARCHAR2(100) INDEX BY VARCHAR2(2);
SUBTYPE maxvarchar2_t IS VARCHAR2 (4000);
fields field_id_value_type;
TYPE items_tt IS TABLE OF maxvarchar2_t
INDEX BY PLS_INTEGER;
TYPE nested_items_tt IS TABLE OF items_tt
INDEX BY PLS_INTEGER;
TYPE second_nested_items_tt IS TABLE OF nested_items_tt
INDEX BY PLS_INTEGER;
dataset second_nested_items_tt;
FUNCTION string_to_list (fields_in IN items_tt) --string_in IN VARCHAR2, delim_in IN VARCHAR2)
RETURN field_id_value_type
IS
fields_out_tbl field_id_value_type;
BEGIN
FOR i IN fields_in.FIRST .. fields_in.LAST LOOP
fields_out_tbl(substr(fields_in(i),1,2)) := SUBSTR(fields_in(i),3,LENGTH(fields_in(i)));
END LOOP;
RETURN fields_out_tbl;
END string_to_list;
FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
RETURN items_tt
IS
c_end_of_list CONSTANT PLS_INTEGER := -99;
l_item maxvarchar2_t;
l_startloc PLS_INTEGER := 1;
items_out items_tt;
PROCEDURE add_item (item_in IN VARCHAR2)
IS
BEGIN
IF item_in = delim_in
THEN
/* We don't put delimiters into the collection. */
NULL;
ELSE
items_out (items_out.COUNT + 1) := item_in;
END IF;
END;
PROCEDURE get_next_item (string_in IN VARCHAR2
, start_location_io IN OUT PLS_INTEGER
, item_out OUT VARCHAR2
)
IS
l_loc PLS_INTEGER;
BEGIN
l_loc := INSTR (string_in, delim_in, start_location_io);
IF l_loc = start_location_io
THEN
/* A null item (two consecutive delimiters) */
item_out := NULL;
ELSIF l_loc = 0
THEN
/* We are at the last item in the list. */
item_out := SUBSTR (string_in, start_location_io);
ELSE
/* Extract the element between the two positions. */
item_out :=
SUBSTR (string_in
, start_location_io
, l_loc - start_location_io
);
END IF;
IF l_loc = 0
THEN
/* If the delimiter was not found, send back indication
that we are at the end of the list. */
start_location_io := c_end_of_list;
ELSE
/* Move the starting point for the INSTR search forward. */
start_location_io := l_loc + 1;
END IF;
END get_next_item;
BEGIN
IF string_in IS NULL OR delim_in IS NULL
THEN
/* Nothing to do except pass back the empty collection. */
NULL;
ELSE
LOOP
get_next_item (string_in, l_startloc, l_item);
IF LENGTH(l_item) != 0 THEN
add_item (l_item);
END IF;
EXIT WHEN l_startloc = c_end_of_list;
END LOOP;
END IF;
RETURN items_out;
END string_to_list;
FUNCTION string_to_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
RETURN nested_items_tt
IS
l_elements items_tt;
l_return nested_items_tt;
BEGIN
/* Separate out the different lists. */
l_elements := string_to_list (string_in, outer_delim_in);
/* For each list, parse out the separate items
and add them to the end of the list of items
for that list. */
FOR indx IN 1 .. l_elements.COUNT
LOOP
l_return (l_return.COUNT + 1) :=
string_to_list (l_elements (indx), inner_delim_in);
END LOOP;
RETURN l_return;
END string_to_list;
FUNCTION string_to_list (string_in IN VARCHAR2
, outer_delim_in IN VARCHAR2
, mid_delim_in IN VARCHAR2
, inner_delim_in IN VARCHAR2
)
RETURN second_nested_items_tt
IS
l_elements items_tt;
l_return second_nested_items_tt;
BEGIN
/* Separate out the different lists. */
/* separated by group (claim) segments */
l_elements := string_to_list (string_in, outer_delim_in);
/* For each list, parse out the separate items
and add them to the end of the list of items
for that list. */
FOR indx IN 1 .. l_elements.COUNT
LOOP
l_return (l_return.COUNT + 1) :=
string_to_list (l_elements (indx), mid_delim_in, inner_delim_in);
END LOOP;
RETURN l_return;
END string_to_list;
BEGIN
loc_string :=
group_seperator
|| -- seg 1
segment_seperator
|| field_seperator
|| 'AB11'
|| field_seperator
|| 'AC1D'
|| field_seperator
|| 'AD2'
|| -- seg2
segment_seperator
|| field_seperator
|| 'AE03'
|| field_seperator
|| 'AF6'
|| -- seg3
segment_seperator
|| field_seperator
|| 'AG30'
|| field_seperator
|| 'AH00'
|| field_seperator
|| 'AIA'
|| field_seperator
|| 'DF1'
|| -- seg4
segment_seperator
|| field_seperator
|| '5T0'
|| field_seperator
|| '772'
|| field_seperator
|| 'RE2'
|| field_seperator
|| 'IU1'
|| -- record 2
group_seperator
|| segment_seperator
|| field_seperator
|| 'EW00'
|| field_seperator
|| 'JH1'
|| field_seperator
|| 'WQA'
|| -- seg2
segment_seperator
|| field_seperator
|| 'RE02'
|| field_seperator
|| 'LL99'
|| field_seperator
|| 'IIKT';
dataset := string_to_list (loc_string , group_seperator, segment_seperator, field_seperator);
DBMS_OUTPUT.put_line( 'List '
|| ' contains '
|| dataset.COUNT
|| ' elements');
FOR outer_index IN 1 .. dataset.COUNT
LOOP
-- DBMS_OUTPUT.put_line( 'List '
-- || outer_index
-- || ' = '
-- || dataset (outer_index) (1) (1) );
-- mid_items := string_to_list(dataset (outer_index), mid_delim_in);
FOR mid_index IN 1 .. dataset(outer_index).COUNT -- mid_items.COUNT
LOOP
FOR inner_index IN 1 ..dataset(outer_index) (mid_index).COUNT
LOOP
DBMS_OUTPUT.put_line('INNER Value is ' || dataset(outer_index) (mid_index) (inner_index));
END LOOP;
fields := string_to_list(dataset(outer_index) (mid_index));
idx := fields.FIRST;
-- DBMS_OUTPUT.PUT_LINE ('Segment: ' || get_description(idx, fields(idx)));
WHILE idx IS NOT NULL
LOOP
DBMS_OUTPUT.PUT_LINE ( idx || ' = ' || fields(idx) );
idx := fields.NEXT(idx);
END LOOP;
END LOOP;
END LOOP;
END;
This example is indexed by PLS_INTEGER except the last loop that uses the VARCHAR2 indexed type.
So is there a way to change these all to VARCHAR2 based indexing and not have to worry about accessing an element that doesn't exist without using the EXISTS function?
My inital thought was I could have a record type for the segments I know like:
segment employee is:
TYPE emp_rec IS RECORD(name VARCHAR2(30),
dob DATE,
position VARCHAR2(30));
but if I come to that segment, how can I determine what values are missing or there for that matter, based on the record above? I don't think this is possible since it is a PL defined record and I cannot gleam any metadata from it, at least to my knowledge.
Basically I am trying to figure out a way to make index by VARCHAR2 work instead of looping through via PLS_INTEGER

Dynamic typing or generics in Oracle PL/SQL

For some reason, I have certain fields in a table, that are collections of chars. Chars of different length. Example:
create or replace type t_charray_1 as varray(5) of char(1);
create or replace type t_charray_2 as varray(5) of char(2);
create or replace type t_charray_3 as varray(5) of char(3);
create or replace type t_charray_4 as varray(5) of char(4);
create table mytable (
field1 number,
field2 t_charray_1,
field3 t_charray_3,
Also, I have a function that returns a (fixed length) string representation of a mytable record. This function calls other functions that are returning the string representation of a given collection-typed field. Examples:
function to_chr(
p_array in t_charray_1,
pad_length in number,
p_list_length in number
) return char as
v_res varchar2(255) := '';
begin
for i in 1 .. p_list_length loop
if p_array is not null and p_array.exists(i) and p_array(i) is not null then
v_res := v_res || rpad(p_array(i), pad_length, ' ');
else
v_res := v_res || rpad(' ', pad_length, ' ');
end if;
end loop;
return v_res;
end to_chr;
------------------------------------------------------------------------------
function to_chr(
p_array in t_charray_2,
pad_length in number,
p_list_length in number
) return char as
v_res varchar2(255) := '';
begin
for i in 1 .. p_list_length loop
if p_array is not null and p_array.exists(i) and p_array(i) is not null then
v_res := v_res || rpad(p_array(i), pad_length, ' ');
else
v_res := v_res || rpad(' ', pad_length, ' ');
end if;
end loop;
return v_res;
end to_chr;
Note that these functions are overloaded versions of each other. The only difference in their signature is the type of the p_array argument.
Please also note that the bodies of these functions are identical.
Motivation
I want to eliminate duplicate code. What are my choices?
EDIT I have heard of sys.anydata but never used it. Can it be a solution?
You could write a procedure that takes the largest type, and explicitly CAST the smaller types to the larger type before passing them. Note that CAST can only be used in SQL
DECLARE
x t_charray_1 := t_charray_1();
y t_charray_2 := t_charray_2();
PROCEDURE foo( p_foo t_charray_2 )
AS
BEGIN
FOR i IN p_foo.FIRST..p_foo.LAST loop
dbms_output.put_line( p_foo(i) );
END LOOP;
END;
BEGIN
x.EXTEND;
x.EXTEND;
x(1) := 'A';
x(2) := 'B';
y.EXTEND;
y.EXTEND;
y(1) := 'AA';
y(2) := 'BB';
foo(y);
SELECT CAST(x AS t_charray_2) INTO y FROM dual;
foo(y);
END;
/
Try:
create or replace function to_chr(p_array in anydata,
pad_length in number,
p_list_length in number) return char as
v_res varchar2(255) := '';
x number;
v_array t_charray_4;
v_array1 t_charray_1;
v_array2 t_charray_2;
v_array3 t_charray_3;
begin
dbms_output.put_line(p_array.GetTypeName);
case p_array.GetTypeName
when '<schema>.T_CHARRAY_1' then
x := p_array.GetCollection(v_array1);
select cast(v_array1 as t_charray_4) into v_array from dual;
when '<schema>.T_CHARRAY_2' then
x := p_array.GetCollection(v_array2);
select cast(v_array2 as t_charray_4) into v_array from dual;
when '<schema>.T_CHARRAY_3' then
x := p_array.GetCollection(v_array3);
select cast(v_array3 as t_charray_4) into v_array from dual;
when '<schema>.T_CHARRAY_4' then
x := p_array.GetCollection(v_array);
end case;
for i in 1 .. p_list_length loop
if v_array is not null and v_array.exists(i) and v_array(i) is not null then
v_res := v_res || rpad(v_array(i), pad_length, ' ');
else
v_res := v_res || rpad(' ', pad_length, ' ');
end if;
end loop;
return v_res;
end to_chr;
you can run it like this:
declare
p_array anydata;
v_array t_charray_3 := new t_charray_3('aaa', 'bbb');
v_res varchar2(255);
begin
p_array := anydata.convertcollection(v_array);
v_res := to_chr(p_array => p_array, pad_length => 2, p_list_length => 3);
end;

Getting index of element in PL/SQL collection

Is there a built-in function to determine the (first) index of an element in a PL/SQL collection?
Something like
DECLARE
TYPE t_test IS TABLE OF VARCHAR2(1);
v_test t_test;
BEGIN
v_test := NEW t_test('A', 'B', 'A');
dbms_output.put_line( 'A: ' || get_index( v_test, 'A' ) );
dbms_output.put_line( 'B: ' || get_index( v_test, 'B' ) );
dbms_output.put_line( 'C: ' || get_index( v_test, 'C' ) );
END;
A: 1
B: 2
C:
I can use Associative Arrays, Nested Tables or Varrays, whatever necessary. If the same element exists more than once, then the index of the first occurrence is sufficient.
Otherwise I'd have to do something like
CREATE FUNCTION get_index ( in_test IN t_test, in_value IN VARCHAR2 )
RETURN PLS_INTEGER
AS
i PLS_INTEGER;
BEGIN
i := in_test.FIRST;
WHILE( i IS NOT NULL ) LOOP
IF( in_test(i) = in_value ) THEN
RETURN i;
END IF;
i := in_test.NEXT(i);
END LOOP;
RETURN NULL;
END get_index;
Not sure, if this really helps, or if you think it is more elegant:
create type t_test as table of varchar2(1);
/
DECLARE
--TYPE t_test IS TABLE OF VARCHAR2(1);
v_test t_test;
function get_index(q in t_test, c in varchar2) return number is
ind number;
begin
select min(rn) into ind from (
select column_value cv, rownum rn
from table(q)
)
where cv = c;
return ind;
end get_index;
BEGIN
v_test := NEW t_test('A', 'B', 'A');
dbms_output.put_line( 'A: ' || get_index( v_test, 'A' ) );
dbms_output.put_line( 'B: ' || get_index( v_test, 'B' ) );
dbms_output.put_line( 'C: ' || get_index( v_test, 'C' ) );
END;
/
show errors
drop type t_test;
I don't think there is a built-in function that searches a collection. However, if you know you will need to search a collection a lot, you could build an index. Adding element to the collection will be a bit more expensive, but looking for an element will be an O(1) operation (instead of O(n) for a brute force search). For example, you could use something like this:
SQL> DECLARE
2 TYPE t_test IS TABLE OF VARCHAR2(1);
3 TYPE t_test_r IS TABLE OF NUMBER INDEX BY VARCHAR2(1);
4
5 v_test t_test;
6 v_test_r t_test_r;
7
8 FUNCTION get_index(p_test_r t_test_r,
9 p_element VARCHAR2) RETURN NUMBER IS
10 BEGIN
11 RETURN p_test_r(p_element);
12 EXCEPTION
13 WHEN no_data_found THEN
14 RETURN NULL;
15 END get_index;
16
17 PROCEDURE add_element(p_test IN OUT t_test,
18 p_test_r IN OUT t_test_r,
19 p_element VARCHAR2) IS
20 BEGIN
21 p_test.extend;
22 p_test(p_test.count) := p_element;
23 p_test_r(p_element) := least(p_test.count,
24 nvl(get_index(p_test_r, p_element),
25 p_test.count));
26 END add_element;
27 BEGIN
28 v_test := NEW t_test();
29 add_element(v_test, v_test_r, 'A');
30 add_element(v_test, v_test_r, 'B');
31 add_element(v_test, v_test_r, 'A');
32 dbms_output.put_line('A: ' || get_index(v_test_r, 'A'));
33 dbms_output.put_line('B: ' || get_index(v_test_r, 'B'));
34 dbms_output.put_line('C: ' || get_index(v_test_r, 'C'));
35 END;
36 /
A: 1
B: 2
C:
PL/SQL procedure successfully completed
You could also define a record that contains both arrays and all functions/procedures to interact with arrays would use this record type.
When in doubt, consult the documentation ;) (here)
DECLARE
TYPE aa_type_int IS TABLE OF INTEGER INDEX BY PLS_INTEGER;
aa_int aa_type_int;
PROCEDURE print_first_and_last IS
BEGIN
DBMS_OUTPUT.PUT_LINE('FIRST = ' || aa_int.FIRST);
DBMS_OUTPUT.PUT_LINE('LAST = ' || aa_int.LAST);
END print_first_and_last;
BEGIN
aa_int(1) := 3;
aa_int(2) := 6;
aa_int(3) := 9;
aa_int(4) := 12;
DBMS_OUTPUT.PUT_LINE('Before deletions:');
print_first_and_last;
aa_int.DELETE(1);
aa_int.DELETE(4);
DBMS_OUTPUT.PUT_LINE('After deletions:');
print_first_and_last;
END;
/
Result:
Before deletions:
FIRST = 1
LAST = 4
After deletions:
FIRST = 2
LAST = 3

Concatenation of CLOB datatypes in a LOOP in PL/SQL

I am trying to concatenate clobs in a PL/SQL loop and it has been returning null whilst when using DBMS_OUTPUT prints out the loop values and when executing each result of the clobs gives an output as well.
The system is meant to execute an already stored SQL in a table based on the report name passed into it. This particular report has many report names; hence the concatenation of each of the reports. The arguments passed are the report name, version of the report you're interested in, the kind of separator you want, and an argument list for the unknowns in the SQL if any. There are also two main types of SQL; 1 that needs the table_name be replaced with a temp table_name and another that needs an ID be appended to a table_name in the SQL.
please find below the code for the REPREF1 function.
CREATE OR REPLACE FUNCTION REPREF1(P_VER IN VARCHAR2 DEFAULT 'LATEST',
P_SEPARATOR IN VARCHAR2 DEFAULT ', ',
P_ARGLIST IN VAR DEFAULT NULL) RETURN CLOB IS
L_CLOB CLOB;
FUNCTION GET_CLOB(P_REPNAM IN VARCHAR2,
P_VER IN VARCHAR2 DEFAULT 'LATEST',
P_SEPARATOR IN VARCHAR2 DEFAULT ', ',
P_ARGLIST IN VAR DEFAULT NULL) RETURN CLOB IS
---------------------------------------------------------------------------------
-- TITLE - GET_CLOB beta - b.0 DATE 2010Mar12
--
-- DESCRIPTION - A function that return a report based on the report name put in
--
-- USAGE - select get_clob(p_repnam,p_ver, p_separator, var(varay(val_1,...val_n), varay(val_1,...val_n))) FROM dual
-----------------------------------------------------------------------------------------------------------------------------
V_SQL VARCHAR2(32767);
L_RESULT CLOB;
V_TITLE VARCHAR2(4000);
V_REPDATE VARCHAR2(30);
V_CNT NUMBER(2);
V_NUMARG NUMBER(3);
V_CDCRU NUMBER(3);
V_BCNT NUMBER(3);
V_NEWTABDAT VARCHAR2(30);
V_NEWTABLIN VARCHAR2(30);
L_COLLIST VARAY;
V_VER VARCHAR2(6);
N PLS_INTEGER;
V_CNTTAB NUMBER(3);
-- EXEC_SQL_CLOB
FUNCTION EXEC_SQL_CLOB(P_SQL IN VARCHAR2,
P_NUMARG IN NUMBER,
P_COLLIST IN VARAY DEFAULT NULL,
P_ARGLIST IN VARAY DEFAULT NULL,
P_SEPARATOR IN VARCHAR2 DEFAULT '') RETURN CLOB IS
------------------------------------------------------------------------------------------------------
-- TITLE - EXEC_SQL_CLOB beta - b.0 DATE 2010Mar22
--
-- DESCRIPTION - A function that returns a clob value after executing the sql query that is passed into it
--
-- USAGE - select exec_sql_clob(p_sql, p_numarg, var(varay(val_1, val_2,...val_n), varay(val_1, val_2,...val_n))) FROM dual
---------------------------------------------------------------------------------------------------------------
L_CUR INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
L_STATUS INTEGER;
V_COL VARCHAR2(4000);
L_RESULT CLOB;
L_COLCNT NUMBER DEFAULT 0;
L_SEPARATOR VARCHAR2(10) DEFAULT '';
V_NUMARG NUMBER(3);
BEGIN
-- parse the query for the report
DBMS_SQL.PARSE(L_CUR, P_SQL, DBMS_SQL.NATIVE);
-- whilst it is not more than 255 per line
FOR I IN 1 .. 255
LOOP
BEGIN
-- define each column in the select list
DBMS_SQL.DEFINE_COLUMN(L_CUR, I, V_COL, 2000);
L_COLCNT := I;
EXCEPTION
WHEN OTHERS THEN
IF (SQLCODE = -1007) THEN
EXIT;
ELSE
RAISE;
END IF;
END;
END LOOP;
-- If query has no bind variables
IF (P_ARGLIST IS NULL) THEN
IF (P_NUMARG = 0) THEN
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
-- Query has bind variables
ELSE
-- Check if the numarg passed is the same has stored in the table
SELECT NUMARG
INTO V_NUMARG
FROM REPVER
WHERE REPCODE = P_SQL;
-- If number of arguments is greater than 0
IF (V_NUMARG > 0) THEN
-- Check if the number of arguments are the same
IF (P_NUMARG = V_NUMARG) THEN
-- Replace the bind variables in the query
FOR J IN 1 .. P_ARGLIST.COUNT
LOOP
DBMS_SQL.BIND_VARIABLE(L_CUR, P_COLLIST(J), P_ARGLIST(J));
END LOOP;
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
ELSE
-- If the number of argument is equal to 0
IF (P_NUMARG = 0) THEN
-- Execute the query in the cursor
L_STATUS := DBMS_SQL.EXECUTE(L_CUR);
LOOP
-- Exit loop when fetch is complete
EXIT WHEN(DBMS_SQL.FETCH_ROWS(L_CUR) <= 0);
L_SEPARATOR := '';
FOR I IN 1 .. L_COLCNT
LOOP
DBMS_SQL.COLUMN_VALUE(L_CUR, I, V_COL);
L_RESULT := L_RESULT || L_SEPARATOR || V_COL;
L_RESULT := REPLACE(REPLACE(L_RESULT, CHR(13) || CHR(10), ' '), CHR(10), ' ');
L_SEPARATOR := P_SEPARATOR;
END LOOP;
L_RESULT := L_RESULT || CHR(13);
END LOOP;
ELSE
RAISE_APPLICATION_ERROR(-20011, ' INCORRECT NUMBER OF ARGUMENTS PASSED IN LIST ');
END IF;
END IF;
END IF;
-- Close cursor
DBMS_SQL.CLOSE_CURSOR(L_CUR);
RETURN L_RESULT;
END EXEC_SQL_CLOB;
BEGIN
-- Check if the version entered is null or latest
IF (P_VER IS NULL)
OR (UPPER(P_VER) = UPPER('LATEST')) THEN
SELECT MAX(VER)
INTO V_VER
FROM REPORT B, REPVER R
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF;
ELSE
V_VER := P_VER;
END IF;
-- Check if the repname and version entered exists
SELECT COUNT(*)
INTO V_CNT
FROM REPORT B, REPVER R
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND VER = V_VER
AND B.REPREF = R.REPREF;
IF (V_CNT > 0) THEN
-- Store the SQL statement, title and number of arguments of the report name passed.
SELECT REPCODE, REPTITLE, NUMARG, COLLIST
INTO V_SQL, V_TITLE, V_NUMARG, L_COLLIST
FROM REPVER R, REPORT B
WHERE UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
V_REPDATE := TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI');
L_RESULT := V_TITLE || ' (' || P_REPNAM || ' version ' || V_VER || ') generated ' || V_REPDATE || CHR(13) || CHR(13);
-- Check for some specific type of queries
SELECT COUNT(*)
INTO V_CDCRU
FROM REPVER R, REPORT B
WHERE CTDDATA = 'Y'
AND UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
SELECT COUNT(*)
INTO V_BCNT
FROM REPVER R, BODCREPS B
WHERE BENLIST = 'Y'
AND UPPER(REPNAM) = UPPER(P_REPNAM)
AND B.REPREF = R.REPREF
AND VER = V_VER;
IF (V_CDCRU > 0) THEN
V_NEWTABDATA := 'CT_' || 'DAT_' || P_ARGLIST(1) (P_ARGLIST(1).FIRST);
V_NEWTABLINK := 'CT_' || 'LIN_' || P_ARGLIST(1) (P_ARGLIST(1).FIRST);
-- Check if the tables exist
SELECT COUNT(*)
INTO V_CNTTAB
FROM ALL_TABLES
WHERE TABLE_NAME = V_NEWTABDAT
OR TABLE_NAME = V_NEWTABLIN
AND OWNER = 'SCOTT';
IF (V_CNTTAB > 0) THEN
V_SQL := UPPER(V_SQL);
V_SQL := REPLACE(V_SQL, 'CT_DAT_CRU', V_NEWTABDAT);
V_SQL := REPLACE(V_SQL, 'CT_LIN_CRU', V_NEWTABLIN);
ELSE
V_SQL := 'SELECT ''THE TABLE NOT CREATED YET''
FROM DUAL';
END IF;
END IF;
IF (V_BCNT > 0) THEN
V_SQL := UPPER(V_SQL);
V_SQL := REPLACE(V_SQL, 'LIST', P_ARGLIST(1) (P_ARGLIST(1).LAST));
END IF;
IF (P_ARGLIST IS NULL) THEN
-- execute the query
L_RESULT := L_RESULT || EXEC_SQL_CLOB(V_SQL, V_NUMARG, L_COLLIST, NULL, P_SEPARATOR);
ELSE
N := P_ARGLIST.COUNT;
-- execute the query
L_RESULT := L_RESULT || EXEC_SQL_CLOB(V_SQL, V_NUMARG, L_COLLIST, P_ARGLIST(N), P_SEPARATOR);
END IF;
RETURN L_RESULT;
ELSE
RAISE_APPLICATION_ERROR(-20012, P_REPNAM || ' or ' || P_VER || ' DOES NOT EXIST ');
END IF;
END GET_CLOB;
BEGIN
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
SELECT CONCAT_CLOB(GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST))
INTO L_CLOB
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
-- DBMS_OUTPUT.PUT_LINE (COUNT(i.REPNAM));
END LOOP;
RETURN L_CLOB;
END REPREF1;
/
Cheers,
Tunde
Many thanks APC for making the code look better.
#Robert, the last loop in the code returns null even with the CONCAT_CLOB aggregate function that concatenates clobs.
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
SELECT CONCAT_CLOB(GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST))
INTO L_CLOB
FROM DUAL;
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
END LOOP;
when I try this,
FOR I IN (SELECT REPNAM
FROM REPORT
WHERE REPREF NOT IN ('R01', 'R02', 'R03', 'R04'))
LOOP
L_CLOB := L_CLOB || CHR(13) || GET_CLOB(I.REPNAM, P_VER, P_SEPARATOR, P_ARGLIST);
DBMS_OUTPUT.PUT_LINE(I.REPNAM);
END LOOP;
It also gives null; but this time the dbms output for the repnam are not complete.
Don't know about your code. Here is how it works for me:
Whenever I create a function returning a clob value I do this:
function foo return clob is
l_clob clob;
begin
dbms_lob.createtemporary(lob_loc => l_clob, cache => true, dur => dbms_lob.call);
...
return l_clob;
end;
When concatenating values into a clob I use a function:
procedure add_string_to_clob(p_lob in out nocopy clob
,p_string varchar2) is
begin
dbms_lob.writeappend(lob_loc => p_lob, amount => length(p_string), buffer => p_string);
end;
You have to use
dbms_lob.substr(your clob parameter,start position, length)
e.g
dbms_output('my clob value:' || dbms_lob.substr(your clob parameter,start position, length);
But you can print in a string max 4000 character, you can then use this in a looping function to print 4000 characters in each line.

Resources