Tuesday 9 July 2013

associative array in oracle

Associative Array:

Earlier, we reviewed the definition of a PL/SQL Table (also know as an index-by table). The statement

TYPE book_title_tab IS TABLE OF book.title%TYPE
    INDEX BY BINARY_INTEGER;
book_titles   book_title_tab;


defines a collection of book titles, accessible by a numeric index. Although it is feasible to
locate an element by its numeric index, the limitation to this approach is that the value
 we have to search by is often not an integer.


SELECT title FROM book;


Above are values from the title column of the book table. If we needed to remove an entry,
given only the book title,we would have to search the entire collection in a somewhat inefficient manner.
The following is code illustrates this:


FOR cursor_column IN  book_titles.FIRST..book_titles.LAST LOOP
       IF book_titles(cursor_column) = 'A Farewell to Arms' THEN
          book_titles.DELETE(cursor_column);
       END IF;
   END LOOP;


With Associative Arrays, it is now possible to index by the title of the book.
In fact, there are numerous different indexing options, including by VARCHAR2,
 using the %TYPE keyword, and more. This is a improvement over indexing everything by an integer
 then having to shuffle through entries to find what you're looking for.
 Now, if we want to remove the book A Farewell to Arms, we can use an Associative Array:


DECLARE
   TYPE book_title_tab IS TABLE OF book.title%TYPE
       INDEX BY book.title%TYPE;
   book_titles book_title_tab;
BEGIN
      book_titles.DELETE('A Farewell to Arms');
END;



Ur's
AmarAlam

0 comments:

Post a Comment