Collections, Cursors, Bulk Binds and FORALL

27
PL/SQL Collections PL/SQL Collections These are composite variables in PL/SQL and have internal components that you can treat as individual variables. You can pass these composite variables to subprograms as a parameters. To create a collection or record variable, you first define a collection or record type, and then you declare a variable of that type. In a collection, the internal components are always of the same data type, and are called elements. You access each element by its unique subscript. Lists and arrays are classic examples of collections. In a record, the internal components can be of different data types, and are called fields. You access each field by its name. A record variable can hold a table row, or some columns from a table row. Each record field corresponds to a table column. PL/SQL Collection Types: PL/SQL has three collection types, whose characteristics are summarized below. 1] Associative array (or index-by table) Number of Elements: Unbounded Subscript Type: String or integer Dense or Sparse: Either Where Created: Only in PL/SQL block 2] Nested Table Number of Elements: Unbounded Subscript Type: Integer Dense or Sparse: Starts dense, can become sparse Where Created: Either in PL/SQL block or at schema level 3] Variable size Array (Varray) Number of Elements: Bounded Subscript Type: Integer

Transcript of Collections, Cursors, Bulk Binds and FORALL

Page 1: Collections, Cursors, Bulk Binds and FORALL

PL/SQL Collections

PL/SQL Collections

These are composite variables in PL/SQL and have internal components that you can treat as individual variables. You can pass these composite variables to subprograms as a parameters.To create a collection or record variable, you first define a collection or record type, and then you declare a variable of that type.

In a collection, the internal components are always of the same data type, and are called elements. You access each element by its unique subscript. Lists and arrays are classic examples of collections.

In a record, the internal components can be of different data types, and are called fields. You access each field by its name. A record variable can hold a table row, or some columns from a table row. Each record field corresponds to a table column.

PL/SQL Collection Types:PL/SQL has three collection types, whose characteristics are summarized below.1] Associative array (or index-by table)

Number of Elements: Unbounded Subscript Type: String or integer Dense or Sparse: Either Where Created: Only in PL/SQL block

2] Nested Table Number of Elements: Unbounded Subscript Type: Integer Dense or Sparse: Starts dense, can become sparse Where Created: Either in PL/SQL block or at schema level

3] Variable size Array (Varray) Number of Elements: Bounded Subscript Type: Integer Dense or Sparse: Always Dense Where Created: Either in PL/SQL block or at schema level

Note:Unbounded means that, theoretically, there is no limit to the number of elements in the collection. Actually, there are limits, but they are very high.Dense means that the collection has no gaps between elements—every element between the first and last element is defined and has a value (which can be NULL).A collection that is created in a PL/SQL block is available only in that block. A nested table type or varray type that is created at schema level is stored in the database, and you can manipulate it with SQL statements.A collection has only one dimension, but you can model a multidimensional collection by

Page 2: Collections, Cursors, Bulk Binds and FORALL

creating a collection whose elements are also collections.Associative Arrays (Index-By Tables):An associative array (also called an index-by table) is a set of key-value pairs. Each key is unique, and is used to locate the corresponding value.01 DECLARE02   -- Associative array indexed by string:03  04      TYPE ODI_RUNS IS TABLE OF NUMBER  -- Associative array type05   INDEX BY VARCHAR2(64);06  07      odi_batsman_runs  ODI_RUNS;        -- Associative array variable08   i VARCHAR2(64);09  10   BEGIN11     -- Add new elements to associative array:12  13      odi_batsman_runs('Virender Sehwag')  := 7380;14      odi_batsman_runs('Ricky Ponting')    := 13082;15      odi_batsman_runs('Sachin Tendulkar') := 17629;16  17    -- Print associative array:18  19   i := odi_batsman_runs.FIRST;20  21   WHILE i IS NOT NULL LOOP22       DBMS_Output.PUT_LINE

23   ('Total ODI Runs on Jan 2010 by ' || i || ' is ' || TO_CHAR(odi_batsman_runs(i)));

24   i := odi_batsman_runs.NEXT(i);25     END LOOP;26     END;

Output:Total ODI Runs on Jan 2010 by Ricky Ponting is 13082Total ODI Runs on Jan 2010 by Sachin Tendulkar is 17629Total ODI Runs on Jan 2010 by Virender Sehwag is 7380

