Está en la página 1de 18

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 elementsevery 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 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 DECLARE 02 -- Associative array indexed by string: 03 04 TYPE ODI_RUNS IS TABLE OF NUMBER -- Associative array type 05 INDEX BY VARCHAR2(64); 06 07 odi_batsman_runs ODI_RUNS; -- Associative array variable 08 i VARCHAR2(64); 09 10 BEGIN 11 -- 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 LOOP 22 DBMS_Output.PUT_LINE ('Total ODI Runs on Jan 2010 by ' || i || ' is ' || 23 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 13082 Total ODI Runs on Jan 2010 by Sachin Tendulkar is 17629 Total 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. 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 DECLARE 02 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 BEGIN 07 v1 := nested_type('Shipping','Sales','Finance','Payroll'); 08 v2 := varray_type(1, 2, 3, 4, 5); -- Up to 5 integers 09 FOR i IN v1.FIRST .. v1.LAST 10 LOOP DBMS_OUTPUT.PUT_LINE('Element #' || i || 'in the nested table = ' || 11 v1(i)); 12 END LOOP; 13 14 FOR j IN v2.FIRST .. v2.LAST 15 LOOP DBMS_OUTPUT.PUT_LINE('Element #' || j || 'in the varray = ' || 16 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.

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 occurs 2. Which constraint type ensures that each row in a table contains an entry that uniquely identifies that row from any other. Ans ) primary key 3. Views can be defined with up to (?) columns. Ans ) 254 4. During database creation, which of the following database users require setting their password? Ans ) sys 5. What is a Cartesian product? Ans )The product of a select statement which has more than one table, and no where clause 6. 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 option 7. The DECODE () function is similar to (?). Ans ) an if then else construct 8. In which section of a PL/SQL block will a user defined exception be handled? Ans ) exception block 9. Which of the following are used to determine the order of an ORDER BY clause? Ans ) ASC 10. 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) COUNT 12. More frequent checkpoints reduce the time needed to (?). Ans ) recover 13. A (?) is an area of memory, given a name, that is used to store a value. Ans ) variable 14. 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 ID 16. 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 ) locks 18. The default length for char data type is Ans ) one 19. The default order in which records are retrieved when an order by clause is

used is Ans ) Ascending 20. The operator precedence between AND & OR is Ans) AND over OR 21. The output of ltrim (\"BILL CLINTON\",BALL) is Ans) ILL CLINTON 22. The output of substr (\"CREATE\",3,3) is Ans) EAT 23. The number of minimum join condition that are required to join n tables is N-1 24. In an outer join (+) sign is placed on the Ans) deficient table side 25. 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 operators 26. If where clause is not specified in an update statement then Ans ) all rows updated 27. The database object from which multiple users may generate unique integer is Ans ) sequence 28. Cluster columns must correspond to columns in each of the cluster tables in Ans ) size and column name 29. The clause in the computer command that helps in computing count of rows is Ans ) number 30. The elements, which are mandatory for a PL/SQL blocks are Ans ) 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 SQL Ans ) data access compatibility 33. 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 is Ans ) exception_unit and raise_application_error 35. Data can be retrieved into variables using which of the following options Ans ) select into and fetch 36. Which of the following does a cursor For Loop do 1. Open a cursor 2. Fetch 3. close cursor Ans) ALL 37. Which statement can appear in a trigger body Ans) SQL set 38. To create a database trigger, the user must have the privilege. Ans ) create trigger privilege 39. Which operator finds common rows from 2 or more different queries? Ans ) intersect 40. Foreign key constraint can be enforced by using constraint. Ans ) references 41. The statement fetches rows from a table to a cursor. Ans) select 42. The NVL() function is used to Ans) substitute a new value 43. The maximum size of LOB is Ans) 4gb 44. How many triggers can create per table Ans) 12 45. Maximum how many constraints can enforce on a single column Ans) four

46. PL/SQL stands for Ans ) procedural language of sql 47. which are the character functions will take string parameter and it will return numeric Ans) length and instr 48. Select trunc(199.99) from dual Ans) 199 49. Which constraint is only a table level Ans) composite primary key 50. Triggers can call in subprograms Ans) yes 51. The NULL columns do not participate in arithmetic computations 52. You cannot create more than one trigger per table. 53. Which Procedure produces output on the screen Ans ) dbms_output.putline() 54. The cursor is created by any SQL statement. Ans) implicit 55 Which triggers are used for views? Ans) instead of triggers 56 select statement is Ans ) DRL 57 trigger is fired Ans ) implicitly 58 A Cartesian product is Ans ) only available in oracle 8i 59 Select empcode, sum(basic) from empmaster? Can you create a view based on the above select? Ans ) no 60 Which of the following correctly describes how to specify a column alias Ans ) Place the alias after each column, separated by white space. 61 The command to open a CURSOR FOR loop is Ans ) No command is required 62 If left out, which would cause an infinite loop Ans) exit 63 After referencing NEXTVAL, the value in CURRVAL of a sequence is Ans ) incremented by 1 64 What control structure prevents more than one user from updating data in a table? Ans ) locks 65 Which of the following two constraints automatically create an index? Ans ) Unique Constraint 66 How many equality conditions are required to join four tables without a Cartesian product? Ans) two 67 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 ) one 69 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() 72 Which of the following is a character function? Ans) to_number() 73 The binary extension for the menu is Ans) .mmb 74 An ER Diagram which relates 2 entities with dark line joining one entity and with crow foot on the other side is called Ans) Many to Many 75 Once defined, how long will a variable remain in SQL*Plus? Ans) Until the session Completes

