Cannot insert Third column of data - oracle

I am noob in PL/SQL I just start learning and I want to create small peace of software that insert data from .CVS file to Oracle database.
And I stuck in part where I grab data from .CVS file.
I my CVS there are three column: Number_Policy,Contact, Agency
Number_Policy,Contact is catch success, but Agency can not be catched and I dont know why
declare
import_file text_io.file_type;
export_file text_io.file_type;
import_file_name varchar2(1000);
export_file_name varchar2(1000);
import_log_file text_io.file_type;
import_log_file_name varchar2(1000);
vec_importovano number;
brojac number;
brojac_redova number;
linebuf varchar2(10000);
p_rbr varchar2(20);
p_polica varchar2(20);
p_banka VARCHAR2(50);
p_kontakt varchar2(20);
kraj_fajla number;
begin
brojac_redova:=0;
import_file_name := :Global.Lokacija_prenosa||:import.naziv_fajla||:Global.Ekstenzija_prenosa;
import_file := text_io.fopen(import_file_name,'r');
delete from zivot_trajni_nalog_ponude where banka is not null;
commit;
kraj_fajla := 0;
while kraj_fajla = 0 loop
begin
brojac_redova:=brojac_redova+1;
text_io.get_line(import_file, linebuf);
if brojac_redova >= 2 then
p_polica:=substr(linebuf, 1, instr(linebuf,';',1,1)-1);
-- message(p_polica);
p_kontakt:=substr(linebuf, instr(linebuf,';',1,1)+1, instr(linebuf,';',1,2) - instr(linebuf,';',1,1)-1);
p_banka:=substr(linebuf, instr(linebuf,';',1,2)+1, instr(linebuf,';',1,3) - instr(linebuf,';',1,2)-1);
-- message(p_banka);
--p_kontakt:=substr(linebuf, instr(linebuf,';',1,1)+1, instr(linebuf,';',1,2) - instr(linebuf,';',1,1)-1);
-- message(p_kontakt);
/*
p_rbr:=substr(linebuf, 1, instr(linebuf,';',1,1)-1);
-- message(p_rbr);
p_polica:=substr(linebuf, instr(linebuf,';',1,1)+1, instr(linebuf,';',1,2) - instr(linebuf,';',1,1)-1);
-- message(p_polica);
p_banka:=substr(linebuf, instr(linebuf,';',1,2)+1, instr(linebuf,';',1,3) - instr(linebuf,';',1,2)-1);
message(p_banka);
p_kontakt:=substr(linebuf, instr(linebuf,';',1,3)+1, instr(linebuf,';',1,4) - instr(linebuf,';',1,3)-1);
message(p_kontakt);
*/
if vec_importovano = 0 then
insert into ZIVOT_TRAJNI_NALOG_PONUDE
(BROJ_POLICE,BROJ_PONUDE)
values(
p_polica,
--p_rbr,
p_kontakt);
-- p_banka);
commit;
end if;
end if;
EXCEPTION WHEN NO_DATA_FOUND THEN kraj_fajla := 1;
end;
end loop;
IF p_polica IS NOT NULL
THEN
update zivot_trajni_nalog_ponude set BROJ_POLICE=rownum;
commit;
END IF;
text_io.fclose(import_file);
message ('Uspjesno zavrseno');
end;
As you can see from code there is error somewhere here
p_banka:=substr(linebuf, instr(linebuf,';',1,2)+1, instr(linebuf,';',1,3) - instr(linebuf,';',1,2)-1);
-- message(p_banka);
After I disable this column the problem is that column p_polica and p_kontakt can't be inserted into database.
If anyone know where I made mistake I would be very thankful for any help.

Looks like linebuf has only two semicolons. This piece of code worked in my short test:
if instr(linebuf,';',1,3) > 0 then
p_banka := substr(linebuf,
instr(linebuf,';',1, 2) + 1,
instr(linebuf,';',1,3) - instr(linebuf,';',1,2)-1);
else
p_banka := substr(linebuf,
instr(linebuf,';',1, 2) + 1);
end if;

Related

Unable to get dbms_sql.column_value

