PL/SQL error reference to uninitialised collection error even when its initialised - oracle

I have a PL/SQL script which used nested table. Below is the sample code.
type rec is record
(
--col data types here
)
type rec_table is table of rec;
v_rec_table rec_table := rec_table(); --initialising here.
arr_size integer := 0; --edit 1
...
...
begin
...
...
open cursor;
loop
fetch cursor bulk collect into v_rec_table limit arr_size; --edit
if nvl(v_rec_table.last,0) > 0 --it shows error is here.
then
...
...
end if;
The error is ORA-06531: Reference to uninitialized collection. Please help me debug this one.

If would help if you posted complete (sample) code (instead of "...").
Here's an example based on Scott's schema which works OK (your error line is line 14):
SQL> declare
2 type rec is record (id number);
3 type rec_table is table of rec;
4 v_rec_table rec_table := rec_table();
5
6 cursor c1 is select empno from emp;
7 begin
8 open c1;
9 loop
10 exit when c1%notfound;
11 fetch c1 bulk collect into v_rec_table;
12 end loop;
13 dbms_output.put_line('last = ' || v_rec_table.last);
14 if nvl(v_rec_table.last, 0) > 0 then
15 dbms_output.put_line('last exists');
16 end if;
17 close c1;
18 end;
19 /
last = 12
last exists
PL/SQL procedure successfully completed.
Though, I'm not sure what's that LOOP used for, as you could have done it as
SQL> declare
2 type rec is record (id number);
3 type rec_table is table of rec;
4 v_rec_table rec_table := rec_table();
5 begin
6 select empno bulk collect into v_rec_table from emp;
7 dbms_output.put_line('last = ' || v_rec_table.last);
8 end;
9 /
last = 12
PL/SQL procedure successfully completed.

Although your problem is not reproducible, there are few things I found could be improved in your code.
If you are using a bulk collect, the collection is initialised automatically and hence, this line is not required
v_rec_table rec_table := rec_table();
Also, as #Littlefoot mentioned, LOOP is not required unless you are using the LIMIT clause.
You may use the COUNT collection function instead of nvl(v_rec_table.last,0)
v_rec_table.count
Instead of defining a record type and bulk collecting into it, you may define a collection of cursor%ROWTYPE;
CURSOR cur is SELECT column1,column2 FROM tablename;
type rec_table is table of cur%ROWTYPE;
v_rec_table rec_table;

Apologies since i did not post whole code. The error occurred because i did not add index by to two columns in the record definition.
After reading through few articles i found my flaw.

Related

why this simple programm creates an end-of-file on communicatoin channel error

