Download presentation
Presentation is loading. Please wait.
Published byIsaac Poole Modified over 9 years ago
1
Chapter Twenty One Collection Data Type Objective: – Composite Data Structures – Introduction of Records – Introduction of Collections – Application of Records & Collections – Bulk Collections
2
2 Predefined Data Types A.Scalar Type B.Composite Types 1.Records 2.Collections a.Index_by tables b.Nested tables c.VARRAY
3
3 Advantages of Records Data Abstraction Aggregate Operations Produce less lines of code Reusable
4
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
5 Types of Declaring Records I.User defined record II.Table-based record III.Cursor-based record
6
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
7 II- Table-Based Records DECLARE AddressRecordAddress%ROWTYPE; YourAddressAddressRecord;
8
8 III- Cursor-Based Records DECLARE CURSORAddressCursorIS SELECT * FROM Address WHERE Name LIKE ‘%SMITH’; MyAddressCursor AddressCursor%ROWTYPE;
9
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
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
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
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
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
14 Function Returning a Record FUNCTION StudentRegistration( ) RETURN AddressType IS fhs AddressType ; BEGIN ….. Return fhs; END StudentRegistration ;
15
15 Making a Record Null MyAddressAddressType; FSUAddressAddressType; BEGIN MyAddress.Name := UPPER(‘SMITH’); MyAddress.No := 111; MyAddress.St := ‘Main’; MyAddress := FSUAddress;
16
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
17 Application of Records
18
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:301-777-7777
19
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
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
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
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
23 Syntax: TYPE name IS TABLE OF Element_Type [NOT NULL] INDEX BY [BINARY_INTEGER | PLS_INTEGER | VARCHAR2 (MaxSize)]; Index_by Table
24
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
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
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
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
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
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
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
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
32 Initializing Nested Tables -- Initialize at Declaration DECLARE COURSELIST MyTABLE := MyTABLE(‘MATH100’,’MATH200’,’COSC470’); BEGIN. END;
33
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
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
35 2-III. VARRAY Variable length array Similar to Java array Fixed upper bound Use sequential number as subscripts Lower bound is 1
36
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
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
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
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
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
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
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
43 Application of VARRAY SELECT Dept, C_No, Required FROMClass; DeptC_NoRequired Cosc240100 Cosc240101 Cosc241240 Cosc241100 Cosc241101 Math202100
44
44 VARRAY TYPE Prerequisite AS VARRAY(10) OF NUMBER(3); CREATE TABLE class( DeptCHAR(4), C_NoNUMBER(3), Requiredprerequisite ); DeptC_NoRequired COSC240100101 COSC241100101240 MATH202100 (continue)
45
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
46 Select VARRAY Data SELECT Required FROMClass WHEREDept = ‘COSC’ AND C_No = 241; Required A2 (100,101,240)
47
47 Select VARRAY Data SELECTCOLUMN_VALUE FROMClass, TABLE (Required) ; Required 100 101 100 101 240 100
48
48 Select VARRAY Data contd… SELECT A.Dept, A.C_No, COLUMN_VALUE FROMClass A, TABLE(Required) ; Dept C_No Required Cosc 240 100 Cosc 240 101 Cosc 241 100 Cosc 241 101 Cosc 241 240 Math 202 100
49
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
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
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
52 Note 12 34 5 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
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
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
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
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
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
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
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
60 Collections Collections cannot appear in a: –DISTINCT –GROUP BY –ORDER BY
61
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
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
63 Random Access Improve lookup performance Capture data for special processing (non-static) so the process would be fast Advantages of Collection
64
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
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
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
67 BULK COLLECT BEGIN Open Temp; FETCH Temp BULK COLLECT INTO a, b; CLOSE Temp; END;
68
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
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
70 Implicit Cursor INSERT DELETE UPDATE SELECT INTO DECLARE afaculty%ROWTYPE; BEGIN SELECT * INTOa FROMfaculty WHEREID = 1111; END;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.