HomeOracle Page 2 - Database Interaction with PL/SQL, part 3
Using TABLE Without Interacting With Database - Oracle
Jagadish Chatarji has been writing about database interactions with Oracle PL/SQL. The last part started on TYPE, RECORD, and TABLE declarations of PL/SQL. This one now goes further into TABLE, RECORD, and using them together. It will also introduce NESTED TABLES.
First of all, consider my apologies for inserting this topic inside an article titled as "database interactions using PL/SQL". I thought that this would be necessary, as some of our logic depends on some PL/SQL tables which don't always have to be filled with database information. And of course, using this topic, I can also introduce few new collection methods on working with PL/SQL tables.
Let us consider the following example. Even though it is bit lengthy, I can introduce all issues at once.
declare type t_Numtbl is table of number; v_numtbl t_numtbl := t_Numtbl(10,20,30,40,50,60,70); begin dbms_output.put_line('Displaying complete List:'); for i in v_numtbl.first .. v_numtbl.last loop dbms_output.put(v_numtbl(i) || ','); end loop; dbms_output.new_line; --just skipping to next line v_numtbl.delete(3); dbms_output.put_line('Displaying complete List after deletion:'); for i in v_numtbl.first .. v_numtbl.last loop if v_numtbl.exists(i) then dbms_output.put(v_numtbl(i) || ','); end if; end loop; dbms_output.new_line; dbms_output.put_line('No. of elements ' || v_numtbl.count); end;
Let us consider the above program line by line. I don't think I need to cover FOR loops in the above program, as they have been already covered in my previous article.
type t_Numtbl is table of number;
The above line defines 't_Numtbl' as a new data type which can hold only a set of values of type 'number'.
The above line declares and initializes the variable 'v_numtbl' with some sample values. Make a note that they are not from database! Within the body of the above program, I used FOR loops twice to display the contents of the variable 'v_numtbl'.
After displaying the values using the first FOR loop, I am deleting the third element (index starts from 1) from the table using the above statement.
if v_numtbl.exists(i) then dbms_output.put(v_numtbl(i) || ','); end if;
The above condition checks to see if the specified index exists within the table or not before trying to display it. If you don't include this, we would get an error.
dbms_output.put_line('No. of elements ' || v_numtbl.count);
You can use 'v_numtbl.count' to get the number of elements present within the PL/SQL table.