0% found this document useful (0 votes)
28 views27 pages

PL12 Collections

Uploaded by

Priyanka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views27 pages

PL12 Collections

Uploaded by

Priyanka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

COLLECTIONS

PL/SQL Collections
• A collection is an ordered group of elements, all of the
same type.
• It is a general concept that encompasses lists, arrays,
and other datatypes used in classic
programming algorithms.
• Each element is identified by a unique subscript that
represents its position in the collection.
• PL/SQL provides three collection types:
– Index-by tables or Associative array
– Nested table
– Variable-size array or Varray
Collections types
• Associative arrays, also known as index-by tables, let you
look up elements using arbitrary numbers and strings for
subscript values. These are similar to hash tables in other
programming languages.
• Nested tables hold an arbitrary number of elements. They
use sequential numbers as subscripts. You can define
equivalent SQL types, allowing nested tables to be stored in
database tables and manipulated through SQL.
• Varrays (short for variable-size arrays) hold a fixed number
of elements (although you can change the number of
elements at runtime). They use sequential numbers as
subscripts. You can define equivalent SQL types, allowing
varrays to be stored in database tables. They can be stored
and retrieved through SQL, but with less flexibility than
nested tables.
Index-By Table
• An index-by table (also called an associative
array) is a set of key-value pairs. Each key is
unique and is used to locate the corresponding
value. The key can be either an integer or a string.
• An index-by table is created using the following
syntax :
– TYPE type_name IS TABLE OF element_type [NOT
NULL] INDEX BY subscript_type;
– table_name type_name;
Example
DECLARE
TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20);
salary_list salary;
name VARCHAR2(20);
BEGIN
-- adding elements to the table
salary_list('Rajnish') := 62000;
salary_list('Minakshi') := 75000;
salary_list('Martin') := 100000;
salary_list('James') := 78000;
-- printing the table
name := salary_list.FIRST;
WHILE name IS NOT null LOOP
dbms_output.put_line
('Salary of ' || name || ' is ' || TO_CHAR(salary_list(name)));
name := salary_list.NEXT(name);
END LOOP;
END ;
/
Example
• Elements of an index-by table could also be a %ROWTYPE of any database table or
%TYPE of any database table field.
DECLARE
CURSOR c_customers is
select name from customers;
TYPE c_list IS TABLE of customers.name%type INDEX BY binary_integer;
name_list c_list;
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter +1;
name_list(counter) := n.name;
dbms_output.put_line('Customer('||counter|| '):'||name_list(counter));
END LOOP;
END;
/
Nested Tables
• A nested table is like a one-dimensional array with an
arbitrary number of elements. However, a nested table
differs from an array in the following aspects :

• 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, i.e., it always has consecutive


subscripts. A nested array is dense initially, but it can
become sparse when elements are deleted from it.
Nested Tables -Syntax
• A nested table is created using the following
syntax :
– TYPE type_name IS TABLE OF element_type [NOT
NULL];
– table_name type_name;

Note:A nested table can be stored in a database