Like a database table, an associative array holds a data set of arbitrary size, and you can access its elements without knowing their positions in the array.

An associative array does not need the disk space or network operations of a database table, but an associative array cannot be manipulated by SQL statements (such as INSERT and DELETE).

An associative array is intended for temporary data storage. To make an associative array persistent for the life of a database session, declare

the associative array (the type and the variable of that type) in a package, and assign values to its elements in the package body.

Nested Tables: A nested table is like a one-dimensional array with an arbitrary number of elements.

Page 3: Collections, Cursors, Bulk Binds and FORALL

Within the database, a nested table is a column type that holds a set of values. The database stores the rows of a nested table in no particular order. When you retrieve a nested table from the database into a PL/SQL variable, the rows are given consecutive subscripts starting at 1. These subscripts give you array-like access to individual rows.A nested table differs from an array in these important ways:

An array has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically.

An array is always dense (that is, it always has consecutive subcripts). A nested array is dense initially, but it can become sparse, because you can delete elements from it.

Variable-Size Arrays (Varrays):A variable-size array (varray) is an item of the data type VARRAY. A varray has a maximum size, which you specify in its type definition. A varray can contain a varying number of elements, from zero (when empty) to the maximum size. A varray index has a fixed lower bound of 1 and an extensible upper bound. To access an element of a varray, you use standard subscripting syntax.01 DECLARE02   TYPE nested_type IS TABLE OF VARCHAR2(30);03   TYPE varray_type IS VARRAY(5) OF INTEGER;04   v1 nested_type;05   v2 varray_type;06 BEGIN07   v1 := nested_type('Shipping','Sales','Finance','Payroll');08   v2 := varray_type(1, 2, 3, 4, 5); -- Up to 5 integers09 FOR i IN v1.FIRST .. v1.LAST10    LOOP

11   DBMS_OUTPUT.PUT_LINE('Element #' || i || 'in the nested table = ' || v1(i));

12    END LOOP;13  14 FOR j IN v2.FIRST .. v2.LAST15    LOOP

16   DBMS_OUTPUT.PUT_LINE('Element #' || j || 'in the varray = ' || v2(j));

17    END LOOP;18 END;

Nested tables Vs. Varrays: Nested tables are unbounded and are initially dense but can become sparse

through deletions. Varrays are always bounded and never sparse. When stored in the database, the order and subscripts of Nested tables are not

preserved while varrays keep their ordering and subscripts. Nested table data is stored in a separate store table, a system-generated database

table while a  varray is stored as a single object in the database.

Page 4: Collections, Cursors, Bulk Binds and FORALL

Oracle Apps Technical Interview and answers

1. Using PL/SQL, which exception is raised when a division by zero is attempted?Ans ) zero divide error occurs2. Which constraint type ensures that each row in a table contains an entry that uniquely identifies that row from any other. Ans ) primary key3. Views can be defined with up to (?) columns. Ans ) 2544. During database creation, which of the following database users require setting their password? Ans ) sys5. What is a Cartesian product?Ans )The product of a select statement which has more than one table, and no where clause6. A developer calls and reports they are receiving an ORA-00901: invalid CREATE command. What is most likely the problem?Ans ) The CREATE command was not followed by a valid option7. The DECODE () function is similar to (?).Ans ) an if then else construct8. In which section of a PL/SQL block will a user defined exception be handled?Ans ) exception block9. Which of the following are used to determine the order of an ORDER BY clause?Ans ) ASC10. Which of the following are NOT number functions?Ans ) TODATE()11. What column heading is displayed for the following query? SELECT COUNT(ENAME) Count FROM EMP Ans) COUNT12. More frequent checkpoints reduce the time needed to (?). Ans ) recover13. A (?) is an area of memory, given a name, that is used to store a value.Ans ) variable14. How is the command SELECT * FROM EMP WHERE EMPNO=&X.45 interpreted if 123 is entered as a value for X?Ans ) SELECT * FROM EMP WHERE EMPNO=12345;15. The third value in a ROWID represents the (?) of that row. Ans ) file ID16. Which of the following are NOT valid comparison operators?Ans ) == (two equal signs)17. What structure is used to prevent more than one user from updating the same data in a table at the same time? Ans ) locks18. The default length for char data type is Ans ) one19. The default order in which records are retrieved when an order by clause is used is

