DROP TABLE child; DROP TABLE parent; DROP TYPE parent_type FORCE; DROP TYPE child_type FORCE; CREATE OR REPLACE TYPE name_type AS OBJECT First_name VARCHAR230,Last_name VARCHAR230,Middle
Trang 1Another option for an object table is to define the primary key of the table to bethe OID, using the OID clause of the CREATE TABLE statement If you use the pri-mary key as the OID for the table, it will only be unique to the table itself This is analternative to using the default system-generated OID (a 128 byte, base 64 number),which is globally unique throughout the database If you specify that the table shoulduse the system-generated OID, then you will want to specify the STORAGE clauses forthe related OID index that will be created Thus, using the system-generated OID willrequire more storage space than using the primary key.
Listing 8.9 provides an example of the creation of both the child and the parentobject tables, using a few of the options just described
Listing 8.9: Creating Object Tables
Drop all types and tables to make this easier
DROP TABLE child;
DROP TABLE parent;
DROP TYPE parent_type FORCE;
DROP TYPE child_type FORCE;
CREATE OR REPLACE TYPE name_type AS OBJECT(
First_name VARCHAR2(30),Last_name VARCHAR2(30),Middle_init CHAR(1) )/
Create our forward type declaration for the child_type type so we can create the parent_type type
CREATE OR REPLACE TYPE child_type/
Create the parent_type type
Note the two REFs to the child_type
CREATE OR REPLACE TYPE parent_type AS OBJECT (Parent_id NUMBER,
Parent_name name_type,Parent_address address_type,Child_name REF child_type,Exch_student REF child_type)/
Trang 2Now, create the parent table We will use an OID index for this table This is generally required for the main table in a parent/child relationship The OIDINDEX clause will help speed up REF lookups between this and the child table.
CREATE TABLE parent
OF parent_typeOIDINDEX idx_parent (TABLESPACE indexes)TABLESPACE users
PCTFREE 10PCTUSED 70STORAGE (INITIAL 100k NEXT 100k PCTINCREASE 0);
Now, we are going to add a primary key constraint to the parent table
ALTER TABLE parent ADDCONSTRAINT pk_parentPRIMARY KEY (parent_id)USING INDEX
PCTFREE 10TABLESPACE indexesSTORAGE (INITIAL 10k NEXT 10k);
CREATE TABLE child
OF child_type(parent_id WITH ROWID SCOPE IS parent,teacher WITH ROWID SCOPE IS parent)OIDINDEX oid_child (TABLESPACE indexes)TABLESPACE users
STORAGE (INITIAL 100k NEXT 100k PCTINCREASE 0);
USING OBJECT TABLES
Oracle Database Administration
P A R T
II
Trang 3There is a lot going on in Listing 8.9, but much of it is building on what you havealready learned (and we will build even more on this example shortly) Let’s dissectwhat this code is doing.
First, we drop the types and tables that we will be creating This just makes theoverall re-creation process much easier Next, we create a forward type declaration forthe CHILD_TYPE type, since we will need it to create the PARENT_TYPE type Next,
we create the parent type and then the child type As before, each type has REFs erences) to each other (yes, we know, true evil nastiness)
(ref-Then we begin to create the object tables The first thing you may be wonderingabout is the OIDINDEX clause that you see in both CREATE TABLE statements TheOIDINDEX clause will create an index on the OID of the tables This is not unlike aregular index on a primary key The OID index can significantly speed up REF queriesbetween object tables Since both tables will be referencing each other, both indexeswill be helpful If you had only one table with REFs, then you definitely would want
an OID index on the table being referenced In this case, an OID index on the othertable—the one that has no references to it—would not be needed
The parent table creation is a fairly straightforward operation that you havealready seen in earlier examples The child table creation is a bit different Here, yousee some new syntax in the form of:
(parent_id WITH ROWID SCOPE IS parent,teacher WITH ROWID SCOPE IS parent)
What we are doing here is completing what we started When we defined the PARENT_ID and TEACHER_ID attributes of the PARENT_TYPE type (in the CREATETYPE statement), we used the REF clause to indicate that the PARENT_ID andTEACHER_ID attributes would reference row objects in some other object table I’msure that you were wondering just what that REF was going to be used for Well, here isyour answer When we first created the REF, we didn’t have an actual object to refer-ence it to Remember that types are just templates, and beyond that, they do not storeanything Thus, when you create a type, you don’t need anything to reference anattribute to Now that we have created the object tables (and thus allocated some stor-age to an instance of the PARENT_TYPE), we can define what object these REFs arereferring to In Listing 8.9, we have two different operations going on This is known
as scoping the REF.
Also notice in Listing 8.9 that we are storing the ROWID pseudocolumn with theOID of each row Like scoping the REF to a specific table, this can speed up certainquery activities Neither of these actions is required, but taking them will reduce spacerequirements and can speed up access to the table being referenced
Trang 4Have you noticed that something is still missing? Think about it for a moment andsee if you can figure out what it is There is something we still have not done yet, andthat leads us to the topic of altering object tables
Altering Object Tables
After you create an object table, you may need to later alter the nature of that table
As you might guess, the ALTER TABLE statement is what you are looking for
So, going back to the previous section, did you figure out what it was we stillneeded to do? What we have not done yet is to scope out the REFs for the parenttable This is because when we created the parent object table, we had not yet createdthe child table After creating the child table, we can scope the circular references thatare in the parent table, as well as set up the ROWID storage We execute these opera-tions in the last two ALTER TABLE statements, shown in Listing 8.10
Listing 8.10: Altering Object Tables
This enables our circular reference from parent to child for the parent table This is the same as the “parent_id WITH ROWID SCOPE IS parent” line in the CREATE TABLE statement for the child table Since the child table was not present when we created the parent table, we could not do this yet
Now that the child table has been created, we can create the scoped REF
ALTER TABLE parent ADD(REF(child_name) WITH ROWID, REF(exch_student) WITH ROWID)/
ALTER TABLE parent ADD(SCOPE FOR (child_name) IS CHILD,SCOPE FOR (exch_student) IS CHILD)/
As you would expect, you can also use the ALTER TABLE statement to change anumber of characteristics of an object table, just as you would a relational table Thisincludes STORAGE clauses, partitioning, and so on
NOTE One big difference between object tables and relational tables is that it is notpossible to add a column to an object table This is because an object table is whollydefined by a user-defined type
USING OBJECT TABLES
Oracle Database Administration
P A R T
II
Trang 5Dropping Object Tables
Well, it doesn’t get much simpler than this You use the DROP TABLE clause to drop
an object table:
DROP TABLE parent;
As you might expect, there are a couple of nasty potential results from dropping anobject table If you drop a parent table and leave a child table (or even vice-versa, as inour example), you can end up with dangling REFs—the orphaned table will have ref-erences to rows in a table that no longer exists This can also occur if you drop parentrows but do not clean up the child records This is bad news, but Oracle has provided
a way to deal with this problem through the use of the ANALYZE command, using theVALIDATE REF UPDATE SET DANGLING TO NULL option As explained in the “Intro-ducing Row and Column Objects, OIDs, and REFs” section earlier in this chapter, thisoption will update all ROWIDs for REFs, and set dangling REFs to NULL
Getting Information about Object Tables
There are a couple of data dictionary views that are useful for managing object tables.These include the DBA_OBJECT_TABLES view and the DBA_REFS data dictionary views
The DBA_OBJECT_TABLES View
Do you want to see a listing of object tables? You won’t find them in the DBA_TABLESview You’ll need to use the DBA_OBJECT_TABLES view, which provides informationabout the object table, such as the owner name, object table name, the tablespacename that the object table is assigned to, as well as the results of the ANALYZE processexecuted against that object table Here is an example of a query against the
DBA_OBJECT_TABLES view and its results:
SELECT owner, table_name, tablespace_name, initial_extent,next_extent
FROM dba_object_tablesWHERE owner=’SCOTT’;
OWNER TABLE_NAME TABLESPACE_NAME INITIAL_EXTENT NEXT_EXTENT - - - - -SCOTT CHILD USERS 102400 102400SCOTT PARENT USERS 102400 102400
Trang 6NOTE Even though you won’t find object tables in the DBA_TABLES view, you will findthe columns of an object table in the DBA_TAB_COLUMNS view
The DBA_REFS View
The DBA_REFS data dictionary view describes the REFs present in an attribute of anobject type This view describes the owner and object that contains the REF, as well asother information about the REF Here is an example of a query against this data dic-tionary view and its results:
SELECT owner, table_name, column_name,is_scoped, scope_table_owner,scope_table_name
FROM dba_refsWHERE owner NOT LIKE ‘%SYS%’;
OWNER TABLE_NAME COLUMN_NAME IS_ SCOPE_TABL SCOPE_TABLE_NA - - - - - -SCOTT CHILD PARENT_ID YES SCOTT PARENT
SCOTT CHILD TEACHER YES SCOTT PARENTSCOTT PARENT CHILD_NAME NO
SCOTT PARENT EXCH_STUDENT NO
Using Collection Types
If you have had any programming experience, you know what an array is A tion is not unlike an array A collection allows you to store one or more object types in
collec-a given row In other words, with collec-a collection type, you ccollec-an denormcollec-alize collec-a tcollec-able, ing multiple related objects of information in a given row that is related to that infor-mation The two collection types in Oracle are VARRAYs and nested tables Each hasits own distinguishing characteristics, but they are similar in nature
stor-Working with VARRAYs
A VARRAY (or varying array) is much like an array in a programming language such as
C or BASIC A VARRAY column allows you to store multiple values in the same cated datatype You can define a VARRAY as an attribute of a table or as a volatile ele-ment in a PL/SQL routine
allo-USING COLLECTION TYPES
Oracle Database Administration
P A R T
II
Trang 7A VARRAY is an ordered set of data elements of the same type Each element of aVARRAY contains an index An index is a number that points to the order of the dataelement in the array Because you need to define the boundaries of the array (or howmany records it can store), the VARRAY is somewhat more limiting than its cousin,the nested table Once created, the boundaries of the array cannot be redefined with-out dropping and re-creating the VARRAY object A VARRAY cannot contain anothercollection type in its definition Also, VARRAY types cannot store LOBs, while nestedtables can Finally, a VARRAY has a storage limit of 2GB These restrictions obviouslylimit the effectiveness of the VARRAY collection type.
Just as you can store LOBs out of line in a given object to improve performance,you can also store VARRAYs out of line with the rest of the data in the object table.The associated LOB storage segment must be contained in the same tablespace as theobject table When you define the object that contains the VARRAY, you can forceOracle to store the data out of line with the DISABLE STORAGE IN ROW clause of theCREATE TABLE command
The elements of a VARRAY must be packed, meaning that you need to start withindex 0 for the first record, store the second in index 1, and so on You cannot storerecord one in position two and record three in position four This also implies thatyou cannot remove records from a VARRAY except from the uppermost used index
Creating VARRAYs
To create a VARRAY, use the CREATE TYPE command, just as you would to create auser type When creating a VARRAY, you must provide a type name for that array Thetype name can be a built-in datatype (such as NUMBER or VARCHAR2), a REF, or anobject type (such as ADDRESS_TYPE) Listing 8.11 provides an example of creating aVARRAY
Listing 8.11: Creating a VARRAY
DROP TABLE parent;
DROP TYPE address_type FORCE;
DROP TYPE name_type FORCE;
DROP TYPE parent_type FORCE;
First, create the address_type type
CREATE OR REPLACE TYPE address_type AS OBJECT (Address_number NUMBER,
Street_address_one VARCHAR2(50),Street_address_two VARCHAR2(50),City VARCHAR2(30),
Trang 8State VARCHAR2(2),Zip_code VARCHAR2(10) )/
CREATE OR REPLACE TYPE address_varray AS VARRAY(5) OF address_type/
Create the name_type type
CREATE TYPE name_type AS OBJECT(
First_name VARCHAR2(30),Last_name VARCHAR2(30),Middle_init CHAR(1) )/
Create the parent_type type
CREATE TYPE parent_type AS OBJECT (Parent_id NUMBER,Parent_name name_type,Parent_address address_varray)
/
Create the object table with the VARRAY
CREATE TABLE parent OF parent_type (PRIMARY KEY (parent_id)
USING INDEX TABLESPACE indexesSTORAGE (INITIAL 10k NEXT 10k PCTINCREASE 0) )OBJECT ID PRIMARY KEY
VARRAY parent_address STORE AS LOB parent_address_varray(DISABLE STORAGE IN ROW )
PCTFREE 10PCTUSED 70STORAGE (INITIAL 100k NEXT 100k PCTINCREASE 0);
In this example, we begin by dropping the table and types that we will be creating
This is so we get a fresh start with each creation Next, we create the ADDRESS_TYPEtype Following that is the creation of the VARRAY type Notice that when we createthe VARRAY type, we are, again, just creating a type There is still no storage associ-ated with this type; it is just another type defined in the data dictionary We proceed
to create the other types (NAME_TYPE and PARENT_TYPE) that we will need in theobject table to be created in this example
USING COLLECTION TYPES
Oracle Database Administration
P A R T
II
Trang 9Now comes the fun part—the actual creation of the object table that we call ENT The creation syntax is straightforward First, we indicate that the parent objecttable will be of the type PARENT_TYPE Next, we define the primary key for the objecttable to be the PARENT_ID column, and we use the USING INDEX clause to definethe tablespace and storage characteristics of the primary key index, just as we wouldwith a normal relational table Next, we define the OID to be the primary key of thetable (Recall that the OID is a unique identifier for each row in the table.)
PAR-Following the definition of the primary key as the OID, we define the VARRAY thatwill be contained in this table, starting with this command:
VARRAY parent_address STORE AS LOB parent_address_varray;
The VARRAY is the attribute PARENT_ADDRESS in the type PARENT_TYPE We arestoring the VARRAY data as a LOB datatype, and the LOB segment that will be created
is PARENT_ADDRESS_VARRAY Note the use of the DISABLE STORAGE IN ROWclause, which is optional This forces Oracle to store all of the data associated with theVARRAY out of line, in the LOB segment If the DISABLE STORAGE IN ROW clause isnot used, or the default ENABLE STORAGE IN ROW clause is used, then the first 4000bytes of the data (more or less, depending on how finicky Oracle is feeling on a givenday) will be stored in line The remaining data will be stored out of line in the LOBsegment
Note that you can also create a VARRAY as a PL/SQL variable, as shown in thisexample:
CREATE OR REPLACE TYPE number_varray AS VARRAY(10) OF NUMBER;
Altering and Dropping VARRAYs
There isn’t really anything to alter with regard to a VARRAY If you need to makechanges to the definition of a VARRAY, you will need to drop the type and re-create it.This implies that you will need to preserve your data before you make the change Ifyou created a VARRAY and then decide that it just isn’t working out, you can drop thething (in Nevada, there is no waiting period required) To drop a VARRAY, simply usethe DROP TYPE command
You can use the ALTER TABLE statement to modify some of the attributes of theactual VARRAY assigned to the table This would include the LOB STORAGE clause(you can change the PCTVERSION and CHUNK parameters, for example) Here is anexample of changing the PCTVERSION:
ALTER TABLE parentMODIFY VARRAY parent_address(PCTVERSION 20);
Trang 10Note that once you have created or added a VARRAY, you cannot change the ting for storing rows in line
set-Working with Nested Tables
The second cousin (once removed) to the VARRAY is the nested table The nestedtable type has the same job as the VARRAY, which is to store repeating data for a sin-gle row The primary differences between a nested table and a VARRAY are that anested table is not bounded and that the elements of a nested table can be sparselypopulated If you have a nested table with three elements, you can remove the middleelement without affecting the other elements
The data in a nested table is stored out of line in an object that you define whenyou create the table with the nested table The table created to store the nested tabledata is stored in the same tablespace as the table that the data is associated with, andthis default cannot be changed
Creating Nested Tables
When you create a nested table, you define a primary key index for the nested object,just as you would for any other table You can also define the storage of the nestedtable as a hash table, which is the default, or as an index-organized table As withVARRAYs, nested tables cannot contain other collection types; thus, a nested tabletype cannot contain a reference to another nested table
Listing 8.12 shows an example of creating a nested table This example makes theADDRESS_TYPE type a nested table in the PARENT table (assume our parents havemultiple homes)
Listing 8.12: Creating a Nested Table
DROP TYPE address_type FORCE;
DROP TYPE address_type_nt FORCE;
DROP TYPE name_type FORCE;
DROP TYPE parent_type FORCE;
DROP TABLE parent;
First, create the address_type type
CREATE OR REPLACE TYPE address_type AS OBJECT (Address_number NUMBER,
Street_address_one VARCHAR2(50),Street_address_two VARCHAR2(50),City VARCHAR2(30),
USING COLLECTION TYPES
Oracle Database Administration
P A R T
II
Trang 11State VARCHAR2(2),Zip_code VARCHAR2(10) )/
Now, create a nested table type
CREATE TYPE address_type_nt AS TABLE OF address_type/
Create the name_type type
CREATE TYPE name_type AS OBJECT(
First_name VARCHAR2(30),Last_name VARCHAR2(30),Middle_init CHAR(1) )/
Create the parent_type type
CREATE TYPE parent_type AS OBJECT (Parent_id NUMBER,Parent_name name_type,Parent_address address_type_nt)
/
Create the object table with the nested table
CREATE TABLE parent OF parent_type (PRIMARY KEY (parent_id)
USING INDEX TABLESPACE indexesSTORAGE (INITIAL 10k NEXT 10k PCTINCREASE 0) )OBJECT ID PRIMARY KEY
NESTED TABLE parent_address STORE AS parent_address_nestab ((PRIMARY KEY ( nested_table_id, address_number ) ) )
TABLESPACE usersPCTFREE 10PCTUSED 70STORAGE (INITIAL 100k NEXT 100k PCTINCREASE 0);
Trang 12Altering and Dropping Nested Tables
Like VARRAYs, nested tables don’t really have anything to alter, but you might sider using some ALTER TABLE options for active tables containing nested tables Youcan use the ALTER TABLE statement to add a nested table to an existing table You canalso change the nested table so that it returns the locator value of the data in thenested table rather than the data contained in it This is handy for situations whereyou might get a great deal of information from a query that includes a nested table
con-Since, by default, you would get all of the data in the nested table that met the criteria
of the query, this could end up being a significant amount of data By using theRETURN AS LOCATOR clause (and you can create the nested table to do this as well),Oracle will simply return a locator value that is a pointer to the rows that match thecriteria of the query You can use the Oracle Call Interface (OCI) interfaces or thepackage UTL_COLL_IS_LOCATOR to return the row detail using this value
Listing 8.13 provides an example of an ALTER TABLE command that you mightrun against a relational table with a nested table in it In this case, the example adds anested table of type CHILD_TYPE to the parent table This particular nested table willreturn a locator to any rows that are retrieved by a query, rather than the data itself
Listing 8.13: Altering a Relational Table That Contains a Nested Table
Drop the type first
DROP TYPE name_type FORCE;
DROP TYPE name_type_nt FORCE;
DROP TYPE child_type_nt FORCE;
DROP TYPE child_type FORCE;
DROP TABLE parent;
Create the name_type type
CREATE TYPE name_type AS OBJECT(
First_name VARCHAR2(30),Last_name VARCHAR2(30),Middle_init CHAR(1) )/
Make this a nested table
CREATE TYPE name_type_nt AS TABLE OF name_type/
Now, create the child_type
CREATE OR REPLACE TYPE child_type AS OBJECT (
USING COLLECTION TYPES
Oracle Database Administration
P A R T
II
Trang 13Child_id NUMBER,Child_name name_type)
/ Now, create a nested table type
CREATE TYPE child_type_nt AS TABLE OF child_type/
CREATE TABLE parent (Parent_id NUMBER PRIMARY KEY,Parent_name name_type_nt)
NESTED TABLE parent_name STORE AS parent_name_nestab ((PRIMARY KEY ( nested_table_id ) ) )
TABLESPACE usersPCTFREE 10PCTUSED 70STORAGE (INITIAL 100k NEXT 100k PCTINCREASE 0);
ALTER TABLE parent ADD (child_name child_type_nt)NESTED TABLE child_name STORE AS parent_child_name_nestabRETURN AS LOCATOR;
As noted earlier, this example only works on a relational table Unfortunately, youcannot add columns to an object table
Getting Information about Collection Types
If you want to know something about the collection types present in your database,the DBA_COLL_TYPES view is the place to go This view will show you the name andowner of the collection type, what type of collection it is, and other useful informa-tion The following is an example of a query against this DBA view and its results
SELECT owner, type_name, coll_type,elem_type_owner “EOwner”,
elem_type_name “Ename”
FROM dba_coll_typesWHERE owner NOT LIKE ‘%SYS%’;
Trang 14OWNER TYPE_NAME COLL_TYP EOwner Ename - - - - -SCOTT ADDRESS_TYPE_NT TABLE SCOTT ADDRESS_TYPESCOTT CHILD_TYPE_NT TABLE SCOTT CHILD_TYPESCOTT ADDRESS_VARRAY VARYING SCOTT ADDRESS_TYPE_2
SELECT owner, table_name, table_type_name, parent_table_columnFROM dba_nested_tables;
OWNER TABLE_NAME TABLE_TYPE_NAME PARENT_TABLE_COLUMN - - - -SCOTT PARENT_NAME_NESTAB NAME_TYPE_NT PARENT_NAMESCOTT PARENT_CHILD_NAME_NESTAB CHILD_TYPE_NT CHILD_NAME
Notice that the name and owner of the nested table appear in the OWNER andTABLE_NAME columns (this is the name of the actual segment that is storing thetable data) You also see the type name of the nested table, as shown in the CREATETYPE OF TABLE statement, in the TABLE_TYPE_NAME column In the PARENT_
TABLE_COLUMN column, you find the name of the column that the nested table isassigned to
Trang 15There are four types of methods that you can associate with any type that you create:
Using Constructor Methods
A constructor is a PL/SQL function that is created automatically with the creation of
any type or collection object Constructors are used to insert data into user-defineddatatypes and collection objects, as you will learn in the “Querying Object Types” sec-tion later in the chapter
A constructor is named the same as the type that it is based on Therefore, if a VARRAY or nested table is based on a type called ADDRESS_TYPE, the constructor isalso called ADDRESS_TYPE The constructor contains several parameters, one for each
of the attributes of the type it is associated with, in the order that they were created.Thus, if the type the collection type was based on has three attributes, then the con-structor will have three parameters
Working with Member Methods
When creating a member method, you define the method when you issue the ATE TYPE statement to create the user-defined type Just as with other PL/SQL pro-gram units, you can define a member method to run with the rights of either theinvoker or the creator Use the AUTHID clause to indicate if the user or creator’s privi-leges should be used when executing a method As with a package, you define themethod in the initial definition of the type You then proceed to create the actualcode for the method by using the CREATE TYPE BODY statement
CRE-When you call an instance of a member method, the first parameter of that method
is always called SELF This parameter identifies the instance of the object within thatobject SELF is bound automatically when you refer to an object in a method that wascreated (instantiated) in that method If you want to pass the instance of an object toanother method, or reference it in an argument to a function or procedure, you need
to preface the instance of that object with the SELF keyword
Trang 16When using the CREATE TYPE statement to create a method, you can define twotypes of member methods: functions or procedures The methods created can bedefined as either static or member methods A member method can have any number
of parameters associated with it, and it can also be overloaded
Static member methods were introduced in Oracle81 This type of method is a tive of the member method It is associated and invoked with the object type, ratherthan an instance of that object A static method, since it is associated with the typerather than any instance of that type, cannot refer to the attributes of the current object
deriva-If you create a static method, the PL/SQL procedures will not have a SELF parameter
Creating Member Methods
To create a member method, use the CREATE OR REPLACE TYPE BODY command Inthis command, you define the type and name of the member If it is a function, youdeclare the value type to be returned Following this is the body of a PL/SQL block ofcode Listing 8.14 provides an example of the creation of a type that contains onemethod—a function that returns the name and phone number of the recordselected—followed by the command to create the associated PL/SQL block
Listing 8.14: Creating a Member Method
First, create the type
CREATE OR REPLACE TYPE parent_type AS OBJECT(
first_name VARCHAR2(30),last_name VARCHAR2(30),middle_initial CHAR(1),phone_number VARCHAR2(20),last_contact DATE,
MEMBER FUNCTION name_and_phone RETURN VARCHAR2)
/
Now, create the members
CREATE OR REPLACE TYPE BODY parent_type ASMEMBER FUNCTION name_and_phone RETURN VARCHAR2 ISBEGIN
RETURN(SELF.first_name||’ ‘||SELF.last_name||’ Phone:
Trang 17Listing 8.14 just creates a template of the user-defined object What you need to donext is create an instance of it Here is an example of creating the table and theninserting some records into it:
CREATE TABLE parent OF parent_type;
Insert a couple of records
INSERT INTO parent VALUES(‘Robert’,’Freeman’,’G’,’904.200.2020’,to_date(‘01-JAN-01’));
INSERT INTO parent VALUES(‘Deborah’,’Freeman’,’L’,’014.200.2020’,to_date(‘01-MAY-01’));
Now you can use the NAME_AND_PHONE function, like this:
SELECT p.name_and_phone() FROM parent p;
P.NAME_AND_PHONE() -Robert Freeman Phone: 904.200.2020Deborah Freeman Phone: 904.200.2020
Notice that the method is called using the name of the object (or its alias, as in thecase of the listing above) and then the name of the method
You can also create and use a member method in PL/SQL, as demonstrated in theexample in Listing 8.15
Listing 8.15: Creating and Using a Method Instance in PL/SQL
DECLAREV_output VARCHAR2(60);
V_parent parent_type := parent_type(‘Robert’,’Freeman’,’G’,’904.200.2020’,to_date(‘01-JAN-01’));
BEGINV_output=v_parent.name_and_phone();
END;
/
Creating Static Member Methods
To define a static member method, use the keyword STATIC in both the header andthe body of the code you are using to create the method The method can refer to anobject passed to it and to the attributes of a new object
A static method can be used as an alternative to the default constructor method for
a given type Using a static method, you can create the constructor with a name other
Trang 18than the name of the object Listing 8.16 provides an example of using a staticmethod associated with an object type
Listing 8.16: Creating a Static Member Method
DROP TYPE parent_type FORCE;
First, create the type
CREATE OR REPLACE TYPE parent_type AS OBJECT(
first_name VARCHAR2(30),last_name VARCHAR2(30),middle_initial CHAR(1),phone_number VARCHAR2(20),last_contact DATE,
STATIC PROCEDURE my_static_procedure (p_var1 IN VARCHAR2))
/
Now, create the members
CREATE OR REPLACE TYPE BODY parent_type ASSTATIC PROCEDURE my_static_procedure(p_var1 IN VARCHAR2)
ISBEGINDbms_output.enable(1000);
Dbms_output.put_line(p_var1||’ Passed into the static Procedure’);
This is a test of the procedure! Passed into the static Procedure!
USING METHODS
Oracle Database Administration
P A R T
II
Trang 19Creating Map and Order Methods
Map and order methods are used to facilitate ordering and grouping of attributes in
an object By default, Oracle supports comparisons of values within an instance of anobject (not the comparison within an instance of an object) only if those compar-isons are equality or inequality based A type can have only one order or mapmethod, so they are mutually exclusive
Both map and order methods use the SELF parameter A map method returns aVARCHAR2 value and requires no other parameters An order method takes one otherparameter, which represents the value being compared to the current record Theorder method will then return one of three values:
• –1 when the value of SELF is less than the input parameter
• 0 when the value of SELF is equal to that of the input parameter
• 1 when the value of SELF is more than that of the input parameterListing 8.17 provides examples of creating map and order methods for a type
NOTE In Oracle8i, you will find that ordering within an instance of a type works justfine, without a map or order method
Listing 8.17: Creating a Map and Order Method
First, create the type
CREATE OR REPLACE TYPE parent_type AS OBJECT(
first_name VARCHAR2(30),last_name VARCHAR2(30),middle_initial CHAR(1),phone_number VARCHAR2(20),last_contact DATE,
MAP MEMBER FUNCTION parent_map RETURN VARCHAR2)
/
Now, create the map method
CREATE OR REPLACE TYPE BODY parent_type ASMAP MEMBER FUNCTION parent_map RETURN VARCHAR2 ISBEGIN
Trang 20DROP TYPE parent_type FORCE;
First, re-create the type for the order method
CREATE OR REPLACE TYPE parent_type AS OBJECT(
first_name VARCHAR2(30),last_name VARCHAR2(30),middle_initial CHAR(1),phone_number VARCHAR2(20),last_contact DATE,
ORDER MEMBER FUNCTION parent_order (OTHER parent_type)RETURN NUMBER
)/
Now, create the order method
CREATE OR REPLACE TYPE BODY parent_type ASORDER MEMBER FUNCTION parent_order (other parent_type)RETURN NUMBER IS