I'm trying to read a query from a table and process it with DBMS_SQL package. It parses correctly. I can also see the columns, which occurs in a query. But I'm not able to fetch results. In debug mode It throws the exception while trying to getting dbms_sql.column_value (please see the code below).
/*--------------------------------------------------------------------------------------------------------------------*/
PROCEDURE MY_PROC( nCSV_EXP_CFG_ID IN NUMBER,nN1 IN NUMBER DEFAULT null )
/*--------------------------------------------------------------------------------------------------------------------*/
as
l_ntt_desc_tab dbms_sql.desc_tab;
nCursorId INTEGER;
nColCnt INTEGER;
nRowCnt INTEGER;
rCSV_EXP_CFG CSV_EXP_CFG%ROWTYPE;
TYPE rowArray IS VARRAY(20) OF VARCHAR2(255);
colVal rowArray;
BEGIN
SELECT * INTO rCSV_EXP_CFG
FROM CSV_EXP_CFG
WHERE
CSV_EXP_CFG_ID = nCSV_EXP_CFG_ID;
nCursorId:=dbms_sql.open_cursor;
dbms_sql.parse(nCursorId, rCSV_EXP_CFG.EXPORT_TABLE, dbms_sql.native);
IF nN1 IS NOT NULL THEN DBMS_SQL.BIND_VARIABLE (nCursorId, 'n1', nN1); END IF;
dbms_sql.describe_columns(nCursorId, nColCnt, l_ntt_desc_tab);
FOR i IN 1..nColCnt LOOP
DBMS_OUTPUT.PUT_LINE( l_ntt_desc_tab(i).col_name);
--DBMS_SQL.DEFINE_COLUMN(nCursorId, i, colVal(i), 255);
END LOOP;
nRowCnt:=dbms_sql.execute(nCursorId);
LOOP
EXIT WHEN dbms_sql.fetch_rows(nCursorId) = 0;
FOR i IN 1..nColCnt LOOP
--here I'm getting the exception
dbms_sql.column_value(nCursorId, i, colVal(i));
END LOOP;
END LOOP;
Dbms_sql.close_cursor(nCursorId);
EXCEPTION WHEN OTHERS THEN
NULL;
END MY_PROC;
What am I doing wrong?

How to open direct CSV file using TEXT_IO in oracle forms?