Page 5: Collections, Cursors, Bulk Binds and FORALL

Ans ) Ascending20. The operator precedence between AND & OR is Ans) AND over OR21. The output of ltrim (\"BILL CLINTON\",BALL) isAns) ILL CLINTON22. The output of substr (\"CREATE\",3,3) is Ans) EAT23. The number of minimum join condition that are required to join n tables is N-124. In an outer join (+) sign is placed on the Ans) deficient table side25. A sub-query can appear within which of the following clauses & operators 1. Select 2. Where 3. Having 4. Set operators Ans ) select , having and set operators26. If where clause is not specified in an update statement thenAns ) all rows updated27. The database object from which multiple users may generate unique integer isAns ) sequence28. Cluster columns must correspond to columns in each of the cluster tables inAns ) size and column name29. The clause in the computer command that helps in computing count of rows isAns ) number30. The elements, which are mandatory for a PL/SQL blocks areAns ) begin and end;31. The concatenation operator in PL/SQL is Ans)32. Which of the following are available in PL/SQL and not in SQLAns ) data access compatibility33. The assignment operator in PL/SQL is Ans) =34. The procedure which lets you issue user-defined error messages from a stored sub-program or database trigger isAns ) exception_unit and raise_application_error35. Data can be retrieved into variables using which of the following optionsAns ) select into and fetch36. Which of the following does a cursor For Loop do 1. Open a cursor 2. Fetch 3. close cursor Ans) ALL37. Which statement can appear in a trigger body Ans) SQL set38. To create a database trigger, the user must have the privilege.Ans ) create trigger privilege39. Which operator finds common rows from 2 or more different queries?Ans ) intersect40. Foreign key constraint can be enforced by using constraint.Ans ) references41. The statement fetches rows from a table to a cursor. Ans) select42. The NVL() function is used to Ans) substitute a new value

Page 6: Collections, Cursors, Bulk Binds and FORALL

43. The maximum size of LOB is Ans) 4gb44. How many triggers can create per table Ans) 1245. Maximum how many constraints can enforce on a single column Ans) four46. PL/SQL stands for Ans ) procedural language of sql47. which are the character functions will take string parameter and it will return numeric Ans) length and instr48. Select trunc(199.99) from dual Ans) “199”49. Which constraint is only a table level Ans) composite primary key50. Triggers can call in subprograms Ans) yes51. The NULL columns do not participate in arithmetic computations52. You cannot create more than one trigger per table.53. Which Procedure produces output on the screenAns ) dbms_output.putline()54. The cursor is created by any SQL statement. Ans) implicit55 Which triggers are used for views? Ans) instead of triggers56 select statement is Ans ) DRL 57 trigger is fired Ans ) implicitly58 A Cartesian product is Ans ) only available in oracle 8i59 Select empcode, sum(basic) from empmaster? Can you create a view based on the above select? Ans ) no60 Which of the following correctly describes how to specify a column aliasAns ) Place the alias after each column, separated by white space.61 The command to open a CURSOR FOR loop isAns ) No command is required62 If left out, which would cause an infinite loop Ans) exit63 After referencing NEXTVAL, the value in CURRVAL of a sequence isAns ) incremented by 164 What control structure prevents more than one user from updating data in a table?Ans ) locks65 Which of the following two constraints automatically create an index?Ans ) Unique Constraint66 How many equality conditions are required to join four tables without a Cartesian product? Ans) two67 How do we join two or more tables? Using =68 What is the minimum number of shared columns to join two tables in a select statement? Ans ) one69 Which of the following are NOT valid comparison operators? Ans) >>70 When entering a SELECT statement from the SQL prompt the command is terminated with which character? Ans ) /71 What function is similar in function to an IF-THEN-ELSE statement?Ans ) decode()

Page 7: Collections, Cursors, Bulk Binds and FORALL