76 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_found 77 Not Null is which type of constraint? Ans ) check 78 How do you make sure that Oracle will use an Index when you write a select statement? Ans) by selecting columns which have index 79 Forms allows you to manipulate data only if it is Ans) normal mode 80 The different views of objects in object Navigator Ans ) Ownership view and Visual View 81 For undoing changes in the form during design time Ans ) Press CTRL+Z 82 Alert message should not exceed Ans) 200 Characters 83 Data Blocks in the form builder can be classified as Ans ) Master & Detail Block 84 The type of alerts can be set Ans) Note, Caution, Stop 85 The 4 different states of records are as follow ( when internal events of forms run time) Ans ) New, Insert, query, Changed 86 The hierarchy tree of objects in the form application Ans ) Form(Module), Block, record, Item 87 VALIDATE RECORD , Trigger (event) occurs only if the record is Ans) insert 88 LOV (LIST OF VALUES) is a combination of Ans ) Modal dialog Boxes, List and Record Groups 89 The trigger can be classified as the following:Ans ) Smart triggers, Un restricted, Triggers, restricted Triggers 90 The built in procedure to open a form that is independent from calling form is Ans ) open_form 91 The way to involve Report from form object is Ans) run_report_object 92 The is the syntax and place the variable declared in form module to all the triggers in the form Ans ) Declare in PREFOR and the syntax is :Global. 93 A primary key constraint cannot be added on the column of which data type Ans ) long 94 The comprises set of files that protect altered database data that has not been written to data files Ans) redo log 95 Maximum size of raw data type is Ans) 2kb 96 Which one of the following is not applicable on INSTEAD OF Trigger Ans ) Can be applied on tables 97 In Oracle 8, a char database can hold up to Ans) 2000 bytes 98 After creating a sequence, to view the first value we use which keyword Ans ) nextval 99 In PL/SQL assignment operator is replaced using the reserved word Ans) default 100 is a valid pseudo column Ans) rowid, rownum, sysdate, uid, nextval, curval 101 The Index created by the Primary key column is called ans) unique index