I applied this code in oracle forms 10g on trigger WHEN-BUTTON-PRESSED. This code only save the file on target location.
CODE:
PROCEDURE GEN_EXCEL IS
IN_FILE TEXT_IO.FILE_TYPE;
VC_HEAD Varchar2(32000);
vc_file_path Varchar2(50) := 'C:\';
BEGIN
IN_FILE := TEXT_IO.FOPEN(vc_file_path||'Test'||'.CSV','W');
TEXT_IO.PUT_LINE(IN_FILE,'YOUR_TITLE'||chr(10));
VC_HEAD := 'header1,header2,header3,header4';
TEXT_IO.PUT_LINE(IN_FILE,VC_HEAD);
FOR C1 IN ( SELECT column1, column2, column3, column4
FROM Table_name)
LOOP
TEXT_IO.PUT_LINE(IN_FILE,C1.col1||','||C1.col2||','||C1.col3||','||C1.col4);
END LOOP;
TEXT_IO.FCLOSE(IN_FILE);
MESSAGE('Excel file has been created!');
MESSAGE('Excel file has been created!');
EXCEPTION
WHEN Others THEN
TEXT_IO.FCLOSE(IN_FILE);
MESSAGE('Error while writing file.');
MESSAGE('Error while writing file.');
END;
I want when-button-pressed then direct open CSV file from oracle forms
How to achieve this target?
You can use webutil to do this.
It has a function client_host.
Also instead of duplicating your messages you can put pause after the first message. Then you don't need the second message for a popup of the message.
If you want to read-in your .csv file I've found a suitable solution for my problem.
Maybe it helps you too if I did understand it right what you want.
Reading From File
March 19, 2009
--------------------------------------------------
Declare
vfilename varchar2(500);
in_file Client_Text_IO.File_Type;
linebuf VARCHAR2(1800);
BEGIN
vfilename := client_get_file_name('c:/temp/', File_Filter=>'Comma Dialimeted Files (*.csv)|*.csv|');
in_file := client_Text_IO.Fopen(vfilename, 'r');
GO_BLOCK('Emp');
FIRST_RECORD;
LOOP
Client_Text_IO.Get_Line(in_file, linebuf);
p_output_line(linebuf);
Client_Text_IO.New_Line;
Next_record;
END LOOP;
FIRST_RECORD;
EXCEPTION
WHEN no_data_found THEN
Client_Text_IO.Put_Line('Closing the file...');
Client_Text_IO.Fclose(in_file);
END;
-------------------------------------------------------
PROCEDURE p_output_line(p_line varchar2) IS
vLINE VARCHAR2(4000);
vVALUE VARCHAR2(1000);
vCOMMA_COUNT NUMBER;
vREPORT_DATE DATE;
BEGIN
vLINE := p_line;
vCOMMA_COUNT := LENGTH(vLINE)- LENGTH(REPLACE(vLINE,',','')); -- COUNT THE NUMBER OF COMMAS
FOR I IN 1.. vCOMMA_COUNT+1 LOOP
vVALUE := SUBSTR(vLINE,1,INSTR(vLINE,',')-1); -- IF vLINE = 123,ABC,9877 THEN VVALUE WILL BE 123
IF vVALUE IS NULL THEN
vVALUE := vLINE;
END IF;
vLINE := SUBSTR(vLINE,INSTR(vLINE,',')+1) ; -- CHANGE 123,ABC,9877 TO BE ABC,9877
IF I = 1 THEN
:DATA.BMK_NAME := vVALUE;
ELSIF I = 2 THEN
vREPORT_DATE := last_day(to_date(vVALUE,'dd-mm-yyyy'));
:DATA.REPORT_DATE := vREPORT_DATE;
ELSIF I = 3 THEN
:DATA.BMK_RETURN := to_number(vVALUE);
END IF;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
MESSAGE('Please Check the data type is appropriate on you excel file');
MESSAGE('Please Check the data type is appropriate on you excel file');
END;
-----------------------------------------------------------------------
-- notes
1- you must install webutil version 106 or later
2- make sure that you attached and compiled the webutill.pll scucessfuly

How to populate TABLE OF RECORDS with rows of 2 levels parent-child