72 Which of the following is a character function? Ans) to_number()73 The binary extension for the menu is Ans) .mmb74 An ER Diagram which relates 2 entities with dark line joining one entity and with crow foot on the other side is calledAns) Many to Many75 Once defined, how long will a variable remain in SQL*Plus?Ans) Until the session Completes76 After an Update statement, you write an exception with no_data_found, too_many_rows and when others. If the Update statements where condition fails to update any rows then which exception will be raised?Ans) no_data_found77 Not Null is which type of constraint? Ans ) check78 How do you make sure that Oracle will use an Index when you write a select statement? Ans) by selecting columns which have index79 Forms allows you to manipulate data only if it is Ans) normal mode80 The different views of objects in object NavigatorAns ) Ownership view and Visual View81 For undoing changes in the form during design timeAns ) Press CTRL+Z82 Alert message should not exceed Ans) 200 Characters83 Data Blocks in the form builder can be classified asAns ) Master & Detail Block84 The type of alerts can be set Ans) Note, Caution, Stop85 The 4 different states of records are as follow ( when internal events of forms run time) Ans ) New, Insert, query, Changed86 The hierarchy tree of objects in the form applicationAns ) Form(Module), Block, record, Item87 VALIDATE RECORD , Trigger (event) occurs only if the record is Ans) insert88 LOV (LIST OF VALUES) is a combination ofAns ) Modal dialog Boxes, List and Record Groups89 The trigger can be classified as the following:-Ans ) Smart triggers, Un restricted, Triggers, restricted Triggers90 The built in procedure to open a form that is independent from calling form isAns ) open_form91 The way to involve Report from form object is Ans) run_report_object92 The is the syntax and place the variable declared in form module to all the triggers in the formAns ) Declare in PREFOR and the syntax is :Global.93 A primary key constraint cannot be added on the column of which data typeAns ) long94 The comprises set of files that protect altered database data that

Page 8: Collections, Cursors, Bulk Binds and FORALL

has not been written to data files Ans) redo log95 Maximum size of raw data type is Ans) 2kb96 Which one of the following is not applicable on INSTEAD OF TriggerAns ) Can be applied on tables97 In Oracle 8, a char database can hold up to Ans) 2000 bytes98 After creating a sequence, to view the first value we use which keywordAns ) nextval99 In PL/SQL assignment operator is replaced using the reserved wordAns) default100 is a valid pseudo columnAns) rowid, rownum, sysdate, uid, nextval, curval101 The Index created by the Primary key column is called ans) unique index102 The operation cannot be performed using views when the view definition includes more than on table Ans) insert103 The parameter cannot be changed while altering a sequenceAns ) start with n (n cant be changed)104 To check the source code for the object types use the data dictionary view Ans user_source105 Which of the following is most restrictive of table level locks?Ans) exclusive lock106 In PL/SQL block what is the default value of the variable Ans) null107 Find output of the following ( Select substr( \"christmas\" , 4,3) from dual)Ans ) ist108 The ability of object to take more than one form is known asAns ) polymorphism109 When the user is trying to assign values to the attributes of an uninitialized object, which of the following exception is raised Ans) VALUEERROR110 The attribute in the create sequence syntax specifies that the sequence continues to generate values from the beginning after reaching either its max or min value Ans) increment111 A composite unique key can contain how many number of columns Ans) 16112 What operations can be performed on sequence Ans) Alter, Select113 Restriction on triggers can be achieved using what clause Ans) when114 To check the partition type which data dictionary can be used.Ans ) user_tab_partitions115 Outer joins retrieves Ans) both matched and unmatched rows116 A function used to convert a null value to value is Ans) decode117 Role is Ans ) group of privileges118 A returns all rows returned by the simple join as well as those rows from one table that do not match any row from the other table Ans)

Page 9: Collections, Cursors, Bulk Binds and FORALL

outer join119 The data that stored in the cursor is called as Ans ) active data set120 what is the format mask for Julian data Ans ) j121 Label is a word associated with an statements Ans) conditional122 level locks are not released by rolling back to save point Ans ) row level123 you can use the CASE function in place of Ans) decode124 The writes modified blocks from the database buffer cache to the data filesAns ) database writer125 The magnitude range of a binary integer value in pL/sql isAns ) -231-1 to 231-1126 Trigger name should not exceed characters Ans) 30 characters127 The REF operator returns of the row object Ans) OID128 PL/SQL is a structured language? Ans ) block structured language129 Raw types are used to store which type of data Ans ) binary130 PCTFREE is a portion of the data block that is not filled by rows as they are inserted in to a table but is reserved for Ans ) 'Future insert131 Sign function returns Ans) +, - and =132 Syntax of MERGE functionAns) merge into using /<> on when matched these update set when not matched then insert values133 The oracle engine provides procedure named that allows programmers to show user defined messages Ans) Raise_Application_Error134 Which are called as trigger actions Ans) Before and after135 A function that act on only one value at a time are called asAns ) Scalar function136 is used to get cross tabulation & cumulative valuesans ) CUBE and ROLLUP137 Which is used for bulk bind? Ans) for all138 which is used to modify any operating system files Ans) UTL_File139 which is used to insert values in to multiple tables using select statementsans ) INSERTALL140 Which appends on operating system specific line terminator Ans) put_line141 Which is an object , that is completely contained within anotherAns ) embedded object142 Which of the following is false regarding data files?Ans ) Data files can be associated with two or more table spaces143 In which data dictionary table the object type information will be storedAns ) User_Types144 When you use the THE class in DML statements Ans) Nested table145 Which is used to store complete column information at a time in to

