Thursday, 8 September 2011

Use a nested table with TABLE

Once I have put my data into a nested table or varray, I can also take advantage of the TABLE operator to completely sidestep the need for an IN clause with a list of individual values. Instead, I use the TABLE operator so that the SQL statement can then treat the collection as a relational table, used as a subquery in the main SELECT to identify the rows of interest.
FUNCTION in_clause.nested_table_list (list_in IN pky_nt)
RETURN sys_refcursor
IS
retval sys_refcursor;
BEGIN
OPEN retval FOR
SELECT *
FROM otn_question
WHERE ID IN (SELECT column_value
FROM TABLE ( list_in ));

RETURN retval;
END nested_table_list;
Notes on this implementation:
• To use this approach, I must move the elements in my IN list to the collection. You may need to parse a delimited string or in some other way separate the items and place them into a collection.
• You will need to change this program to work with your collection type, rather than the pky_nt type you will find defined in the script at the end of this answer.
• Since this function returns a cursor variable, it can be called from non-PL/SQL host environments, such as Java, which work very easily with cursor variables.
• When using the TABLE operator on a collection of scalars, like list_in, Oracle then requires you to specify the "column" in that collection as COLUMN_VALUE.
• Regardless of the number of items in the collection, the SQL statement executed does not change, so you will not have to worry about the possible overhead of repeated hard parses, as you do with both the NDS (above) and DBMS_SQL (below) implementations.

No comments:

Post a Comment