I have a table with rows describing a tree, columns are:
(column child_num is unique and used as primary key)
TABLE items_tree (
child_num number,
parent_ref varchar2(10),
child_ref varchar2(10)
);
TYPE item_rec_type IS RECORD (
item_id NUMBER,
spaces_number NUMBER,
parent_ref VARCHAR2(10),
child_ref VARCHAR2(10)
);
TYPE tree_table_type IS TABLE OF item_rec_type%ROWTYPE
INDEX BY BINARY_INTEGER;
table_tree tree_table_type; -- table of all items
Example data for table items_tree (values of child_num are not relevant):
parent_ref child_ref
---------------------------
null Abraham
Abraham Isaac
Abraham Ishmael
Isaac Jakob
Jakob Yehuda
Jakob Josef
Jakob Benjamin
Yehuda David
Josef Efraim
Josef Menashe
David Solomon
Solomon Isaiah
Isaiah Jeremiah
I need to populate table_tree records from items_tree table. To do so, I am using a package, the item_rec_type, tree_table_type, table_tree are defined in it and two procedures: print_tree which retrieves the ROOT items of the tree, starts the process and prints the tree from table_tree. Second procedure get_items_by_parent_recursively is recursive procedure that retrieves all the items or a parent item, e.g. calling get_items_by_parent_recursively('Abraham') will add Isaac and Ishmael to table_tree.
The cursor is declared in the package body:
CURSOR get_children_cur(c_parent in varchar2(10))
IS
SELECT parent_ref, child_ref
FROM items_tree
WHERE parent_ref = c_parent
ORDER BY 1, 2;
The code in get_items_by_parent_recursively that retrieves the items for the parent:
procedure get_items_by_parent_recursively(p_parent in VARCHAR2(10), p_spaces_number in NUMBER )
AS
l_spaces_number NUMBER := 0;
l_child VHARCHAR2(10);
l_parent VHARCHAR2(10);
BEGIN
l_spaces_number := p_spaces_number + 3;
OPEN get_children_cur(p_parent);
LOOP
FETCH get_children_cur INTO l_parent, l_child;
EXIT WHEN get_children_cur%NOTFOUND;
IF (l_child is not null) THEN
v_row_number := v_row_number + 1;
tree_table(v_row_number).row_num := v_row_number;
tree_table(v_row_number).spaces_number := l_spaces_number;
tree_table(v_row_number).parent_ref := l_parent;
tree_table(v_row_number).child_ref := l_child;
-- Calling procedure recursively
get_items_by_parent_recursively( l_child, l_spaces_number );
END IF;
END LOOP;
CLOSE get_children_cur;
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
DBMS_OUTPUT.put_line(' Exception -- CURSOR_ALREADY_OPEN');
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.put_line(' Exception -- INVALID_CURSOR');
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.put_line(' Exception -- INVALID_NUMBER');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.put_line(' Exception -- NO_DATA_FOUND');
WHEN PROGRAM_ERROR THEN
DBMS_OUTPUT.put_line(' Exception -- PROGRAM_ERROR');
WHEN ROWTYPE_MISMATCH THEN
DBMS_OUTPUT.put_line(' Exception -- ROWTYPE_MISMATCH');
WHEN STORAGE_ERROR THEN
DBMS_OUTPUT.put_line(' Exception -- STORAGE_ERROR');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.put_line(' Exception -- TOO_MANY_ROWS');
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.put_line(' Exception -- VALUE_ERROR');
END get_items_by_parent_recursively;
Running this procedure I am getting the exception: CURSOR_ALREADY_OPEN.
I have searched for a reply, but none came close to what I need. I will appreciate any ideas.
I will try to make the cursor get_children_cur part of the recursive procedure.
As #vmachan said, you need to move the cursor definition into the procedure. While you have it in the package specification or body, but outside the procedure, there is one instance of it which is global to the session. Each call to your procedure attempts to open the same cursor; the initial call from print_tree succeeds, and your table is populated with 'Abraham'; but then the recursive call tries to re-open it and gets the CURSOR_ALREADY_OPEN exception, and stops.
Moving the cursor into the procedure means each call/iteration has its own independent copy. Cleaning up naming and various other issues, this then works:
procedure get_items_by_parent(p_parent in VARCHAR2, p_spaces_number in NUMBER)
AS
l_spaces_number NUMBER := 0;
l_child VARCHAR2(10);
l_parent VARCHAR2(10);
CURSOR get_children_cur(p_parent in varchar2) IS
SELECT parent_item, child_item
from items_tree
where parent_item = p_parent
or (p_parent is null and parent_item is null);
BEGIN
l_spaces_number := p_spaces_number + 3;
OPEN get_children_cur(p_parent);
LOOP
FETCH get_children_cur INTO l_parent, l_child;
EXIT WHEN get_children_cur%NOTFOUND;
IF (l_child is not null) THEN
v_row_number := v_row_number + 1;
table_tree(v_row_number).item_id := v_row_number;
table_tree(v_row_number).spaces_number := l_spaces_number;
table_tree(v_row_number).parent_item_ref := l_parent;
table_tree(v_row_number).item_ref := l_child;
-- Calling procedure recursively
get_items_by_parent( l_child, l_spaces_number );
END IF;
END LOOP;
CLOSE get_children_cur;
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
DBMS_OUTPUT.put_line(' Exception -- CURSOR_ALREADY_OPEN');
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.put_line(' Exception -- INVALID_CURSOR');
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.put_line(' Exception -- INVALID_NUMBER');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.put_line(' Exception -- NO_DATA_FOUND');
WHEN PROGRAM_ERROR THEN
DBMS_OUTPUT.put_line(' Exception -- PROGRAM_ERROR');
WHEN ROWTYPE_MISMATCH THEN
DBMS_OUTPUT.put_line(' Exception -- ROWTYPE_MISMATCH');
WHEN STORAGE_ERROR THEN
DBMS_OUTPUT.put_line(' Exception -- STORAGE_ERROR');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.put_line(' Exception -- TOO_MANY_ROWS');
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.put_line(' Exception -- VALUE_ERROR');
END get_items_by_parent;
Inventing a print_tree based on what you describe:
procedure print_tree is
begin
get_items_by_parent(null, 0);
for i in 1..table_tree.count loop
dbms_output.put_line(to_char(table_tree(i).item_id, '99999') || ' '
|| lpad(' ', table_tree(i).spaces_number, ' ')
|| table_tree(i).item_ref);
end loop;
end print_tree;
... calling that now works, and produces 13 indented records:
1 Abraham
2 Isaac
3 Jakob
4 Yehuda
5 David
6 Solomon
7 Isaiah
8 Jeremiah
9 Josef
10 Efraim
11 Menashe
12 Benjamin
13 Ishmael
As #XING said, you can get the same result more simply with a different for of cursor loop:
procedure get_items_by_parent(p_parent in VARCHAR2, p_spaces_number in NUMBER)
AS
l_spaces_number NUMBER := 0;
CURSOR get_children_cur(p_parent in varchar2) IS
SELECT parent_item, child_item
from items_tree
where child_item is not null
and (parent_item = p_parent
or (p_parent is null and parent_item is null));
BEGIN
l_spaces_number := p_spaces_number + 3;
FOR r IN get_children_cur(p_parent)
LOOP
v_row_number := v_row_number + 1;
table_tree(v_row_number).item_id := v_row_number;
table_tree(v_row_number).spaces_number := l_spaces_number;
table_tree(v_row_number).parent_item_ref := r.parent_item;
table_tree(v_row_number).item_ref := r.child_item;
-- Calling procedure recursively
get_items_by_parent( r.child_item, l_spaces_number );
END LOOP;
END get_items_by_parent;
or even:
procedure get_items_by_parent(p_parent in VARCHAR2, p_spaces_number in NUMBER)
AS
BEGIN
FOR r IN (
SELECT parent_item, child_item
from items_tree
where child_item is not null
and (parent_item = p_parent
or (p_parent is null and parent_item is null)))
LOOP
v_row_number := v_row_number + 1;
table_tree(v_row_number).item_id := v_row_number;
table_tree(v_row_number).spaces_number := p_spaces_number + 3;
table_tree(v_row_number).parent_item_ref := r.parent_item;
table_tree(v_row_number).item_ref := r.child_item;
-- Calling procedure recursively
get_items_by_parent( r.child_item, p_spaces_number + 3 );
END LOOP;
END get_items_by_parent;
Of course, you don't need to use PL/SQL or a table at all, you can use a hierarchical query:
select rownum, lpad(' ', level * 3, ' ') || child_item as item
from items_tree
start with parent_item is null
connect by parent_item = prior child_item
order siblings by child_num;
ROWNUM ITEM
---------- --------------------------------------------------
1 Abraham
2 Isaac
3 Jakob
4 Yehuda
5 David
6 Solomon
7 Isaiah
8 Jeremiah
9 Josef
10 Efraim
11 Menashe
12 Benjamin
13 Ishmael
but presumably this is a PL/SQL exercise. If you aren't required to use a recursive procedure you could still populate your table from a similar query, using bulk collect.

