nested table element assignment in pl/sql - collections

My requirement in pl/sql nested table is the following:
I have a nested table collection type declared and I populate the elements based on a lookup from a table.
In cases where the lookup yields more than one row(more than one value for code), then add all those multiple values in the nested table and proceed. Here is where i am stuck.
I am not able to increment that parent counter "indx" inside the exception to process those multiple rows. Since i am not, it only stores the latest data in the nested table and not all of them.
declare
TYPE final_coll_typ IS TABLE OF varchar2(100);
l_final_coll final_coll_typ;
MULTI_FETCH EXCEPTION;
PRAGMA EXCEPTION_INIT(MULTI_FETCH, -1422); -- this is an ora error for exact fetch returns more than the required number of rows
begin
for indx in 1..<count> loop
<some processing logic here>
select code into l_final_coll(indx) from lookup_tbl where <some filter>;
exception
when MULTI_FETCH then
for p in (select code from lookup_tbl where <some filter>)
loop
l_final_coll(indx) := p.code;
dbms_output.put_line(l_final_coll(indx));
end loop;
continue; -- this is for further processing after the loop
end loop;
end;
Lets say, the first iteration of the counter indx produced only one row data for code. That gets stored in l_final_coll(indx).
Lets say the next iteration of indx i the main for loop produces 2 rows of values for code. My thought was to catch the exception (ORA-01422) and keep adding these 2 code values in the existing nested table.
So, in effect, my nested table should now have 3 values of code in its element. But, currently, I can only get it to populate 2 of them (the single value from first itreration and the latest value from the next)
Any pointers would be appreciated on how I can accomplish this.
PS: Tried manipulating the counter variables indx and p. But, obviously pl/sql does not allow it for a "for loop".

