Chapter Twenty One Collection Data Type Objective: – Composite Data Structures – Introduction of Records – Introduction of Collections – Application of.

Slides:



Advertisements
Similar presentations
Oracle Object-Relational Model. - Structures : tables, views, indexes, etc. - Operations : actions that manipulate data stored in structures - Integrity.
Advertisements

BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
SQL Objects and PL/SQL. Who am I ?  Gary Myers  Oracle developer since 1994  Database Consultant with SMS M&T  Blogger since 2004 Now at blog.sydoracle.com.
Chapter 6 Type Checking. The compiler should report an error if an operator is applied to an incompatible operand. Type checking can be performed without.
Procedure and Functions. Procedures Syntax: [CREATE [OR REPLACE]] PROCEDURE Pname [(p1, p2…)][IS | AS] [declarations] BEGIN [Execution Statements] [EXCEPTIONS.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Chapter 4B: More Advanced PL/SQL Programming
Introduction to PL/SQL
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Objectives Why PL-SQL ? Language features
PL/SQL Bulk Collections in Oracle 9i and 10g Kent Crotty Burleson Consulting October 13, 2006.
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
SQL Training Procedures & Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. DB Procedures & Functions Procedures and Functions.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
SAGE Computing Services Customised Oracle Training Workshops and Consulting Are you making the most of PL/SQL? Hints and tricks and things you may have.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 11 Introduction to Dynamic SQL and Object Technology.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
6 Copyright © 2009, Oracle. All rights reserved. Working with Composite Data Types.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
Program with PL/SQL Lesson 5. Working with Composite Data Types.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
PL/SQL A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
L/O/G/O Working with Composite Data Types. Objectives After completing this lesson, you should be able to do the following: –Create user-defined PL/SQL.
LECTURE 1 INTRODUCTION TO PL/SQL Tasneem Ghnaimat.
Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Oracle 8i PL/SQL Collections. Collections A Collection is a group of elements of the same kind There are three types of Collections that you can use in.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Collections Oracle Database PL/SQL 10g Programming Chapter 6.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 3 Handling Data in PL/SQL Blocks.
Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Oracle10g Developer: PL/SQL Programming1 Objectives SQL queries within PL/SQL Host or bind variables The %TYPE attribute Include queries and control structures.
Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Copyright  Oracle Corporation, All rights reserved. 20 Working with Composite Datatypes.
6 Copyright © 2004, Oracle. All rights reserved. Working with Composite Data Types.
Oracle 9i Collections. Composite types Several variables as single unit ◦ Records  Different datatype variables are combined here  Ex: All fields of.
Database An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL Definition: PL/SQL.
Composite data types_ PL/SQL table. Composite data types PL/SQL provides three composite data types : TABLE, ROCORD, and VARRAY. Objects of type TABLE.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
Matt Owen Cuesta College. Writing maintainable code Data structures Custom exceptions Design patterns and frameworks Unit Testing Test.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Object-Oriented Features in DBMS Chengyu Sun California State University, Los Angeles.
Preface IIntroduction Course Objectives I-2 Oracle Complete Solution I-3 Course Agenda I-4 Tables Used in This Course I-5 The Order Entry Schema I-6 The.
PLSQL Cont…. Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Collection in PL/SQL.
PL/SQL MULTIPLE CHOICE QUESTION.
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Chapter Eighteen Cursors
Working with Composite Datatypes
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Topics Sequences Introduction to Lists List Slicing
Chapter 8 Advanced SQL.
Topics Sequences Introduction to Lists List Slicing
Database Programming Using Oracle 11g
Presentation transcript:

Chapter Twenty One Collection Data Type Objective: – Composite Data Structures – Introduction of Records – Introduction of Collections – Application of Records & Collections – Bulk Collections

2 Predefined Data Types A.Scalar Type B.Composite Types 1.Records 2.Collections a.Index_by tables b.Nested tables c.VARRAY

3 Advantages of Records Data Abstraction Aggregate Operations Produce less lines of code Reusable

4 Records Facts –Records are similar to 3GL –Records are not the same as rows in a db –We can retrieve a row of data from a db table into a record –You can use %ROWTYPE to declare a record that represents a row in a db table

5 Types of Declaring Records I.User defined record II.Table-based record III.Cursor-based record

6 I- User-Defined Records Syntax: TYPE record_type IS RECORD (field1 type [NOT NULL] [:=expr1], field2 type [NOT NULL] [:=expr2], ……. ); Where type: - Scalar - Subtype - %TYPE - %ROWTYPE - Collection TYPE - REF Cursor

7 II- Table-Based Records DECLARE AddressRecordAddress%ROWTYPE; YourAddressAddressRecord;

8 III- Cursor-Based Records DECLARE CURSORAddressCursorIS SELECT * FROM Address WHERE Name LIKE ‘%SMITH’; MyAddressCursor AddressCursor%ROWTYPE;

9 DECLARE TYPE AddressType AS RECORD (NameStudent.Name%Type, NoNUMBER := 1, StreetVARCHAR2(50), CityVARCHAR2(25), StateCHAR(2), ZipNUMBER(5) NOT NULL :=21502 ); MyAddressAddressType; FSUAddressAddressType; BEGIN MyAddress.City :=‘Frostburg’; FSUAddress.City :=MyAddress.City; END; User Defined Record (continued)

10 BEGIN SELECTName, No, St, City, State, Zip INTOMyAddress FROMStudent WHEREName LIKE &Name; INSERT INTO tempRec(Name,State,Zip,Date) VALUES (MyAddress.Name, MyAddress.State, MyAddress.Zip,SYSDATE); END; Move Data Into a Record (continued)

11 Facts About Records You can copy contents of compatible records to another record MyAddress := FSUAddress; You can assign NULL value to a record MyAddress := NULL; You can pass the record as an argument in a subprogram You can return a record back by a function

12 Fact About Records You CAN NOT use IS NULL You can not compare two records You can not insert a record in a database (Prior to Oracle 9i Release 2)

13 Access the Record Files [SchemaName.][PackageName.]RecordName.fieldName MyAddress.State := ‘VA’; FSUAddress.State := ‘MD’; IF MyAddress.State = FSUAddress.State THEN ….. IF MyAddress.State IS NULL THEN ….

14 Function Returning a Record FUNCTION StudentRegistration( ) RETURN AddressType IS fhs AddressType ; BEGIN ….. Return fhs; END StudentRegistration ;

15 Making a Record Null MyAddressAddressType; FSUAddressAddressType; BEGIN MyAddress.Name := UPPER(‘SMITH’); MyAddress.No := 111; MyAddress.St := ‘Main’; MyAddress := FSUAddress;

16 DECLARE TYPE AddressType AS RECORD (NoNUMBER, StreetVARCHAR2(50), CityVARCHAR2(25), StateCHAR(2), ZipNUMBER NOT NULL :=1111); TYPEStudent AS RECORD (NameVARCHAR2(49), AddressAddressType); S1Student; Nested Record (Composite Types)

17 Application of Records

18 Practice A phone number is made up of these components: Example Area Code 301 Prefix687 Number4787 Each Emergency staff has the following numbers at which s/he can be reached : Home phone Office phone Cell phone Fax a.Create a nested record TYPE to support this description. b.Assign the following data to the home phone number of the record. Name:John Smith Home phone:

19 Predefined Datatypes (Composite Types) 2.Collections: An ordered group of elements of same type I.Index_by table: (Associative Arrays in Oracle 9i and after) II.Nested table: III.Varray:

20 Ways to Define Collections 1.CREATE TYPE: CREATE OR REPLACE TYPE name is VARRAY(10) of NUMBER; 2.TYPE: TYPE name IS TABLE of NUMBER INDEX BY VARCHAR2(10); TYPE name IS TABLE of NUMBER; TYPE name is VARRAY(10) of NUMBER;

21 For Lookup elements. Designed to use a Key (a unique value); To give an array access to rows Must contain two components. Key of data type BINARY_INTEGER or VARCHAR2(size) or PLS_INTEGER (use as index) Column of, a scalar or record data type Can increase dynamically 2-I. Index_by Table (Association Array)

22 Example DECLARE TYPE population is TABLE OF NUMBER INDEX BY VARCHAR2(2); state population; HowMany NUMBER; BEGIN state(‘MD’) := 2,000; state(‘VA’) := 4,000; state(‘WV’):= 1,000; state(‘MD’): = 2,500;--new value HowMany := state(‘WV’); END;

23 Syntax: TYPE name IS TABLE OF Element_Type [NOT NULL] INDEX BY [BINARY_INTEGER | PLS_INTEGER | VARCHAR2 (MaxSize)]; Index_by Table

24 EXAMPLE: TYPE Key IS TABLE OF Student.ID%TYPE INDEX BY BINARY_INTEGER; TYPE KeyList IS TABLE OF Student%ROWTYPE NOT NULL INDEX BY BINARY_INTEGER; TYPE KeyName IS TABLE OF Student%ROWTYPE INDEX BY VARCHAR2(20);

25 Index_by Table Initially Sparse Example DECLARE TYPE facultyTYPE is TABLE OF faculty%ROWTYPE INDEX BY BINARY_INTEGER; facfacultyTYPE; BEGIN SELECT * INTO fac(1111)--use PK as an index FROM faculty WHERE ID = 1111; END;

26 Example: DECLARE TYPEMyTable IS TABLE OF VARCHAR2(10) INDEX BY BINARY_INTEGER; StudentTableMyTable; TempNUMBER; BEGIN StudentTable (-10) := ‘cosc300’; StudentTable (25) := ‘cosc310’; StudentTable (3) := ‘cosc360’; StudentTable (50) := ‘cosc340’; StudentTable (33) := ‘cosc380’; DBMS_OUTPUT.PUT_LINE( StudentTable.COUNT); END; Index_by Table

27 StudentTable (-10) := ‘cosc300’; StudentTable (25) := ‘cosc310’; StudentTable (3) := ‘cosc360’; StudentTable (50) := ‘cosc340’; StudentTable (33) := ‘cosc380’; Index_by Table KeyValue -10cosc300 25cosc310 3cosc360 50cosc340 33cosc380

28 Index_by Table DECLARE TYPE AddressTab is TABLE OF Address%ROWTYPE INDEX BY BINARY_INTEGER; myAddressAddressTab; BEGIN SELECT * INTO myAddress(10) FROM Address WHERE Name LIKE UPPER (’Mark’); myAddress(11).Name := ‘Clark’; myAddress(11).State := ‘MD’;

29 2-II. Nested Tables Syntax: TYPEname IS TABLE OF elementType [NOT NULL]; If you use CREATE TYPE elementType can NOT be: BINARY_INTEGERLONG PLS_INTEGERLONGROW BOOLEANNATURAL STRINGNATURALN POSITIVENCHAR REF CURSOR*

30 Nested Tables DECLARE TYPE NumTab IS TABLE OF NUMBER; T0 NumTab;-- Null Table T1 NumTab := NumTab(-2); T2 NumTab := NumTab(2,4,6,10); T3 NumTab := NumTab();-- Table with no element BEGIN T0(1) := 12;--Illegal - Collection is null T1(1) = 124; T2(5) = 16;-- Illegal - EXTEND FOR I IN 1..4 LOOP DBMS_OUTPUT.PUT(T2(1) || ‘ ‘); END LOOP DBMS_OUTPUT.NEW_LINE; END;

31 Initializing Nested Tables CREATE TYPEMyTable as TABLE of CHAR(7); DECLARE CourseList MyTable; BEGIN - - Use Constructor MyTable( ) CourseList:=MyTable(‘Math100’,’Math200’,’Cosc470’); CourseList:= MyTable(‘MATH100’, NULL, ‘COSC470’); END;

32 Initializing Nested Tables -- Initialize at Declaration DECLARE COURSELIST MyTABLE := MyTABLE(‘MATH100’,’MATH200’,’COSC470’); BEGIN. END;

33 Nested Tables CREATE TYPE Course_TY AS OBJECT ( C_NoCHAR(7), C_NameVARCHAR2(10), CrNUMBER(1)); CREATE TYPE C_List_NT AS TABLE OF Course_TY; CREATE TABLE Student_Course ( NameVARCHAR2(30), IDNUMBER(10), ListC_List_NT) NESTED TABLE List STORE AS List_NT_TAB; (continued)

34 Nested Tables BEGIN INSERT INTO Student_Course VALUES (‘Mary’, 1111, C_List(Course_TY(‘Cosc100’, ‘Intro to COSC’, 3), Course_TY(‘COSC200’, ‘Intro to programming’, 3)); INSERT INTO Student_Course VALUES (‘Mark’, 222, C_List(Course_TY(…), …);

35 2-III. VARRAY Variable length array Similar to Java array Fixed upper bound Use sequential number as subscripts Lower bound is 1

36 VARRAY Syntax CREATE [OR REPLACE] TYPE name AS | IS VARRAY (MaxSize) OF elementType [NOT NULL]; TYPE name IS | AS VARRAY (MaxSize) OF elementType [NOT NULL];

37 VARRAY DECLARE TYPE NumArr IS VARRAY(10) OF NUMBER(2); TYPE AddressArr IS VARRAY(10) OF Address%ROWTYPE; TYPE calender IS VARRAY(366) OF DATE; V1 NumArr V2AddressArr; V3 calender; BEGIN V1:= NumArr (10,20,30,40,50) --max 10 numbers V3:= calender (SYSDATE); --max 366 END;

38 VARRAY Constructor DECLARE TYPE Colors IS VARRAY(10) OF VARCHAR2(10); Rainbow Colors; BEGIN Rainbow:= Colors (‘Violet’, ’Indigo’, ’Blue’, ‘Green’, ‘Yellow’, ‘Orange’, ‘Red’); END;

39 Empty Constructor DECLARE My_Color Colors; BEGIN My_Color:= Colors(); -- Empty varray IF My_Color IS NULL THEN My_Color(1):= ‘Black’;--illegal END IF; END;

40 Initializing VARRAY CREATE TYPE Stud IS RECORD (NAMEVARCHAR2(20), IDNUMBER(5), GPANUMBER(4,2)); __________________________________________________ CREATE TYPE StudentList AS VARRAY(20) of Stud; DECLARE StudList StudentList; BEGIN -- Pass 3 records to constructor studentList StudentList( Stud(‘John’, ‘11111’, 2.5), Stud(‘Mary’, ‘22222’, 3.0), Stud(‘Mark’, ‘99999’, 4.0) ); END;

41 Initializing VARRAY -- Calling Constructor without argument will create an empty but non-null collection DECLARE TYPE Stud_Va IS VARRAY(20) of student; -- Inititalize to an empty VARRAY GradStudent Stud_Va := Stud_Va(); BEGIN If GradStudent IS NOT NULL THEN --True. End IF; End;

42 Data Compatibility DECLARE TYPE L_Name IS VARRAY(5) OF VARCHAR2(30); TYPE F_Name IS VARRAY(5) OF VARCHAR2(30); Group1 L_Name:= L_Name(‘Smith’, ‘Johnson’, ‘Olson’, ‘Jackson’, ‘Martinez’); Group2 L_Name:= L_Name(‘Lee’, ‘Moo’, ‘Yu’, ‘Hung’, ‘Kim’); Group3 F_Name:= F_Name(‘Mark’, ‘Mary’, ‘Lory’, ‘Sandy’, ‘Judy’); BEGIN Group1:= Group2; Group3:= Group2;-- illegal

43 Application of VARRAY SELECT Dept, C_No, Required FROMClass; DeptC_NoRequired Cosc Cosc Cosc Cosc Cosc Math202100

44 VARRAY TYPE Prerequisite AS VARRAY(10) OF NUMBER(3); CREATE TABLE class( DeptCHAR(4), C_NoNUMBER(3), Requiredprerequisite ); DeptC_NoRequired COSC COSC MATH (continue)

45 VARRAY DECLARE A2 Prerequisite := Prerequisite (100,101,240); BEGIN INSERT INTO Class VALUES (‘COSC’, 240, Prerequisite(100,101)); INSERT INTO Class VALUES (‘COSC’, 241, A2); INSERT INTO Class VALUES (‘MATH’, 202, Prerequisite(100));

46 Select VARRAY Data SELECT Required FROMClass WHEREDept = ‘COSC’ AND C_No = 241; Required A2 (100,101,240)

47 Select VARRAY Data SELECTCOLUMN_VALUE FROMClass, TABLE (Required) ; Required

48 Select VARRAY Data contd… SELECT A.Dept, A.C_No, COLUMN_VALUE FROMClass A, TABLE(Required) ; Dept C_No Required Cosc Cosc Cosc Cosc Cosc Math

49 Methods For Collection Collection_Name.Method_Name[(paramters)] -Cannot be called from SQL -Functions: EXISTS, COUNT, FIRST, LAST, NEXT, PRIOR, LIMIT -Procedures: EXTEND, TRIM, DELETE

50 COUNT -- Returns Number of elements in a Collection Temp :=StudentTable.COUNT; For I In 1..Temp Loop EXISTS(n) -- If the n th element exists RETURN TRUE IF StudentTable.EXISTS(3) THEN …… LIMIT-- Max size of VARRAY Num := StudentTable.LIMIT; FIRST-- Returns the 1 st Index number* Temp1:= StudentTable.FIRST; LAST-- Returns the last Index* Temp2:= StudentTable.LAST; *Out of range subscript will not raise flag but returns FALSE Methods for Collection (continued)

51 NEXT(n)--Returns the successor of index n. (in empty collection: FIRST, LAST are NULL) Temp:= StudentTable.NEXT(5); PRIOR(n)--Returns the predecessor of index n. For I In temp1..Temp2 Loop Temp:= StudentTable.PRIOR(5); * EXTEND/EXTEND(n)/EXTEND(n,i) --Add an element(s) to the collection * TRIM/TRIM(n) -- Remove an element from the end of the collection * Cannot be used with INDEX_BY TABLE Methods for Collection (continued)

52 Note If you declare a Nested Table with 5 elements Then delete 2 and 5 - internal size is 5 - COUNT is 3 - LAST is 4 XX

53 Example DECLARE TYPE List IS TABLE OF NUMBER; LList:= List(2,4,6,8); counter INTEGER; BEGIN L.DELETE(2); --deletes 4 (the 2 nd element) counter:= L.FIRST; WHILE counter IS NOT NULL LOOP DBMS_OUTPUT.PUT_LINE(‘Element’|| counter|| ‘is’|| L(counter)); counter:= L.NEXT(counter); END LOOP; END; --PRACTICE: Run this loop in reverse

54 Set Operation DECLARE TYPE A IS TABLE OF NUMBER; n1A:= A(1,2,3); n2A:= A(3,2,1); n3A:= A(2,4,6); n4A:= A(1,3); n5A:= A(3,2,1,2); nA; BBOOLEAN; BEGIN n:= n1MULTISET UNION n2; --(1,2,3,3,2,1) n:= n1MULTISET UNION DISTINCT n3; --(1,2,3,4,6) n:= n1MULTISET INTERSECT n4;--(1,3) n:= SET(n1); --(1,2,3) n:= n2MULTISET EXCEPT n4; --(2) B:= n5IS A SET; --false B:= n5IS NOT A SET; --true B:= n5IS EMPTY; --false B:= 4MEMBER OF n4; --false B:= n4IN(n3, n2, n1); --true B:= n4SUBMULTISET OF n1; --true END;

55 Comparing the Collections DECLARE TYPE color IS TABLE OF VARCHAR2(10); P1 color:= color(‘Black’, ‘Blue’, ‘Red’); P2 color:= color(‘Red’, ‘Blue’, ‘Black’); P3 color:= color(‘Red’, ‘Blue’, ‘Green’); BEGIN IF P1 = P2 THEN …. IF P1 P2 THEN ….

56 DELETE DELETE(i) DELETE(i,j) StudentTable.DELETE(3); StudentTable.DELETE(10,33); StudentTable.DELETE; StudentTable.DELETE(4,1); -- does nothing *if i is NULL, DELETE (i) does nothing *DELETE does not work with VARRAYS Methods for Collection (continued)

57 CREATE TYPE colorsType AS VARRAY(10) OF VARCHAR2(8); / CREATE TABLE color (No NUMBER, colors colorsType); BEGIN INSERT INTO color VALUES(1, ‘Red’, ‘Orange’, ‘Yellow’); INSERT INTO color VALUES(2, ‘Blue’, ‘Green’); COMMIT; END; / DECLARE New_Color ColorsType := ColorsType(‘Purple’, ‘Black’); My_Color New_Color; BEGIN UPDATE Color SETColors = New_Color WHERE No = 2; COMMIT; SELECTColors INTOMy_Color WHERENo = 1; END; / INSERT, UPDATE, SELECT

58 Difference between Tables and Arrays 1. Arrays have a fixed upper bound 2 a. Array elements are consecutive 2 b. Tables are initially dense; but we can delete elements from a table (sparse)

59 Nested TABLE vs. VARRAY 1. VARRAYs have a max size 2. VARRAYs are always dense 3 a. Oracle stores VARRAY data in_line(in the same table) 3 b. Oracle stores Table data offline 4 a. VARRAYs keep their order & subscription when they are stored in a db 4 b. Not the case for tables 5. VARRAY index values are consecutive

60 Collections Collections cannot appear in a: –DISTINCT –GROUP BY –ORDER BY

61 Drop, Create, & Replace Nested Table & VARRAY TYPE DROPTYPETypeName [FORCE]; CREATE [or REPLACE] TYPE TypeName AS | IS TABLE OF elementType [NOT NULL]; CREATE [or REPLACE] TYPE TypeName AS | IS VARRAY (MaxSize) OF elementType [NOT NULL];

62 Applications of Collections Collection as component of Record Collection as Program Parameters Collection as Return Value of a function Collection as a Column in Database Table (only in Nested Array & VARRAY)

63 Random Access Improve lookup performance Capture data for special processing (non-static) so the process would be fast Advantages of Collection

64 Collection Exception COLLECTION_IS_NULL --try to operate on a null collection NO_DATA_FOUND --an element does not exist in INDEX BY SUBSCRIPT_BEYOND_COUNT --subscript exceeds the number of elements in the collection SUBSCRIPT_OUTSIDE_LIMIT --subscript is outside the range VALUE_ERROR –subscript is null or not convertible to the key

65 BULK COLLECT BC can retrieve multiple rows of data Reduce Number of context switches between the PL/SQL & SQL Reduce the overhead of data retrieval

66 BULK COLLECT DECLARE TYPE n IS TABLE OF Student.ID%TYPE; TYPE m IS TABLE OF Student.Major%TYPE; an; bm; CURSOR Temp IS SELECT ID, Major FROM Student WHERE Dept=‘COSC’;

67 BULK COLLECT BEGIN Open Temp; FETCH Temp BULK COLLECT INTO a, b; CLOSE Temp; END;

68 BULK COLLECT DECLARE TYPE T_Number IS TABLE OF Temp_Table.ID%TYPE; TYPE T_String IS TABLE OF Temp_Table.Major%TYPE; V_Num T_Number:=T_Number(1); V_String T_String := T_String(1); CURSOR Temp IS SELECT Major FROM Temp_Table WHERE ID > 1111 ORDER BY ID;

69 BULK COLLECT BEGIN V_Num.EXTEND(1000); V_String.EXTEND(1000); -- Load data into Temp_Table SELECTID, Major FROM Temp_Table BULK COLLECT INTO V_Num, V_String ORDER BY ID; END;

70 Implicit Cursor INSERT DELETE UPDATE SELECT INTO DECLARE afaculty%ROWTYPE; BEGIN SELECT * INTOa FROMfaculty WHEREID = 1111; END;