I have created the following in Oracle PSL/SQL:
I have created a type Animal
.
This has the attributes: Name, Age
I have created the type Dog
. This inherits from type Animal
The only extra field in Dog
is a nested table of references of place lived. I want to store all instances of Dog
in the Animal table.
This is the bit I am confused about: When creating the Animal table of type Animal
, how do I create the nested table for places lived
? There is no field in Animal
for this, only in Dog
.
"When creating the Animal table of type Animal, how do I create the nested table for "places lived"? when there is no field in Animal for this, only in Dog."
This is the mystery of inheritance. A table built from the type ANIMAL actually has columns to support the attributes of its sub-types. However, they are only accessible when we explicitly use the DOG sub-type.
Here is your data structure.
create or replace type animal_t as object
( name varchar2(10)
, age number (3,0))
not final;
/
create or replace type places_nt as table of varchar2(20)
/
create or replace type dog_t under animal_t
( residence_history places_nt)
/
create table animals of animal_t;
To create a record for a goldfish we do this:
insert into animals
values (animal_t('BOB', 7))
/
To create a record for a dog we need to do this:
insert into animals
values (dog_t('FIDO', 12, places_nt('Balham', 'Tooting')))
/
This query will just select the generic columns:
SQL> select * from animals
2 /
NAME AGE
---------- ----------
BOB 7
FIDO 12
SQL>
To gain sight of the details pertaining to dogs we need to cast the record to the relevant sub-type:
SQL> select treat(value(a) as dog_t)
2 from animals a
3 where value(a) is of (dog_t)
4 /
TREAT(VALUE(A)ASDOG_T)(NAME, AGE, RESIDENCE_HISTORY)
--------------------------------------------------------------------------------
DOG_T('FIDO', 12, PLACES_NT('Balham', 'Tooting'))
SQL>
There is an entire book in the Oracle documentation devoted to its Object-Relational features. Find out more .
Note: I have used an object table here simply because it is easy to illustrate how nested tables work. I do not recommend using types for data storage: OO is a programming paradigm and should only be used for writing programs. Data should always be persisted in relational structures.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.