You don't need to do a single select at all, just use the cursor loop to start with, and append to the collection (which you'd have to initialise):
declare
type final_coll_typ is table of varchar2(100);
l_final_coll final_coll_typ;
begin
l_final_coll := final_coll_typ();
for indx in 1..<count> loop
<some processing logic here>
for p in (select code from lookup_tbl where <some filter>) loop
l_final_coll.extend(1);
l_final_coll(l_final_coll.count) := p.code;
end loop;
end loop;
dbms_output.put_line('Final size: ' || l_final_coll.count);
end;
/
For each row found but the cursor, the collection is extended by one (which isn't very efficient), and the cursor value is put in the last, empty, row; which is found from the current count.
As a demo, if I create a dummy table with a duplicate value:
create table lookup_tbl(code varchar2(100));
insert into lookup_tbl values ('Code 1');
insert into lookup_tbl values ('Code 2');
insert into lookup_tbl values ('Code 2');
insert into lookup_tbl values ('Code 3');
... then with a specific counter and filter:
declare
type final_coll_typ is table of varchar2(100);
l_final_coll final_coll_typ;
begin
l_final_coll := final_coll_typ();
for indx in 1..3 loop
for p in (select code from lookup_tbl where code = 'Code ' || indx) loop
l_final_coll.extend(1);
l_final_coll(l_final_coll.count) := p.code;
end loop;
end loop;
dbms_output.put_line('Final size: ' || l_final_coll.count);
end;
/
... I get:
anonymous block completed
Final size: 4
As a slightly more complicated option, you could bulk-collect all the matching data into a temporary collection, then loop over that to append those values into the real collection. Something like:
declare
type final_coll_typ is table of varchar2(100);
l_final_coll final_coll_typ;
l_tmp_coll sys.dbms_debug_vc2coll;
begin
l_final_coll := final_coll_typ();
for indx in 1..<count> loop
<some processing logic here>
select code bulk collect into l_tmp_coll from lookup_tbl where <some filter>;
for cntr in 1..l_tmp_coll.count loop
l_final_coll.extend(1);
l_final_coll(l_final_coll.count) := l_tmp_coll(cntr);
end loop;
end loop;
end;
/
There may be a quicker way to combine two collections but I'm not aware of one. Bulk-collect has to be into a schema-level collection type, so you can't use your local final_coll_typ. You can create your own schema-level type, and then use it for both the temporary and final collection variables; but I've used a built-in one, sys.dbms_debug_vc2coll, which is defined as table of varchar2(1000).
As a demo, with the same table/data as above, and the same specific count and filter:
declare
type final_coll_typ is table of varchar2(100);
l_final_coll final_coll_typ;
l_tmp_coll sys.dbms_debug_vc2coll;
begin
l_final_coll := final_coll_typ();
for indx in 1..3 loop
select code bulk collect into l_tmp_coll
from lookup_tbl where code = 'Code ' || indx;
for cntr in 1..l_tmp_coll.count loop
l_final_coll.extend(1);
l_final_coll(l_final_coll.count) := l_tmp_coll(cntr);
end loop;
end loop;
dbms_output.put_line('Final size: ' || l_final_coll.count);
end;
/
... I again get:
anonymous block completed
Final size: 4

Related

PLS-00382: expression is of wrong type in populating an associative array table

I have this structure of table in my database
Now i want all the values inside of it in a associative array that is indexed by the job_id%type which is a varchar2, so i created this anonymous block first before creating a procedure to test it and i want to populate my associative array with the results:
DECLARE
TYPE jobs_tab_type IS TABLE OF jobs%rowtype INDEX BY jobs.job_id%type;
jobstab jobs_tab_type;
BEGIN
FOR rec IN (SELECT * FROM jobs)
LOOP
jobstab(rec.job_id) := rec.job_id;
END LOOP;
END;
I know for sure that this is a wrong way to do it since I've encountered this error: PLS-00382: expression is of wrong type , but at the same time i don't know if there is any proper way to do this. I have seen the documentation but all the examples were to use a user defined string that will hold the job_id, but the problem is that i need the job_id to be indexed and not a user defined string. Is there any way to fix this problem in PL/SQL?
You don't need the index by INDEX BY jobs.job_id%type. It is making your code more complicated. The INDEX BY determines the index of the collection - that is the character used to indicate the position in the collection. That doesn't need to be a column from the table you are taking a %rowtype from.
Typically an INDEX BY VARCHAR2 is used if you want to reference the collection based on a meaningful string, like capitals('United States') = 'Washingston'
Now, about your question. Here is the answer to the original question:
create table jobs
(job_id VARCHAR2(10)
,job_title VARCHAR2(30)
,min_salary NUMBER
,max_salary NUMBER
);
INSERT INTO jobs (job_id, job_title, min_salary, max_salary) VALUES ('a','CLERK',100,500);
INSERT INTO jobs (job_id, job_title, min_salary, max_salary) VALUES ('b','PRESIDENT',1000,5000);
INSERT INTO jobs (job_id, job_title, min_salary, max_salary) VALUES ('c','SALESMAN',500,800);
DECLARE
TYPE jobs_tab_type IS TABLE OF jobs%rowtype INDEX BY jobs.job_id%type;
jobstab jobs_tab_type;
l_idx VARCHAR2(100);
BEGIN
FOR rec IN (SELECT * FROM jobs)
LOOP
jobstab(rec.job_id) := rec;
END LOOP;
l_idx := jobstab.FIRST;
WHILE (l_idx IS NOT NULL) LOOP
dbms_output.put_line(l_idx ||': '||jobstab(l_idx).job_title);
l_idx := jobstab.NEXT(l_idx);
END LOOP;
END;
/
a: CLERK
b: PRESIDENT
c: SALESMAN
Notice that in this block, it's a bit tedious to loop through the elements, just because the index is not an integer. Now lets look at the same functionality, but using an INDEX BY BINARY_INTEGER:
DECLARE
TYPE jobs_tab_type IS TABLE OF jobs%rowtype INDEX BY BINARY_INTEGER;
jobstab jobs_tab_type;
l_idx NUMBER := 1;
BEGIN
-- example 1: using a cursor for loop
-- FOR rec IN (SELECT * FROM jobs)
-- LOOP
-- jobstab(l_idx) := rec;
-- l_idx := l_idx + 1;
-- END LOOP;
-- example 2: using bulk collect
SELECT * BULK COLLECT INTO jobstab FROM jobs;
FOR r IN 1 .. jobstab.COUNT LOOP
dbms_output.put_line(r ||': '||jobstab(r).job_title);
END LOOP;
END;
/
1: CLERK
2: PRESIDENT
3: SALESMAN
It's simpler to loop through the values of a collection because of the numeric index and it also can be implicitly assigned as well, using the BULK COLLECT statement.
The value of your associative array is the entire record. Hence just remove .job_id from this line of your code.
jobstab(rec.job_id) := rec.job_id;
In other words, the line should be
jobstab(rec.job_id) := rec;
Refer to this db<>fiddle

Compound Triggers

Problem - Want to avoid the problem of mutating triggers by using the compound trigger. But unable to do so
Background -
I want to insert data in new table " Tracking Table " whenever there is change in Main table "CUSTOM_ITEM"
Design is such that, everytime a row is created in table an ITEM_ID is generated but there is a column FIRST_ITEM_ID that remains same in some cases.
So whenever a new row is added, I want to check its FIRST_ITEM_ID and then check the whole table and find out all the ITEM_IDs having that same FIRST_ITEM_ID.
And I want to insert all those rows in the New table using trigger.
Is it even possible ?
Attaching the trigger :
CREATE OR REPLACE TRIGGER APP.TEST_TRG
FOR DELETE OR INSERT OR UPDATE
ON APP.CUSTOM_ITEM
COMPOUND TRIGGER
TYPE t_change_tab IS TABLE OF APP.TEST_TRG.OBJECT_ID%TYPE;
g_change_tab t_change_tab := t_change_tab();
BEFORE EACH ROW IS
BEGIN
Select item_id bulk collect into g_change_tab from CUSTOM_ITEM where first_item_id =
(Select first_item_id from CUSTOM_ITEM where item_id = :NEW.item_id);
For i in 1 .. g_change_tab.COUNT()
LOOP
g_change_tab.extend;
END LOOP;
END BEFORE EACH ROW;
AFTER STATEMENT IS
BEGIN
For i in 1 .. g_change_tab.COUNT()
LOOP
app.bc_acs_pkg.populate_TEST_TRG /* Package Inserts data */
(p_object_type => 'ITEM',
p_object_id => g_change_tab(i));
END LOOP;
g_change_tab.delete;
END AFTER STATEMENT;
END ;
/
You can do what you want just not with your current approach. Let's take a step back. What is a mutating table exception (ORA-04091). It is thrown when you attempt to access the table on which the trigger fired in a row level event, that is not permitted. Just creating a compound trigger does not remove that restriction. So in your Before Row segment the statement
Select item_id
bulk collect into g_change_tab
from CUSTOM_ITEM where first_item_id =
(Select first_item_id from CUSTOM_ITEM where item_id = :NEW.item_id);
is invalid, and results in raising ORA-04091. What you need is to just build your collection with the necessary ids. Then process them in the After statement segment.
create or replace trigger test_trg
for delete or insert or update
on custom_item
compound trigger
type t_change_tab is
table of custom_item.first_item%type;
g_change_tab t_change_tab := t_change_tab();
before each row is
l_first_item_exists boolean := false;
indx integer;
begin
indx := g_change_tab.first;
while not l_first_item_exists
and indx is not null
loop
l_first_item_exists := (g_change_tab(indx) = :new.first_item);
if not l_first_item_exists
then
indx := g_change_tab.next(indx);
end if;
end loop;
if not l_first_item_exists
then
g_change_tab.extend;
g_change_tab(g_change_tab.last) := :new.first_item;
end if;
end before each row;
after statement is
begin
for indx in g_change_tab.first .. g_change_tab.last
loop
insert into tracking_table(item_id, first_item)
select item_id, first_item
from custom_item
where first_item = g_change_tab(indx);
end loop;
end after statement;
end test_trg;
The issue here is the loops, always the slowest processing, and very bad in triggers. Below is an approach which avoids them totally. It does however require creating your type array at the schema level.
create or replace type custom_item_change_t is
table of integer ; --custom_item.first_item%type;
create or replace trigger test_trg
for insert
on custom_item
compound trigger
g_change_tab custom_item_change_t := custom_item_change_t();
before each row is
begin
g_change_tab.extend;
g_change_tab(g_change_tab.last) := :new.first_item;
end before each row;
after statement is
begin
insert into tracking_table(item_id, first_item)
select item_id, first_item
from custom_item ci
where first_item in (select distinct column_value
from table(g_change_tab)
)
and not exists
( select null
from tracking_table tt
where ci.item_id = tt.item_id
and ci.first_item = tt.first_item
);
end after statement;
end test_trg;

Assigning object type in plsql

I need your help to know how to assign the object type through a string in PLSQL
Below is the problem description:
I first created the object types as below:
create or replace type picu_obj is object(Customer_ID varchar2(32767),Customer_Name varchar2(32767),Server_Name varchar2(32767),Time_stamp varchar2(32767));
create or replace type picu_obj_tab is table of picu_obj;
and I have a PLSQL block as below:
declare
l_str1 varchar2(1000);
l_str2 varchar2(10000);
l_newstr1_1 varchar2(10000);
picu_var picu_obj_tab;
cursor c1cudetails
is
select item,current_value
from
(select rownum,
last_value(category ignore nulls) over (order by rownum) category ,
last_value(item ignore nulls) over (order by rownum) item,
current_value
from pi_perfdata_new
order by rownum
)
where upper(category) like '%CUSTOMER%DETAILS%' ;
type cudet is table of c1cudetails%rowtype index by pls_integer;
l_cudet cudet;
begin
/* create dynamic string for items */
open c1cudetails;
fetch c1cudetails bulk collect into l_cudet limit 50;
for i in l_cudet.first..l_cudet.last loop
l_str1:=l_str1||','||''''||l_cudet(i).current_value||'''';
l_str2:=trim(leading ',' from l_str1);
l_newstr1_1:='picu_obj_tab(picu_obj('||l_str2||'))';
end loop;
-- dbms_output.put_line(''||l_newstr1_1||'');
-- picu_var := l_newstr1_1;
close c1cudetails;
end;
For the string "l_newstr1_1" following value is retruned from above PLSQL block
picu_obj_tab(picu_obj('CSCO5','DXRTYE','PI22-pro-333','2015-07-22-22:48:56'))
Now I want to assign the above result to variable "picu_var" which I have declared.
Basically I need to convert to the following during runtime.
picu_var := picu_obj_tab(picu_obj('CSCO5','DXRTYE','PI22-pro-333','2015-07-22-22:48:56'))
How to achieve the same?
Please suggest how to initialize the object type variable to the string values.
Use dynamic PL/SQL like this:
execute immediate 'begin :x := ' || l_newstr1_1|| '; end;'
using out picu_var;

How to place a plsql block inside a sequence

I am trying to create a user generated sequence. According to usual syntax of oracle sequence we can start with a number and increment a value.
Is there a method to write a plsql block (declare begin end) inside a sequence and generate my own sequnce.
example : ABC001
When i call the next val of sequence , the value should be ABC002
PLEASE CLEAR FIRST WHAT YOU EXACTLY WANT TO ASK.
If you are asking HOW TO DYNAMICALLY CREATE SEQUENCE USING PL/SQL, then check below.
Simplest way.
DECLARE
SQL_S VARCHAR2(100);
BEGIN
SQL_S := 'CREATE SEQUENCE SQN_NAME INCREMENT BY 1 START WITH 1';
EXECUTE IMMEDIATE SQL_S;
END;
/
If you want to dynamically create sequence with some DYNAMIC name as argument passed to procedure, then it will be like
CREATE OR REPLACE PROCEDURE DYNAMIC_SQN (ARG IN VARCHAR2) IS
SQL_S VARCHAR2(100);
PARAM1 VARCHAR2(20);
BEGIN
PARAM1 := 'SQN_NAME_' || ARG;
SQL_S := 'CREATE SEQUENCE ' || PARAM1 || ' INCREMENT BY 1 START WITH 1';
EXECUTE IMMEDIATE SQL_S;
END;
/
And if you simply want to insert in to any column, and create the PK using it in addition to some String, then
INSERT INTO TABLE_T VALUES('ABC'|| SEQUENCE_NAME.nextval, OTHER_VALUES);
It will still give you values like : ABC1, ABC2, .... ABC12, ABC13, .... ABC99, ABC100 and so on...
Considering the sample example you have given i m writing the following code
create your sequence, then
insert into seq values('ABC'||YOURSEQUENCENAME.nextval,YOUR_VALUE);

Oracle 11g : When declaring new TYPE as TABLE, must I add "INDEX BY PLS_INTEGER"?

What is the diffecence between adding INDEX BY PLS_INTEGER and not at end of declaration of new table type. Look at this example:
DECLARE
GC_BULK_LIMIT CONSTANT INTEGER := 500;
CURSOR CUR_CLIENTS IS SELECT C.ID, C.NAME FROM CLIENTS C;
TYPE RT_CLIENTS IS TABLE OF CUR_CLIENTS%ROWTYPE;
-- TYPE RT_CLIENTS IS TABLE OF CUR_CLIENTS%ROWTYPE INDEX BY PLS_INTEGER;
LT_CLIENTS RT_CLIENTS;
BEGIN
OPEN CUR_CLIENTS;
LOOP
FETCH CUR_CLIENTS BULK COLLECT INTO LT_CLIENTS LIMIT GC_BULK_LIMIT;
EXIT WHEN LT_CLIENTS.COUNT = 0;
FOR I IN 1..LT_CLIENTS.COUNT LOOP
-- ... SOME LOGIC
END LOOP;
END LOOP;
CLOSE CUR_CLIENTS;
END;
in response to "must i add". The short answer is NO.
the difference is that
TYPE RT_CLIENTS IS TABLE OF CUR_CLIENTS%ROWTYPE;
Is a nested table. This means that for a given variable of this type, we know that the subscripts are sequential. i.e. the subscript starts from 1 and goes up to the array length.
The following loop therefore, is the right way to access a nested table array:
FOR I IN 1..LT_CLIENTS.COUNT LOOP
This however, is called a associative array:
TYPE RT_CLIENTS IS TABLE OF CUR_CLIENTS%ROWTYPE INDEX BY PLS_INTEGER;
(you could also index by a varchar2 if you wanted). The difference is that the subscripts in this case do not have to be sequential, depending on how the array was populated. In your code, they would be (as bulk collect would do that), but its not always the case.
The safe way to access and loop through an index by array is :
v_subscript := t_arr.first;
while v_subscript is not null loop
dbms_output.put_line(v_subscript || ': ' || t_arr(v_subscript));
v_subscript := t_arr.next(v_subscript);
end loop;
where v_subscript is a variable of the same datatype of the index by part.
also with a nested table, you can populate the array quickly with:
declare
type myarr is table of number;
t_arr myarr;
v_subscript number;
begin
t_arr := myarr(1, 12, 44);
whereas with an index by array you'd have to have three lines there to populate it:
t_arr(1):= 1;
t_arr(2):= 12;
t_arr(3):= 44;
for your particular case, without the index by is perfectly fine.
further reading: http://docs.oracle.com/cd/E18283_01/appdev.112/e17126/composites.htm

Resources