CREATE OR REPLACE TYPE a IS OBJECT
(
b integer,
c varchar2(10)
);
/
declare
cursor ca return a is select 1,'e' from dual;
va a;
begin
null;
for cur in ca
loop
DBMS_OUTPUT.PUT_LINE('do nothing');
end loop;
end;
ORA-03113: end-of-file on communication channel
Process ID: 803778
Session ID: 64 Serial number: 4181
the loop as only one element and fast nothing is done in the loop.
But I get the error end-of-file communication channel
As #littlefoot said it works fine if I use a record defined in a package or no record at all. I don't know why it doesn't work with an object
code
Simply put, you can't do that.
Oracle does not support returning object types from a cursor. Cursors *always* return a rowtype. So to do something similar to what you want, you can define a table which has a column of the object type you're interested in, and then have the cursor return the rowtype of that table - i.e. something like:
CREATE OR REPLACE TYPE a IS OBJECT
(
b integer,
c varchar2(10)
);
CREATE TABLE tt
(t_a a);
INSERT INTO tt VALUES (a(1, 'e'));
declare
cursor ca return tt%ROWTYPE is select t_a from tt;
an_a a;
begin
FOR aRow IN ca LOOP
an_a := aRow.t_a;
dbms_output.put_line('an_a.b=' || an_a.b);
dbms_output.put_line('an_a.c=''' || an_a.c || '''');
end loop;
end;
db<>fiddle here
You never said what a is.
Documentation says that - if you use return clause, then it returns rowtype.
RETURN: Specifies the datatype of a cursor return value. You can use the %ROWTYPE attribute in the RETURN clause to provide a record type that represents a row in a database table or a row returned by a previously declared cursor. Also, you can use the %TYPE attribute to provide the datatype of a previously declared record.
A cursor body must have a SELECT statement and the same RETURN clause as its corresponding cursor spec. Also, the number, order, and datatypes of select items in the SELECT clause must match the RETURN clause.
ROWTYPE: A record type that represents a row in a database table or a row fetched from a previously declared cursor or cursor variable. Fields in the record and corresponding columns in the row have the same names and datatypes.
So, if your code were like this, it would work:
SQL> set serveroutput on
SQL>
SQL> declare
2 type a is record(val1 number, val2 varchar2(10));
3
4 cursor ca return a is select 1 ,'e' from dual;
5 va a;
6 begin
7 for cur in ca
8 loop
9 DBMS_OUTPUT.PUT_LINE(cur.val1 ||', '|| cur.val2 ||', do nothing');
10 end loop;
11 end;
12 /
1, e, do nothing
PL/SQL procedure successfully completed.
SQL>
Or, simpler, if you remove the return clause from your own code, it would also work:
SQL> declare
2 cursor ca --return a
3 is select 1,'e' from dual;
4 va a;
5 begin
6 null;
7 for cur in ca
8 loop
9 DBMS_OUTPUT.PUT_LINE('do nothing');
10 end loop;
11 end;
12 /
do nothing
PL/SQL procedure successfully completed.
SQL>
If you're asking what's the reason of end-of-file on communication channel, I wouldn't know.

For loop not printing last record in a cursor

So,I am working with a cursor,the cursor was initially operating with the initial for loop,now i needed to perform operation if the no of records in the cursor is more than one,so i fetched the no of records first and stored in a variable and used an if-condition based on that.Now the problem is when I run the whole process,the procedure does its job,but only for the first record in the cursor and entirely skips the second record.Please suggest or help me identify the mistake.
Adding code snippet.
for m in get_m_p(a,b)--main cursor
loop
fetch get_m_p into c_m;
exit when g_m_p%notfound;
end loop;
tempcount := g_m_p%ROWCOUNT:
statements---
if(tempcount>1) then
statements----
end if;
end loop;
for the two records the main curosr is returning in first line,operations are only done for the first one,and the second record is being skipped entirely.
This is a superfluous line:
fetch get_m_p into c_m;
You don't explicitly fetch within a cursor FOR loop, it is implicitly done in each loop iteration. Remove that line.
How to get number of rows returned by a cursor? Lucky you, it seems that you don't care whether how many rows - exactly - it returns. All you want to know is whether it returned more than 1 row. So, count them, literally; exit the loop if counter exceeds 1.
SQL> DECLARE
2 CURSOR get_m_p IS
3 SELECT *
4 FROM emp
5 WHERE deptno = 10;
6
7 l_cnt NUMBER := 0;
8 BEGIN
9 FOR m IN get_m_p
10 LOOP
11 l_cnt := l_cnt + 1;
12 EXIT WHEN l_cnt > 1;
13 END LOOP;
14
15 DBMS_OUTPUT.put_line ('Cursor returned at least ' || l_cnt || ' row(s)');
16
17 IF l_cnt > 1
18 THEN
19 NULL;
20 -- the rest of statements go here
21 END IF;
22 END;
23 /
Cursor returned at least 2 row(s)
PL/SQL procedure successfully completed.
SQL>
As there's no way to know how many rows will cursor return, unfortunately, you'll have to check that first, and then decide what to do with the result.
DECLARE
CURSOR get_m_p IS
SELECT *
FROM emp
WHERE deptno = 10;
l_cnt NUMBER := 0;
BEGIN
SELECT COUNT (*)
INTO l_cnt
FROM (-- this is cursor's SELECT statement
SELECT *
FROM emp
WHERE deptno = 10);
FOR m IN get_m_p
LOOP
-- some statements here
IF l_cnt > 1
THEN
NULL;
-- statements to be executed if cursor return more than 1 row
END IF;
END LOOP;
END;
/
Cursor:
Oracle creates memory area to process SQL statement which is called context area and the cursor is pointer to the context area. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.
There are two type of cursor
1. Implicit cursor
2. Explicit cursor
Implicit Cursors :
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed. Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example. Use the SQL%ROWCOUNT attribute to determine the number of rows affected
DECLARE
no_of_records number(2);
BEGIN
select * from records;
IF sql%notfound THEN
dbms_output.put_line('no records present');
ELSIF sql%found THEN
no_of_records := sql%rowcount;
IF no_of_records > 1 THEN
dbms_output.put_line('no of records ' || no_of_records);
END IF
END IF;
END;
Explicit Cursors :
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
Please see below example:
DECLARE
r_id records.id%type;
CURSOR c_records is
SELECT id FROM records;
BEGIN
OPEN c_records;
LOOP
FETCH c_records into r_id;
EXIT WHEN c_records%notfound;
dbms_output.put_line('Record id ' || r_id );
END LOOP;
CLOSE c_records;
END;
Reference :
https://www.tutorialspoint.com/plsql/plsql_cursors.htm
As an alternative you can cache every row and process after.
Example using sample schema "HR" on Oracle 11g Express Edition:
DECLARE
CURSOR get_m_p
IS
SELECT *
FROM hr.employees
WHERE department_id = 60
order by employee_id;
--
rcEmp_last get_m_p%rowtype;
l_cnt NUMBER;
BEGIN
FOR rcM IN get_m_p LOOP
l_cnt := get_m_p%rowcount;
Dbms_Output.Put_Line('l_cnt='||l_cnt);
if l_cnt=1 then
rcEmp_last:=rcM;
Else
Dbms_Output.Put_Line('Process='||to_char(l_cnt-1));
Dbms_Output.Put_Line('rcEmp_last.employee_id='||rcEmp_last.employee_id);
--
rcEmp_last:=rcM;
END IF;
End loop;
--
Dbms_Output.Put_Line('Exited FOR-LOOP');
Dbms_Output.Put_Line('l_cnt='||l_cnt);
--
if l_cnt>1 then
Dbms_Output.Put_Line('rcEmp_last.employee_id='||rcEmp_last.employee_id);
End if;
END;
Output:
Text
PL/SQL block, executed in 1 ms
l_cnt=1
l_cnt=2
Process=1
rcEmp_last.employee_id=103
l_cnt=3
Process=2
rcEmp_last.employee_id=104
l_cnt=4
Process=3
rcEmp_last.employee_id=105
l_cnt=5
Process=4
rcEmp_last.employee_id=106
Exited FOR-LOOP
l_cnt=5
rcEmp_last.employee_id=107
Total execution time 35 ms

PL/SQL Record populate

I have a record as following and I want to populate this with a for loop.
declare
type ch_type is table of record(id number, name varchar2(50));
type ch_type_tab is table of ch_type;
rec_typr ch_type_tab;
begin
for i in (select * from emp) loop
rec_typr.id := i.emp_id;
rec_typr.name := i.first_name;
end loop;
for i in rec_typr.first..rec_typr.last
loop
dbms_output.put_line(rec_typr(i).id);
end loop;
end;
but I get the error:
PLS:0302 component first must be declared.
Can you help me with this?
Two things are problematic in your code.
1) type ch_type is table of record is syntactically incorrect. You must first declare a record and then define its collection type.
2) Using implicit cursor loop is not an efficient method to load a collection and definitely can't be done the way you're trying to do. Use much simpler BULK COLLECT method instead.
declare
type ch_type is record(id number, name varchar2(50));
type ch_type_tab is table of ch_type;
rec_typr ch_type_tab;
begin
select emp_id,first_name bulk collect into
rec_typr from emp;
for i in rec_typr.first..rec_typr.last
loop
dbms_output.put_line(rec_typr(i).id);
end loop;
end;
/
Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
PL/SQL procedure successfully completed.
EDIT
I need to populate the record through a loop not through bulk collect.
Is it any way?
Yes, there is. But, it is less efficient than the method described above.
declare
type ch_type is record(id number, name varchar2(50));
type ch_type_tab is table of ch_type;
rec_typr ch_type_tab := ch_type_tab();
i INTEGER := 1;
begin
rec_typr.extend;
for rec in
(
select emp_id,first_name bulk collect into
rec_typr from emp
)
loop
rec_typr(i).id := rec.emp_id;
rec_typr(i).name := rec.first_name;
rec_typr.extend;
i := i + 1;
end loop;
for i in rec_typr.first..rec_typr.last
loop
dbms_output.put_line(rec_typr(i).id);
end loop;
end;
/

Using cursor with where in condition

I am passing arguments `EBN,BGE' into a procedure , then I am passing this argument to a cursor.
create or replace procedure TEXT_MD (AS_IDS VARCHAR2)
is
CURSOR C_A (AS_ID VARCHAR2) IS
SELECT
name
FROM S_US
WHERE US_ID IN (AS_ID);
BEGIN
FOR A IN C_A (AS_IDS) LOOP
DBMS_OUTPUT.PUT_LINE('I got here: '||AS_IDS);
end loop;
END;
But while debuging the count of the cursor is still null
So my question , why the cursor not returning values with in condition
You are passing a string parameter, so it will be used as a string, not as a list of strings; so, your cursor will be something like
SELECT name
FROM S_US
WHERE US_ID IN ('EBN,BGE')
This will, of course, not do what you need.
You may need to change your procedure and the way to pass parameters; if you want to keep a string parameter , one way could be the following:
setup:
SQL> CREATE TABLE S_US
2 (
3 US_ID,
4 NAME
5 ) AS
6 SELECT 'EBN', 'EBN name' FROM DUAL
7 UNION ALL
8 SELECT 'BGE', 'BGE name' FROM DUAL;
Table created.
procedure:
SQL> CREATE OR REPLACE PROCEDURE TEXT_MD_2(AS_IDS VARCHAR2) IS
2 vSQL varchar2(1000);
3 c sys_refcursor;
4 vName varchar2(16);
5 BEGIN
6 vSQL := 'SELECT name
7 FROM S_US
8 WHERE US_ID IN (' || AS_IDS || ')';
9 open c for vSQL;
10 loop
11 fetch c into vName;
12 if c%NOTFOUND then
13 exit;
14 end if;
15 DBMS_OUTPUT.PUT_LINE(vName);
16 END LOOP;
17 END;
18 /
Procedure created.
You need to call it with a string already formatted to be a parameter list for IN:
SQL> EXEC TEXT_MD_2('''EBN'',''BGE''');
EBN name
BGE name
PL/SQL procedure successfully completed.
This is only an example of a possible way, and not the way I would do this.
Among the reasons to avoud this kind of approach, consider what Justin Cave says:
"that would be a security risk due to SQL injection and would have a potentially significant performance penalty due to constant hard parsing".
I believe you should better check how to pass a list of values to your procedure, rather then using a string to represent a list of strings.
Here is a possible way to do the same thing with a collection:
SQL> CREATE OR REPLACE TYPE tabVarchar2 AS TABLE OF VARCHAR2(16)
2 /
Type created.
SQL>
SQL> CREATE OR REPLACE PROCEDURE TEXT_MD_3(AS_IDS tabVarchar2) IS
2 vSQL VARCHAR2(1000);
3 c SYS_REFCURSOR;
4 vName VARCHAR2(16);
5 BEGIN
6 FOR i IN (SELECT name
7 FROM S_US INNER JOIN TABLE(AS_IDS) tab ON (tab.COLUMN_VALUE = US_ID))
8 LOOP
9 DBMS_OUTPUT.PUT_LINE(i.name);
10 END LOOP;
11 END;
12 /
Procedure created.
SQL>
SQL> DECLARE
2 vList tabVarchar2 := NEW tabVarchar2();
3 BEGIN
4 vList.EXTEND(2);
5 vList(1) := 'BGE';
6 vList(2) := 'EBN';
7 TEXT_MD_3(vList);
8 END;
9 /
BGE name
EBN name
PL/SQL procedure successfully completed.
SQL>
Again, you can define collections in different ways, within a stored procedure or not, indexed or not, and so on; this is only one of the possible ways, not necessarily the best, depending on your environment, needs.

ORA-00932 in cursor fetch

I have run into a strange problem in an ALREADY WORKING code.
There is a working procedure pkg_pbrer.p_gen_pbrer_rpt which returns v_po_report as an output cursor.
I am trying to capture this cursor into table_po_report_62 and this was working fine.
Now I am facing the error of
ORA-00932: inconsistent datatypes: expected - got -" in cursor fetch
statement.
For simplicity of understanding, I have omitted the unnecessary lines of code.
DECLARE
v_po_report SYS_REFCURSOR;
TYPE type_po_report_62 IS RECORD (soc varchar2(1000), pt varchar2(1000), mp varchar2(1000),
blind varchar2(1000), ac varchar2(1000), placebo varchar2(1000));
table_po_report_62 type_po_report_62;
--
--
-- Some working code
--
--
-- Initializing Reference cursor
open v_po_report for 'select 1 from dual';
pkg_pbrer.p_gen_pbrer_rpt (v_user_id,v_report_type,v_report_form_id,v_reg_report_id,v_po_report,v_po_case_list);
LOOP
FETCH v_po_report INTO table_po_report_62;
-- Encountered ORA-00932: inconsistent datatypes: expected - got -
EXIT WHEN v_po_report%NOTFOUND;
insert into pbrer_output62_report (soc, pt, mp, blind, ac, placebo)
values (table_po_report_62.soc, table_po_report_62.pt, table_po_report_62.mp, table_po_report_62.blind, table_po_report_62.ac, table_po_report_62.placebo) ;
END LOOP;
CLOSE v_po_report;
EXCEPTION
WHEN OTHERS THEN
--
--
-- Some working code
--
--
END;
Check your cursor data for recently added records which may be unconvertable for oracle. for exmaple a column accept varchar2 has value '1000' able to convert by oracle to a number but a value 'abc' do not.
open v_po_report for 'select 1 from dual';
FETCH v_po_report INTO table_po_report_62;
v_po_report is a refcursor which points to a single row dataset with a single column value 1, i.e. NUMBER data type. While you are trying to fetch into a record type with a completely different structure.
You refcursor basically returns:
SQL> var v_po_report refcursor
SQL> declare
2 v_po_report SYS_REFCURSOR;
3 BEGIN
4 OPEN :v_po_report FOR 'select 1 from dual';
5 END;
6 /
PL/SQL procedure successfully completed.
SQL> print v_po_report
1
----------
1
SQL>
So, with proper match of number of columns and data type, you could do it as:
SQL> DECLARE
2 v_po_report SYS_REFCURSOR;
3 TYPE type_po_report_62 IS RECORD (soc NUMBER);
4 table_po_report_62 type_po_report_62;
5 BEGIN
6 OPEN v_po_report FOR 'select 1 from dual';
7 LOOP
8 FETCH v_po_report INTO table_po_report_62;
9 EXIT WHEN v_po_report%NOTFOUND;
10
11 -- do something
12
13 END LOOP;
14 CLOSE v_po_report;
15 END;
16 /
PL/SQL procedure successfully completed.
SQL>

Resources