column and so it could be used for simplifying SQL
operations where you join a single-column table
with a larger table
Example
DECLARE
TYPE names_table IS TABLE OF VARCHAR2(10);
TYPE grades IS TABLE OF INTEGER;
names names_table;
marks grades;
total integer;
BEGIN
names := names_table('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz');
marks:= grades(98, 97, 78, 87, 92);
total := names.count;
dbms_output.put_line('Total '|| total || ' Students');
FOR i IN 1 .. total LOOP
dbms_output.put_line('Student:'||names(i)||', Marks:' || marks(i));
end loop;
END;
/
Example
DECLARE
CURSOR c_customers is
SELECT name FROM customers;
TYPE c_list IS TABLE of customers.name%type;
name_list c_list := c_list();
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter +1;
name_list.extend;
name_list(counter) := n.name;
dbms_output.put_line('Customer('||counter||'):'||name_list(counter));
END LOOP;
END ;
/
PL/SQL Varrays
• PL/SQL programming language provides a data structure
called the VARRAY, which can store a fixed-size sequential
collection of elements of the same type.
• A varray is used to store an ordered collection of data, but
it is often more useful to think of an array as a collection of
variables of the same type.
• All varrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element .
• An array is a part of collection type data and it stands for
variable-size arrays .
• Each element in a varray has an index associated with it. It
also has a maximum size that can be changed dynamically .
Creating a Varray Type
• A varray type is created with the CREATE TYPE
statement. You must specify the maximum size and the
type of elements stored in the varray .
• CREATE OR REPLACE TYPE varray_type_name IS
VARRAY(n) of <element_type >
• Where,
– varray_type_name is a valid attribute name ,
– n is the number of elements (maximum) in the varray,
– element_type is the data type of the elements of the array.
• Eg.
– TYPE namearray IS VARRAY(5) OF VARCHAR2(10);
– Type grades IS VARRAY(5) OF INTEGER;
Example
DECLARE • Output:
type namesarray IS VARRAY(5) OF VARCHAR2(10); – Student: Kavita Marks: 98
type grades IS VARRAY(5) OF INTEGER; – Student: Pritam Marks: 97
– Student: Ayan Marks: 78
names namesarray;
– Student: Rishav Marks: 87
marks grades; – Student: Aziz Marks: 92
total integer;
BEGIN PL/SQL procedure successfully completed
names := namesarray('Kavita', 'Pritam', 'Ayan',
'Rishav', 'Aziz');
marks:= grades(98, 97, 78, 87, 92);
total := names.count;
dbms_output.put_line('Total '|| total || '
Students');
FOR i in 1 .. total LOOP
dbms_output.put_line('Student: ' || names(i) || '
Marks: ' || marks(i));
END LOOP;
END;
/
Example
Elements of a varray could also be a %ROWTYPE
of any database table or %TYPE of any • Output:-
database table field. – Customer(1): Ramesh
– Customer(2): Khilan
DECLARE – Customer(3): kaushik
CURSOR c_customers is – Customer(4): Chaitali
SELECT name FROM customers; – Customer(5): Hardik
– Customer(6): Komal
type c_list is varray (6) of customers.name%type;
name_list c_list := c_list(); PL/SQL procedure successfully completed.
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter + 1;
name_list.extend;
name_list(counter) := n.name;
dbms_output.put_line('Customer('||counter
||'):'||name_list(counter));
END LOOP;
END;
/
Declaring Nested Tables, Varrays, and
Associative Arrays
DECLARE BEGIN
-- an arbitrary number of strings can be inserted
TYPE nested_type IS TABLE OF v1
VARCHAR2(30); v1 :=
nested_type('Shipping','Sales','Finance','Payr
TYPE varray_type IS VARRAY(5) OF INTEGER; oll');
TYPE assoc_array_num_type IS TABLE OF v2 := varray_type(1, 2, 3, 4, 5); -- Up to 5 integers
NUMBER INDEX BY PLS_INTEGER; v3(99) := 10; -- Just start assigning to elements
v3(7) := 100; -- Subscripts can be any integer
TYPE assoc_array_str_typeIS TABLE OF values
VARCHAR2(32) INDEX BY PLS_INTEGER; v4(42) := 'Smith'; -- Just start assigning to
elements
TYPE assoc_array_str_type2 IS TABLE OF
v4(54) := 'Jones'; -- Subscripts can be any integer
VARCHAR2(32) INDEX BY values
VARCHAR2(64); v5('Canada') := 'North America'; -- Just start
assigning to elements
v1 nested_type;
v5('Greece') := 'Europe'; -- Subscripts can be
v2 varray_type; string values
v3 assoc_array_num_type; END;
/
v4 assoc_array_str_type;
v5 assoc_array_str_type2;
RECORDS
RECORDS
• A PL/SQL record is a data structure that can hold
data items of different kinds .
• Records consist of different fields, similar to a row
of a database table.
• For example, you want to keep track of your
books in a library. You might want to track the
following attributes about each book like, Title,
Author, Subject, Book ID. A record containing a
field for each of these items allows treating a
BOOK as a logical unit and allows you to organize
and represent its information in a better way
Records- types
• PL/SQL can handle the following types of
records:
– Table-based
– Cursor-based records
– User-defined records
Table-Based Records
• The %ROWTYPE attribute enables a programmer to create table-based
and cursor-based records
DECLARE
customer_rec customers%rowtype;
BEGIN
SELECT * into customer_rec
FROM customers
WHERE id = 5;
dbms_output.put_line('Customer ID: ' || customer_rec.id);
dbms_output.put_line('Customer Name: ' || customer_rec.name);
dbms_output.put_line('Customer Address: ' || customer_rec.address);
dbms_output.put_line('Customer Salary: ' || customer_rec.salary);
End;
/
Cursor-Based Records
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
END LOOP;
END;
/
User-defined Records
• PL/SQL provides a user-defined record type that
allows you to define different record structures.
Records consist of different fields
• Eg.:- Suppose you want to keep track of your
books in a library. You might want to track the
following attributes about each book .
– Title
– Author
– Subject
– Book ID
Defining a Record
• The record type is defined as :
TYPE
type_name IS RECORD
( field_name1 datatype1 [NOT NULL] [:= DEFAULT
EXPRESSION],
field_name2 datatype2 [NOT NULL] [:= DEFAULT
EXPRESSION],
...
field_nameN datatypeN [NOT NULL] [:= DEFAULT
EXPRESSION);
record-name type_name;
Example
DECLARE
TYPE books IS RECORD
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
Accessing Fields
• To access any field of a record, we use the dot
(.) operator. The member access operator is
coded as a period between the record variable
name and the field that we wish to access.
Example
DECLARE
book2.book_id := 6495700;
type books is record -- Print book 1 record
(title varchar(50),
author varchar(50), dbms_output.put_line('Book 1 title : '||
book1.title);
subject varchar(100),
dbms_output.put_line('Book 1 author : '||
book_id number); book1.author);
book1 books; dbms_output.put_line('Book 1 subject : '||
book1.subject);
book2 books;
dbms_output.put_line('Book 1 book_id : ' ||
BEGIN book1.book_id);
-- Book 1 specification -- Print book 2 record
book1.title := 'C Programming'; dbms_output.put_line('Book 2 title : '||
book2.title);
book1.author := 'Nuha Ali '; dbms_output.put_line('Book 2 author : '||
book1.subject := 'C Programming Tutorial'; book2.author);
book1.book_id := 6495407; dbms_output.put_line('Book 2 subject : '||
book2.subject);
-- Book 2 specification dbms_output.put_line('Book 2 book_id : '||
book2.title := 'Telecom Billing'; book2.book_id);
book2.author := 'Zara Ali'; END;
/
book2.subject := 'Telecom Billing Tutorial';
Records as Subprogram Parameters
• You can pass a record as a subprogram
parameter in very similar way as you pass any
other variable
Example
DECLARE BEGIN
type books is record -- Book 1 specification
(title varchar(50), book1.title := 'C Programming';
author varchar(50), book1.author := 'Nuha Ali ';
subject varchar(100), book1.subject := 'C Programming Tutorial';
book_id number); book1.book_id := 6495407;
book1 books; -- Book 2 specification
book2 books; book2.title := 'Telecom Billing';
PROCEDURE printbook (book books) IS book2.author := 'Zara Ali';
BEGIN book2.subject := 'Telecom Billing Tutorial';
dbms_output.put_line ('Book title : ' || book2.book_id := 6495700;
book.title); -- Use procedure to print book info
dbms_output.put_line('Book author : ' || printbook(book1);
book.author); printbook(book2);
dbms_output.put_line( 'Book subject : ' || END;
book.subject);
/
dbms_output.put_line( 'Book book_id : ' ||
book.book_id);
END;

You might also like