Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Programming PL SQL.doc
Скачиваний:
2
Добавлен:
01.07.2025
Размер:
5.06 Mб
Скачать

11.2.1 A Simple Collection Example

Collections are much more complex in structure and syntax than scalar variables such as dates and numbers. Let's take a look at a very simple example, and then use that to explore some of the concepts and terminology associated with collections. Take a look at the following code.

1 DECLARE

2 TYPE list_of_dates_t IS TABLE OF DATE;

3

4 TYPE list_of_names_t IS TABLE OF VARCHAR2 (100)

5 INDEX BY BINARY_INTEGER;

6

7 birthdays list_of_dates_t

8 := list_of_dates_t ( );

9 happyfamily list_of_names_t;

10 BEGIN

11 birthdays.EXTEND;

12 birthdays (1) := '23-SEP-1958';

13 birthdays.EXTEND;

14 birthdays (2) := '01-OCT-1986';

15

16 happyfamily (-15070) := 'Steven';

17 happyfamily (88) := 'Veva';

18 happyfamily (909) := 'Chris';

19 happyfamily (2020202020) := 'Eli';

20

21 DBMS_OUTPUT.put_line (birthdays.COUNT);

22 DBMS_OUTPUT.put_line (happyfamily.FIRST);

23 END;

Here is the output from running this script:

2

-15070

The following table steps through the code and draws out some concepts and definitions:

Line(s)

Description

2-5

Declarations of types of collections. To work with a collection (list), you must first define its type and then declare specific collections from those types. You see here two different collection types: a nested table type on line 2 and an associative array type on lines 4-5.

7-8

Actual declaration of a nested table. Notice that you must also initialize the nested table by calling a constructor, a function with the same name as the TYPE that is automatically provided by PL/SQL.

9

Declaration of an associative array. No constructor is needed for these types of collections.

11-14

I define two rows in the nested table with a standard assignment operator. Notice, however, that I must explicitly extend or make room for those rows. If I do not extend first, an assignment like this will raise an error. Notice also that I populate the rows in the birthdays nested table sequentially.

16-19

I populate the happyfamily collection with four names. I do not have to extend with associative arrays; simply by assigning a value to a row number, I conjure that row into existence. Notice that I did not add rows sequentially. In fact, I chose my row numbers randomly, using both positive and negative numbers. This is an example of a sparse collection.

21

I take advantage of the collection method called COUNT to obtain the number of rows defined in my birthdays nested table.

22

Finally, I use the collection method FIRST to obtain the first or lowest row number in use in my happyfamily collection.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]