Page 10: Collections, Cursors, Bulk Binds and FORALL

a variableAns ) bulk collect146 when you use for update class in a cursor which is compulsoryans ) where current of 147 When cursor is in for loop which operations are not necessaryAns ) Open, Fetch, Close148 RowID consistes ofAns ) Data file Id, Object Id , Block Id, Row_Sequence_ID149 What is a object, which can be created only at run time Ans ) Timer150 what is the extension of .PLL Ans) Programming Link Library151 what is the extension of object library module Ans) OBL152 How many styles are there in alert property Ans) three153 Display item doesn’t have which property Ans) navigational154 When Timer Expired is correspondent to which object Ans) timer155 When we compare with radio button & push button, push button will not have Ans ) Button value property156 Which function is used to create runtime record group Ans) create_group157 which trigger and code is used to run application without connecting to databaseans ) on_logon,NULL158 Form 6i is a ans ) 2 and 3 Tier architecture159 When we select value from LOV, by default where the value is going to storeAns ) return item160 LOV always return ans ) boolean value161 Alert always return ans) number value162 Which procedure is used to change alert button labelAns ) set_alert_button_properly163 When we create a LOV automatically created ans ) record group164 which function is used to create dynamic query record groupans ) create_group_from_query165 How many types of canvas are there ans ) five166 Which variable cannot assign a value ans) system167 When you have cascade delete behavior which trigger gets createdAns ) PRE-DELETE168 Which Trigger fires when an operator double clicks on a image itemAns ) WHEN_IMAGE_ACTIVATED169 The data type of an image item is ans ) BLOB170 The default window name is ans ) window1171 What needed to create for making a master/detail report Ans) Data link

Page 11: Collections, Cursors, Bulk Binds and FORALL

172 A group of radio buttons are placed under the item ans ) Radio Group173 An operator cannot navigate to a ans) Display item174 The Default text label of alert button1 is ans) OK175 The LOV can be attached to a text Item at runtime by the built inAns) SET_LOV_PROPERTY176 The on_clear_detail and On_ populate_deatails triggers are used withAns ) ISOLATED operations177 Which Symbol is used for lexical parameter Ans) &178 What are called trigger time ans) before and after179 In oracle any object name it should start with and it should not exceed charactersAns ) character and 30180 Which one of the following is applicable on INSTEAD OF TriggersAns ) complex views181 Restriction on triggers can be achieved using ans ) where clause182 Within a FOR LOOP, which variable cannot be changed by the userAns ) Index Variable183 Which Cursor is created by any SQL statement ans ) implicit184 Which clause within Cursor exclusively locks the rows returned by the queryAns ) For update185 Which Exceptions are internally defined by runtime system ans ) Pre defined186 Which option is used with the create command to modify an existing named pl/sql block ans ) replace187 Minimum privilege required to connect to oracle database is ans ) connect188 How to call a procedure from a PL/SQL block ans ) Using procedure name189 Which attribute provides a record type that represents a row in a tableAns )% row190 For iteration to proceed downwards from upper bound to lower bound we can use the optional keyword in a for loop ans ) reverse191 if PL/SQL runs out of memory, then, what predefined exception is raisedAns ) Storage_error192 which exception is used when all exceptions are to be trappedans ) when others193 The conditions can be given at which clause for grouped resultAns ) Group by194 Joining a table to itself is called ans ) self join195 If inner query in sub query returns more than one row then which operator is used