102 The operation cannot be performed using views when the view definition includes more than on table Ans) insert 103 The parameter cannot be changed while altering a sequence Ans ) start with n (n cant be changed) 104 To check the source code for the object types use the data dictionary view Ans user_source 105 Which of the following is most restrictive of table level locks? Ans) exclusive lock 106 In PL/SQL block what is the default value of the variable Ans) null 107 Find output of the following ( Select substr( \"christmas\" , 4,3) from dual) Ans ) ist 108 The ability of object to take more than one form is known as Ans ) polymorphism 109 When the user is trying to assign values to the attributes of an uninitialized object, which of the following exception is raised Ans) VALUEERROR 110 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) increment 111 A composite unique key can contain how many number of columns Ans) 16 112 What operations can be performed on sequence Ans) Alter, Select 113 Restriction on triggers can be achieved using what clause Ans) when 114 To check the partition type which data dictionary can be used. Ans ) user_tab_partitions 115 Outer joins retrieves Ans) both matched and unmatched rows 116 A function used to convert a null value to value is Ans) decode 117 Role is Ans ) group of privileges 118 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) outer join 119 The data that stored in the cursor is called as Ans ) active data set 120 what is the format mask for Julian data Ans ) j 121 Label is a word associated with an statements Ans) conditional 122 level locks are not released by rolling back to save point Ans ) row level 123 you can use the CASE function in place of Ans) decode 124 The writes modified blocks from the database buffer cache to the data files Ans ) database writer 125 The magnitude range of a binary integer value in pL/sql is Ans ) -231-1 to 231-1 126 Trigger name should not exceed characters Ans) 30 characters 127 The REF operator returns of the row object Ans) OID 128 PL/SQL is a structured language? Ans ) block structured language 129 Raw types are used to store which type of data Ans ) binary 130 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 insert 131 Sign function returns Ans) +, - and = 132 Syntax of MERGE function Ans) merge into using /<> on when matched these update set when not matched

then insert values 133 The oracle engine provides procedure named that allows programmers to show user defined messages Ans) Raise_Application_Error 134 Which are called as trigger actions Ans) Before and after 135 A function that act on only one value at a time are called as Ans ) Scalar function 136 is used to get cross tabulation & cumulative values ans ) CUBE and ROLLUP 137 Which is used for bulk bind? Ans) for all 138 which is used to modify any operating system files Ans) UTL_File 139 which is used to insert values in to multiple tables using select statements ans ) INSERTALL 140 Which appends on operating system specific line terminator Ans) put_line 141 Which is an object , that is completely contained within another Ans ) embedded object 142 Which of the following is false regarding data files? Ans ) Data files can be associated with two or more table spaces 143 In which data dictionary table the object type information will be stored Ans ) User_Types 144 When you use the THE class in DML statements Ans) Nested table 145 Which is used to store complete column information at a time in to a variable Ans ) bulk collect 146 when you use for update class in a cursor which is compulsory ans ) where current of 147 When cursor is in for loop which operations are not necessary Ans ) Open, Fetch, Close 148 RowID consistes of Ans ) Data file Id, Object Id , Block Id, Row_Sequence_ID 149 What is a object, which can be created only at run time Ans ) Timer 150 what is the extension of .PLL Ans) Programming Link Library 151 what is the extension of object library module Ans) OBL 152 How many styles are there in alert property Ans) three 153 Display item doesnt have which property Ans) navigational 154 When Timer Expired is correspondent to which object Ans) timer 155 When we compare with radio button & push button, push button will not have Ans ) Button value property 156 Which function is used to create runtime record group Ans) create_group 157 which trigger and code is used to run application without connecting to database ans ) on_logon,NULL 158 Form 6i is a ans ) 2 and 3 Tier architecture 159 When we select value from LOV, by default where the value is going to store Ans ) return item 160 LOV always return ans ) boolean value

161 Alert always return ans) number value 162 Which procedure is used to change alert button label Ans ) set_alert_button_properly 163 When we create a LOV automatically created ans ) record group 164 which function is used to create dynamic query record group ans ) create_group_from_query 165 How many types of canvas are there ans ) five 166 Which variable cannot assign a value ans) system 167 When you have cascade delete behavior which trigger gets created Ans ) PRE-DELETE 168 Which Trigger fires when an operator double clicks on a image item Ans ) WHEN_IMAGE_ACTIVATED 169 The data type of an image item is ans ) BLOB 170 The default window name is ans ) window1 171 What needed to create for making a master/detail report Ans) Data link 172 A group of radio buttons are placed under the item ans ) Radio Group 173 An operator cannot navigate to a ans) Display item 174 The Default text label of alert button1 is ans) OK 175 The LOV can be attached to a text Item at runtime by the built in Ans) SET_LOV_PROPERTY 176 The on_clear_detail and On_ populate_deatails triggers are used with Ans ) ISOLATED operations 177 Which Symbol is used for lexical parameter Ans) & 178 What are called trigger time ans) before and after 179 In oracle any object name it should start with and it should not exceed characters Ans ) character and 30 180 Which one of the following is applicable on INSTEAD OF Triggers Ans ) complex views 181 Restriction on triggers can be achieved using ans ) where clause 182 Within a FOR LOOP, which variable cannot be changed by the user Ans ) Index Variable 183 Which Cursor is created by any SQL statement ans ) implicit 184 Which clause within Cursor exclusively locks the rows returned by the query Ans ) For update 185 Which Exceptions are internally defined by runtime system ans ) Pre defined 186 Which option is used with the create command to modify an existing named pl/sql block ans ) replace 187 Minimum privilege required to connect to oracle database is ans ) connect 188 How to call a procedure from a PL/SQL block ans ) Using procedure name 189 Which attribute provides a record type that represents a row in a table Ans )% row 190 For iteration to proceed downwards from upper bound to lower bound we can use the optional keyword in a for loop ans ) reverse 191 if PL/SQL runs out of memory, then, what predefined exception is raised Ans ) Storage_error