How to get the values of an OBJECT or ROWTYPE dynamically (Reflection) in Oracle PL/SQL?

I am trying to take a ROWTYPE, RECORD, or OBJECT type and dynamically convert it to a single string representation.
I want to do this dynamically.
Update: Doing this for an OBJECT type now working thanks to Justin Cave's feedback.
Example Data:
ID | VAL
---------
1 | BOB
Desired Output:
ID=1, VAL=BOB
Error Received:
ORA-06550: line 7, column 25:
PLS-00306: wrong number or types of arguments in call to 'TO_STRING'
ORA-06550: line 7, column 4:
PL/SQL: Statement ignored
What I have so Far (Doesn't loop through columns yet.):
CREATE OR REPLACE FUNCTION to_string (
ip_anydata in out anydata --note the "out" - this is required for the "piecewise"
)
RETURN VARCHAR2
IS
lv_typecode PLS_INTEGER;
lv_anytype anytype;
BEGIN
DBMS_OUTPUT.PUT_LINE('[Expected='||dbms_types.typecode_object||', Actual='||ip_anydata.getType(lv_anytype)||']');
--Get the typecode, and the ANYTYPE
lv_typecode := ip_anydata.getType(lv_anytype);
--Check that it's really an object
IF lv_typecode = dbms_types.typecode_object
THEN
--If it is an object, find the first item
DECLARE
lv_first_attribute_typecode pls_integer;
lv_aname varchar2(32767);
lv_result pls_integer;
lv_varchar varchar2(32767);
--Variables we don't really care about, but need for function output
lv_prec pls_integer;
lv_scale pls_integer;
lv_len pls_integer;
lv_csid pls_integer;
lv_csfrm pls_integer;
lv_attr_elt_type anytype;
BEGIN
lv_first_attribute_typecode := lv_anytype.getAttrElemInfo(
pos => 1, --First attribute
prec => lv_prec,
scale => lv_scale,
len => lv_len,
csid => lv_csid,
csfrm => lv_csfrm,
attr_elt_type => lv_attr_elt_type,
aname => lv_aname
);
--Check typecode of attribute
IF lv_first_attribute_typecode = dbms_types.typecode_varchar2
THEN
--Now that we've verified the type, get the actual value.
ip_anydata.piecewise;
lv_result := ip_anydata.getVarchar2(c => lv_varchar);
--DEBUG: Print the attribute name, in case you're curious
--dbms_output.put_line('lv_aname: '||lv_aname);
RETURN lv_aname||'='||lv_varchar;
ELSE
raise_application_error(-20000, 'Unexpected 1st Attribute Typecode: '||lv_first_attribute_typecode);
END IF;
END;
ELSE
raise_application_error(-20000, 'Unexpected Typecode: '||lv_typecode);
END IF;
END;
/
Scenario#1 - Select INTO w/ ROWTYPE:
DECLARE
lv_cv dual%ROWTYPE;
lv_str VARCHAR2(32767);
BEGIN
DBMS_OUTPUT.PUT_LINE('-----------------------------');
SELECT * INTO lv_cv FROM dual WHERE ROWNUM <= 1;
DBMS_OUTPUT.PUT_LINE(to_string(lv_cv));
END;
/
Scenario#2 - FETCH INTO w/ Cursor ROWTYPE:
DECLARE
CURSOR cv_cur IS SELECT * FROM dual WHERE ROWNUM <= 1;
lv_cv cv_cur%ROWTYPE;
lv_str VARCHAR2(32767);
BEGIN
DBMS_OUTPUT.PUT_LINE('-----------------------------');
OPEN cv_cur;
FETCH cv_cur INTO lv_cv;
CLOSE cv_cur;
DBMS_OUTPUT.PUT_LINE(to_string(lv_cv));
END;
/
Scenario#3 - Regular OBJECT: (Updated)
DECLARE
lv_cv T_CODE_VAL_REC := T_CODE_VAL_REC('BOB', 5);
lv_str VARCHAR2(32767);
lv_any ANYDATA;
BEGIN
DBMS_OUTPUT.PUT_LINE('-----------------------------');
lv_any := sys.anydata.ConvertObject(lv_cv);
DBMS_OUTPUT.PUT_LINE(to_string(lv_any));
EXCEPTION WHEN OTHERS THEN
pts2_test_valitation_util.fail(999, CHR(10)||CHR(10)||'Unexpected Error:'||CHR(10)||SQLERRM||CHR(10)||DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
END;
/

How to loop through a delimited list in Oracle PLSQL

I am working on an Oracle procedure that calls another procedure within it. One of my parameters (parm1) can contain one or more values in a comma separated list. How can I loop through these values to pass them one at a time to another procedure?
Here is an example of what I would like it to do:
When Parm1 = 123,312
callProcedure2(123)
callProcedure2(321)
-or-
When Parm1 123
callProcedure2(123)
I think this can be accomplished using a loop but I can't figure out how to get it to use each value as a separated call within the loop.
Any help would be appreciated!
Thanks!
CURSOR V_CUR IS
select regexp_substr(Parm1 ,'[^,]+', 1, level) As str from dual
connect by regexp_substr(Parm1, '[^,]+', 1, level) is not null;
This curor will give you result like this
123
321
Now iterate the cursor and call the procedure in loop.
For i IN V_CUR
LOOP
callProdcedure2(i.str);
END LOOP;
Just loop through substrings:
declare
parm1 varchar2(1000) := '123,234,345,456,567,789,890';
vStartIdx binary_integer;
vEndIdx binary_integer;
vCurValue varchar2(1000);
begin
vStartIdx := 0;
vEndIdx := instr(parm1, ',');
while(vEndIdx > 0) loop
vCurValue := substr(parm1, vStartIdx+1, vEndIdx - vStartIdx - 1);
-- call proc here
dbms_output.put_line('->'||vCurValue||'<-');
vStartIdx := vEndIdx;
vEndIdx := instr(parm1, ',', vStartIdx + 1);
end loop;
-- Call proc here for last part (or in case of single element)
vCurValue := substr(parm1, vStartIdx+1);
dbms_output.put_line('->'||vCurValue||'<-');
end;
There is a utility procedure COMMA_TO_TABLE and array type DBMS_UTILITY.UNCL_ARRAY dedicated for this task. Since Oracle 10g.
It is well document here.
Here is a sample solution:
SET SERVEROUTPUT ON
DECLARE
csvListElm VARCHAR2(4000) := 'elm1, elm2,elm3 ,elm4 , elm5';
csvListTable DBMS_UTILITY.UNCL_ARRAY;
csvListLen BINARY_INTEGER;
currTableName VARCHAR2(222);
BEGIN
DBMS_UTILITY.COMMA_TO_TABLE(csvListElm, csvListLen, csvListTable);
FOR csvElm IN 1..(csvListTable.COUNT - 1) LOOP
dbms_output.put_line('-- CSV element : <'||csvListTable(csvElm)||'>');
dbms_output.put_line('-- Trimmed CSV element: <'||trim(csvListTable(csvElm))||'>');
END LOOP;
END;
/
Sample output:
-- CSV element : <elm1>;
-- Trimmed CSV element: <elm1>;
-- CSV element : < elm2>;
-- Trimmed CSV element: <elm2>;
-- CSV element : <elm3 >;
-- Trimmed CSV element: <elm3>;
-- CSV element : <elm4 >;
-- Trimmed CSV element: <elm4>;
-- CSV element : < elm5>;
-- Trimmed CSV element: <elm5>;
It is possible to use a function that you can use in a for loop (without regexp for ThinkJet):
Create a type and function
CREATE OR REPLACE TYPE t_my_list AS TABLE OF VARCHAR2(100);
CREATE OR REPLACE
FUNCTION cto_table(p_sep in Varchar2, p_list IN VARCHAR2)
RETURN t_my_list
AS
l_string VARCHAR2(32767) := p_list || p_sep;
l_sep_index PLS_INTEGER;
l_index PLS_INTEGER := 1;
l_tab t_my_list := t_my_list();
BEGIN
LOOP
l_sep_index := INSTR(l_string, p_sep, l_index);
EXIT
WHEN l_sep_index = 0;
l_tab.EXTEND;
l_tab(l_tab.COUNT) := TRIM(SUBSTR(l_string,l_index,l_sep_index - l_index));
l_index := l_sep_index + 1;
END LOOP;
RETURN l_tab;
END cto_table;
/
Then how to call it in the for loop:
DECLARE
parm1 varchar2(4000) := '123,234,345,456,567,789,890';
BEGIN
FOR x IN (select * from (table(cto_table(',', parm1)) ) )
LOOP
dbms_output.put_line('callProdcedure2 called with ' || x.COLUMN_VALUE);
callProdcedure2(x.COLUMN_VALUE);
END LOOP;
END;
/
Notice the default name COLUMN_VALUE given by Oracle, which is necessary for the use I want to make of the result.
Result as expected:
callProdcedure2 called with 123
callProdcedure2 called with 234
...

Resources