Page 12: Collections, Cursors, Bulk Binds and FORALL

Ans ) IN196 The dual table contains column and row. Ans) single & single197 Which option is used to grant privileges to all users Ans) Public198 Which pseudo column used to refer to a sequenceAns ) Curval & Nextval199 Which level locks are not released by rolling back to save point ans) rowlevel200 which function is used for opening a file ans) fopen201 The procedure reads a line from the file ans) get_line202 The colon symbol is used for parameter ans) bind203 In the radio button property which value is must ans) initial204 Which function is used to find out whether the runtime query record group is return rows or notAns ) populate_group_with_query and populate_group205 :system.currentitem is going return ans ) Name206 The default item type is ans) text207 The display status of a check box is ans) checked, Unchecked208 Which trigger performs an action whenever a record is cleared or deletedAns ) when_remove_record209 Which trigger is associated with a button item ans) when_button_pressed210 setting which property to Yes, a LOV is displayed as soon as the user enters an item ans ) auto refresh211 The block coordination has deferred and ans) Auto query212 The value of what parameter being passed to a called product is always the name of a record group defined in the current form ans) Data_parameter213 Which built-in will call another form within a form ans) call_form214 At least one must be assigned to each window ans) canvas215 built-in is used to display a window at runtime ans) show_window216 An executable menu module file has the extension ans ) mmx217 type of menu items are not require PL/SQL code ans ) Magic & Separator218 built-in is used to call a report from a form ans ) SRW.Run_product219 what is the default value of date ans ) $$date$$220 which system variable we can assign value ans ) system.date_thershold221 what parameter is required to create group function ans ) Record groupname222 which style has to be selected for making master/detail report ans ) group above223 built-in is used to call report within a report ans ) srw.run_report224 In show_editor procedure which are optional parameters ans) X and Y225 Which trigger is associated with a list item ans) when_list_changed

Page 13: Collections, Cursors, Bulk Binds and FORALL

226 which procedure is used to changed the size of image ans ) Image_zoom227 which function is used to create dynamic query record groupans ) populate_group_with_query228 Maximum number of buttons that can be defined in an alert is ans ) 3229 How many types of menu items are there in menu module ans) 5230 How many arguments are required in add_group_column ans) 4231 How many arguments are required in set_alert_button_property ans) 4

SCM Tables (O2C)

 1. OE_ORDER_HEADERS_ALL2. OE_ORDER_LINES_ALL3. WSH_DELIVERY_DETAILS4. WSH_DELIVERY_ASSIGNMENTS5. WSH_NEW-DELIVERIES6. WSH_DELIVERY_LEGS7. WSH_TRIP_STOPS8. WSH_TRIPS9. M TL_TRX_REQUEST_LINES10. MTL_MATERIAL_TRANSACTION_TEMP11. OE_SETS12. OE_LINE_SETS13. OE_LINES_ALL14. MTL_RESERVATIONS

Collections, Cursors, Bulk Binds and FORALL

Once in a while, I read something about Oracle that stops me in my tracks and makes me really think about how I approach my job. Recent examples include starting to work with 9iAS, and slowly becoming aware of how much I'm going to have to get my head around the role Java and middleware is going to have in future Oracle applications. Another was when I began studying for my OCP, and began to understand how, for any system to be effective, you need to really have a good understanding of how Oracle works internally. The latest example came about from reading a recent thread started by Daniel Morgan on comp.databases.oracle.server.

The initial posting asked the question:

Page 14: Collections, Cursors, Bulk Binds and FORALL

"At a class I taught this last weekend I brought up the fact that most PL/SQL programmers are still writing v7 code. I gave everyone there a challenge and thought I'd share it with the group for any of you looking for a challenge on which to sharpen your skills.

CREATE TABLE t1 ASSELECT *FROM all_objectsWHERE 1=0;

CREATE OR REPLACE PROCEDURE test_proc IS

BEGIN    FOR x IN (SELECT * FROM all_objects)    LOOP        INSERT INTO t1        (owner, object_name, subobject_name, object_id,        data_object_id, object_type, created, last_ddl_time,        timestamp, status, temporary, generated, secondary)        VALUES        (x.owner, x.object_name, x.subobject_name, x.object_id,        x.data_object_id, x.object_type, x.created,        x.last_ddl_time, x.timestamp, x.status, x.temporary,        x.generated, x.secondary);    END LOOP;COMMIT;END test_proc;/