192 which exception is used when all exceptions are to be trapped ans ) when others 193 The conditions can be given at which clause for grouped result Ans ) Group by 194 Joining a table to itself is called ans ) self join 195 If inner query in sub query returns more than one row then which operator is used Ans ) IN 196 The dual table contains column and row. Ans) single & single 197 Which option is used to grant privileges to all users Ans) Public 198 Which pseudo column used to refer to a sequence Ans ) Curval & Nextval 199 Which level locks are not released by rolling back to save point ans) rowlevel 200 which function is used for opening a file ans) fopen 201 The procedure reads a line from the file ans) get_line 202 The colon symbol is used for parameter ans) bind 203 In the radio button property which value is must ans) initial 204 Which function is used to find out whether the runtime query record group is return rows or not Ans ) populate_group_with_query and populate_group 205 :system.currentitem is going return ans ) Name 206 The default item type is ans) text 207 The display status of a check box is ans) checked, Unchecked 208 Which trigger performs an action whenever a record is cleared or deleted Ans ) when_remove_record 209 Which trigger is associated with a button item ans) when_button_pressed 210 setting which property to Yes, a LOV is displayed as soon as the user enters an item ans ) auto refresh 211 The block coordination has deferred and ans) Auto query 212 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_parameter 213 Which built-in will call another form within a form ans) call_form 214 At least one must be assigned to each window ans) canvas 215 built-in is used to display a window at runtime ans) show_window 216 An executable menu module file has the extension ans ) mmx 217 type of menu items are not require PL/SQL code ans ) Magic & Separator 218 built-in is used to call a report from a form ans ) SRW.Run_product 219 what is the default value of date ans ) $$date$$ 220 which system variable we can assign value ans ) system.date_thershold 221 what parameter is required to create group function ans ) Record groupname 222 which style has to be selected for making master/detail report ans ) group above 223 built-in is used to call report within a report ans ) srw.run_report 224 In show_editor procedure which are optional parameters ans) X and Y 225 Which trigger is associated with a list item ans) when_list_changed 226 which procedure is used to changed the size of image ans ) Image_zoom

227 which function is used to create dynamic query record group ans ) populate_group_with_query 228 Maximum number of buttons that can be defined in an alert is ans ) 3 229 How many types of menu items are there in menu module ans) 5 230 How many arguments are required in add_group_column ans) 4 231 How many arguments are required in set_alert_button_property ans) 4

SCM Tables (O2C)


1. OE_ORDER_HEADERS_ALL 2. OE_ORDER_LINES_ALL 3. WSH_DELIVERY_DETAILS 4. WSH_DELIVERY_ASSIGNMENTS 5. WSH_NEW-DELIVERIES 6. WSH_DELIVERY_LEGS 7. WSH_TRIP_STOPS 8. WSH_TRIPS 9. M TL_TRX_REQUEST_LINES 10. MTL_MATERIAL_TRANSACTION_TEMP 11. OE_SETS 12. OE_LINE_SETS 13. OE_LINES_ALL 14. 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: "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 AS SELECT * FROM all_objects WHERE 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 on exec test_proc; set timing off Everyone using 8i+ features should be able to improve the performance of this 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 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 IS SELECT * 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 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 is 2 type TObjectTable is table of ALL_OBJECTS%ROWTYPE; 3 ObjectTable$ TObjectTable; 4 begin 5 select 6 * BULK COLLECT INTO ObjectTable$ 7 from ALL_OBJECTS; 8 9 forall x in ObjectTable$.First..ObjectTable$.Last 10 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 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 1000000 DECLARE 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 The The The number number number number 1 2 4 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 1000000 DECLARE TYPE table_type IS TABLE 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; 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 The The The number number number number 1 2 4 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 1000000 DECLARE 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; 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 The The The The number number number number number 1 2 3 4 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 limit ORA-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. 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.

También podría gustarte