set timing onexec test_proc;set timing off

Everyone using 8i+ features should be able to improve the performance ofthis by at least 5X.

I'll post a solution in a week or so."

The bit that hit home was the comment about most PL/SQL programmers still writing v7 code. Thinking about it, that's one I'm guilty of.

The sort of work I do involves knowing as much as possible about as many Oracle products as possible. One week I'm tuning up a Discoverer installation, next week I'm building a data model for a first-phase data warehouse. Large parts of my work involve working out which Oracle products are best suited to a potential application, and the nature of the job is that you thoroughly learn something for a particular project, then

Page 15: Collections, Cursors, Bulk Binds and FORALL

move on and rely on that knowledge for some time afterwards. On average, I usually know more about a particular Oracle product than most people, but I'm the first to admit that I'm no expert and there's always room to learn.

As Daniel Morgan points out, PL/SQL has come on considerably since version 2.3 that came with Oracle 7. One of the major areas of improvement has been in the area of arrays and PL/SQL Tables, and in fact this area is now referred to in Oracle 8i, 9i and now 10g as 'Collections'. Together with the way cursors are now handled, there's now much more efficient ways of bulk processing large arrays of data, and it's worth taking some time out to look at how things have developed.

Going back to the original thread, and discarding the approach of just using a straight insert (*/ append */)  into ... select ... from all_objects (which of course would be the fastest, as it's just doing the insert using a straight SQL set operation) , the answer as provided by Daniel was as follows;

"I was thinking in terms of some variation on the following:

CREATE OR REPLACE PROCEDURE fast_proc (p_array_size IN PLS_INTEGER DEFAULT 100)IS

TYPE ARRAY IS TABLE OF all_objects%ROWTYPE;l_data ARRAY;

CURSOR c ISSELECT *FROM all_objects;

BEGIN    OPEN c;    LOOP    FETCH c BULK COLLECT INTO l_data LIMIT p_array_size;

    FORALL i IN 1..l_data.COUNT    INSERT INTO t2 VALUES l_data(i);

    EXIT WHEN c%NOTFOUND;    END LOOP;    CLOSE c;END fast_proc;/

of which many possibilities exist. One of which Billy V posted. The point I would hope more junior developers take away from this is that while cursors definitely have their

Page 16: Collections, Cursors, Bulk Binds and FORALL

uses ... they should not be the first thing one thinks of any more. Ok ... shouldn't be the first thing after the 'obvious' DML statement."

Another solution proposed by Billy Verreynne was even more compact, and gave a threefold increase in performance.

"My attempt gives me a 3x improvement in performance....

SQL> create or replace procedure fast_proc is2         type TObjectTable is table of ALL_OBJECTS%ROWTYPE;3         ObjectTable$ TObjectTable;4         begin5         select6                     * BULK COLLECT INTO ObjectTable$7         from ALL_OBJECTS;89         forall x in ObjectTable$.First..ObjectTable$.Last10       insert into t1 values ObjectTable$(x) ;11       end;12 /

Procedure created."

So, what are the new features that the two solutions are using, and why do they give such an increase in performance? I decided to take a bit of time out and do some more studying.

Collections

Oracle uses collections in PL/SQL the same way other languages use arrays. Oracle provides three basic collections, each with an assortment of methods.

Index-By Tables Nested Table Collections Varray Collections Collection Methods

Index-By Tables

The first type of collection is known as index-by tables. These behave in the same way as arrays except that have no upper bounds, allowing them to constantly extend. As the name implies, the collection is indexed using BINARY_INTEGER values, which do not need

Page 17: Collections, Cursors, Bulk Binds and FORALL

to be consecutive. The collection is extended by assigning values to an element using an index value that does not currently exist.

SET SERVEROUTPUT ON SIZE 1000000DECLARE TYPE table_type IS TABLE OF NUMBER(10) INDEX BY BINARY_INTEGER; v_tab table_type; v_idx NUMBER;BEGIN -- Initialise the collection. << load_loop >> FOR i IN 1 .. 5 LOOP v_tab(i) := i; END LOOP load_loop; -- Delete the third item of the collection. v_tab.DELETE(3); -- Traverse sparse collection v_idx := v_tab.FIRST; << display_loop >> WHILE v_idx IS NOT NULL LOOP DBMS_OUTPUT.PUT_LINE('The number ' || v_tab(v_idx)); v_idx := v_tab.NEXT(v_idx); END LOOP display_loop;END;/

The number 1The number 2The number 4The number 5

PL/SQL procedure successfully completed.

SQL>

Nested Table Collections

Nested table collections are an extension of the index-by tables. The main difference between the two is that nested tables can be stored in a database column but index-by tables cannot. In addition some DML operations are possible on nested tables when they are stored in the database. During creation the collection must be dense, having consecutive subscripts for the elements. Once created elements can be deleted using the DELETE method to make the collection sparse. The NEXT method overcomes the problems of traversing sparse collections.

SET SERVEROUTPUT ON SIZE 1000000DECLARE TYPE table_type IS TABLE OF NUMBER(10); v_tab table_type;

Page 18: Collections, Cursors, Bulk Binds and FORALL

v_idx NUMBER;BEGIN

-- Initialise the collection with two values. v_tab := table_type(1, 2);

-- Extend the collection with extra values. << load_loop >> FOR i IN 3 .. 5 LOOP v_tab.extend; v_tab(v_tab.last) := i; END LOOP load_loop; -- Delete the third item of the collection. v_tab.DELETE(3); -- Traverse sparse collection v_idx := v_tab.FIRST; << display_loop >> WHILE v_idx IS NOT NULL LOOP DBMS_OUTPUT.PUT_LINE('The number ' || v_tab(v_idx)); v_idx := v_tab.NEXT(v_idx); END LOOP display_loop;END;/

The number 1The number 2The number 4The number 5

PL/SQL procedure successfully completed.

SQL>

Varray Collections

A VARRAY is similar to a nested table except you must specifiy an upper bound in the declaration. Like nested tables they can be stored in the database, but unlike nested tables individual elements cannot be deleted so they remain dense.

SET SERVEROUTPUT ON SIZE 1000000DECLARE TYPE table_type IS VARRAY(5) OF NUMBER(10); v_tab table_type; v_idx NUMBER;BEGIN -- Initialise the collection with two values. v_tab := table_type(1, 2);

-- Extend the collection with extra values. << load_loop >> FOR i IN 3 .. 5 LOOP v_tab.extend; v_tab(v_tab.last) := i;

Page 19: Collections, Cursors, Bulk Binds and FORALL

END LOOP load_loop; -- Can't delete from a VARRAY. -- v_tab.DELETE(3);

-- Traverse collection v_idx := v_tab.FIRST; << display_loop >> WHILE v_idx IS NOT NULL LOOP DBMS_OUTPUT.PUT_LINE('The number ' || v_tab(v_idx)); v_idx := v_tab.NEXT(v_idx); END LOOP display_loop;END;/

The number 1The number 2The number 3The number 4The number 5

PL/SQL procedure successfully completed.

SQL>

Extending the load_loop to 3..6 attempts to extend the VARRAY beyond it's limit of 5 elements resulting in the following error.

DECLARE*ERROR at line 1:ORA-06532: Subscript outside of limitORA-06512: at line 12

Collection Methods

A variety of methods exist for collections, but not all are relevant for every collection type.

EXISTS(n) - Returns TRUE if the specified element exists. COUNT - Returns the number of elements in the collection. LIMIT - Returns the maximum number of elements for a VARRAY, or NULL for

nested tables. FIRST - Returns the index of the first element in the collection. LAST - Returns the index of the last element in the collection. PRIOR(n) - Returns the index of the element prior to the specified element. NEXT(n) - Returns the index of the next element after the specified element. EXTEND - Appends a single null element to the collection. EXTEND(n) - Appends n null elements to the collection. EXTEND(n1,n2) - Appends n1 copies of the n2th element to the collection. TRIM - Removes a single element from the end of the collection.

Page 20: Collections, Cursors, Bulk Binds and FORALL

TRIM(n) - Removes n elements from the end of the collection. DELETE - Removess all elements from the collection. DELETE(n) - Removes element n from the collection. DELETE(n1,n2) - Removes all elements from n1 to n2 from the collection.