1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Oracle PL/SQL Language Pocket Reference- P21 doc

50 443 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 167,82 KB

Nội dung

What database objects are dependent on Foo_t? USER_DEPENDENCIES SELECT name, type FROM user_dependencies WHERE referenced_name = 'FOO_T'; 18.6.2 SQL*Plus "Describe" Command If you're like me and don't like to type any more than necessary, you'll appreciate a wonderful enhancement that Oracle has provided for the describe command in SQL*Plus. It will report not only the attributes of an object type, but also the methods and their arguments. To illustrate: SQL> desc pet_t Name Null? Type ------------------------------- -------- ---- TAG_NO NUMBER(38) NAME VARCHAR2(60) ANIMAL_TYPE VARCHAR2(30) SEX VARCHAR2(1) PHOTO BINARY FILE LOB VACCINATIONS VACCINATION_LIST_T OWNER REF OF PERSON_T METHOD ------ MEMBER FUNCTION SET_TAG_NO RETURNS PET_T Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- NEW_TAG_NO NUMBER IN METHOD ------ MEMBER FUNCTION SET_PHOTO RETURNS PET_T Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- FILE_LOCATION VARCHAR2 IN MEMBER PROCEDURE PRINT_ME Although the formatting could be improved, this is much easier than SELECTing the equivalent information from the data dictionary. 18.6.3 Schema Evolution Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Let's say that you have created an object type and you need to make a change to its definition. What do you do? The answer is that it depends -- on whether you have used the type, and on what type of change you want to make. Precious few modifications are easy; the rest will probably age you prematurely. Consider the implications of where you have used the type: ● Type has no dependencies. Using CREATE OR REPLACE, you can change the object type to you heart's content. Or drop and recreate it; who cares? Life is good. ● Type is used only in PL/SQL modules. In this case, since you don't have to rebuild any dependent tables, life is still easy. Oracle will automatically recompile dependent PL/SQL modules the next time they are called. ● Type is used in one or more tables. Consider what would be a simple change to a relational table: adding a column. If you try to add a column to an object table, you get an "ORA-22856 cannot add columns to object tables." The "Action" for this message says we need to "Create a new type with additional attributes, and use the new type to create an object table. The new object table will have the desired columns." Your frustrations are beginning. OK, if you want to add an attribute, you're out of luck. What about methods? Oracle8.0 does include an ALTER TYPE statement that allows you to recompile an object specification or body. It also allows you to add new methods. It is extremely limited, however; it does not allow you to add or remove attributes, nor does it allow you to modify the quantity or datatypes of existing method arguments. The basic syntax is: Form I ALTER TYPE [ BODY ] type_name COMPILE [ SPECIFICATION | BODY ]; which does not solve our problem, or: Form II ALTER TYPE [ BODY ] type_name REPLACE <the entire new type or body definition>; Using Form II, we can, in fact, add an entirely new method to an object type, even if there are dependencies on the type. In the case of changing a method's specification (or deleting a method) in object type Foo_t which is implemented in table foo, you would think that export/import would work, using something like: 1. Export the foo table. 2. Drop the foo table. 3. CREATE OR REPLACE TYPE Foo_t with the new definition. 4. Import the foo table. But alas, it doesn't work, because when you CREATE OR REPLACE the type, it actually assigns a new OID to the type, and the import fails with IMP-00063 when it sees that the OID is different. Huh? What do you mean, "assigns a new OID to the type?" For reasons apparently having to do with facilitating certain operations in the Oracle Call Interface (OCI), object types themselves have an OID. See for yourself -- you can easily retrieve them from the USER_TYPES data dictionary view. Neither can you "CREATE new_object_table AS SELECT . FROM old_object_table." Even if you could, the REFs wouldn't match up to the OIDs of the new table. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. It's even worse if you want to make any serious modifications to an object type and you have a dependency on the type from other types or tables. You cannot drop and recreate a parent object table unless you drop the child object types and object tables first. So maybe you could: 1. Create new object types and tables. 2. Somehow populate new from the old. 3. Drop the old object tables and types. 4. Rename the new types and object tables to the old names. It is not obvious to me how to do the second step in a way that will preserve REFs to the type. The only way I see to do it in a guaranteed fashion is to rely on relational primary and foreign keys for tuple identification. That is, your schema will include not only REFs but also equivalent foreign keys. Then, when your OIDs change because you have rebuilt an object table, you can update all the REFs to that object table using foreign key values. Not a pretty picture. Also, you cannot rename object types (number 4 above); attempting to do so fails with "ORA-03001: unimplemented feature." WARNING: Requiring the dropping of all dependent types and objects before altering a type is not going to endear the Oracle objects option to the average database administrator (or to anyone else, for that matter). Object schema evolution is a significant area where Oracle could make a lot of improvements. Previous: 18.5 Modifying Persistent Objects Oracle PL/SQL Programming, 2nd Edition Next: 18.7 Making the Objects Option Work 18.5 Modifying Persistent Objects Book Index 18.7 Making the Objects Option Work The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Previous: 18.6 Object Housekeeping Chapter 18 Object Types Next: 19. Nested Tables and VARRAYs 18.7 Making the Objects Option Work This stuff isn't designed to be easy for the beginner, and the complexities are more than syntax-deep. In addition to the operational limitations we have discussed, the act of "thinking objects" is not a trait that comes naturally to programmers schooled in database or structured approaches. But if you feel intimidated, take heart from this advice: "There may be an OO revolution, but that does not mean you have to make the change all at once. Instead, you can incorporate what you know worked before, and bring in the best that OO has to offer, a little at a time as you understand it."[16] [16] See Rick Mercer and A. Michael Berman, "Object-Oriented Technology and C++ in the First Year: Ten Lessons Learned." Presented at the Northeastern Small College Computing Conference, April 18- 20, 1996, and on the web at http://www.rowan.edu/ ~berman/tenLessons/paper.htm. If object technology is such a challenge, what is it that drives many organizations to consider object approaches in the first place? The overriding interest of managers seems to be their desire to reuse rather than reinvent the software needed to run their businesses.[ 17] In industries whose automation needs are not satisfied by off-the-shelf solutions, IS managers are continuously squeezed by the need to deliver more and more solutions while maintaining their legacy code, all while attempting to keep costs under control. [17] See Ivar Jacobson, "Reuse in Reality: The Reuse-Driven Software-Engineering Business." Presented at Object Expo Paris, available at http://www.rational.com/ support/techpapers/objex_ivar.pdf. It may not be obvious from our examples just how the objects option is going to facilitate reuse, particularly given Oracle8.0's lack of inheritance and difficulties with schema evolution. Indeed, the benefits of an object approach do not automatically accrue to the practitioner; large systems, in particular, must exhibit other characteristics.[18] Achieving reuse requires careful planning and deliberate execution. [18] See Grady Booch, Object-Oriented Analysis and Design with Applications, Addison-Wesley 1994. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Experts recommend not attempting object approaches just because someone says they are cool or because everyone else is doing it. Without a financial and time commitment to understanding, and without taking advantage of a different programming model, you are not likely to get much benefit, and yours will join the landscape of projects that didn't deliver. Yes, object approaches can be a way to do more with less. In fact, computer industry pundits assert that "componentware" is becoming the dominant form of software, and that application development is evolving into a process of wiring together components -- whether built in-house or procured -- rather than developing software from scratch. These components are typically built using object design (to specify the component's interfaces, and what it will and won't do) and object-oriented programming languages. The game isn't over, though; we need look only as close as the nearest desktop computer to see both the benefits and the perils of componentware. Windows DLLs, for example, allow module sharing and dynamic loading, but lack a superstructure for managing multiple versions. Other component models exist (CORBA, ActiveX, COM, JavaBeans) in varying states of industry acceptance. Almost certainly, Oracle Corporation will be adding needed features such as inheritance and schema evolution tools to their objects option. One day, objects may even be a standard part of the server. Until the technology matures, early adopters will enjoy the pleasures of finding workarounds, and will gain a deeper appreciation of features that appear later in the product. Previous: 18.6 Object Housekeeping Oracle PL/SQL Programming, 2nd Edition Next: 19. Nested Tables and VARRAYs 18.6 Object Housekeeping Book Index 19. Nested Tables and VARRAYs The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates. All rights reserved. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Previous: 18.7 Making the Objects Option Work Chapter 19 Next: 19.2 Creating the New Collections 19. Nested Tables and VARRAYs Contents: Types of Collections Creating the New Collections Syntax for Declaring Collection Datatypes Using Collections Collection Pseudo-Functions Collection Built-Ins Example: PL/SQL-to-Server Integration Collections Housekeeping Which Collection Type Should I Use? In PL/SQL Version 2, Oracle introduced the TABLE datatype as a way of storing singly dimensioned sparse arrays in PL/SQL. Known as the "PL/SQL table," this structure is thoroughly documented in Chapter 10, PL/SQL Tables. PL/SQL8 introduces two new collection structures that have a wide range of new uses. These structures are nested tables and variable-size arrays (VARRAYs). Like PL/ SQL tables, the new structures can also be used in PL/SQL programs. But what is dramatic and new is the ability to use the new collections as the datatypes of fields in conventional tables and attributes of objects. While not an exhaustive implementation of user-defined datatypes, collections offer rich new physical (and, by extension, logical) design opportunities for Oracle practitioners. In this chapter we'll include brief examples showing how to create and use collection types both in the database and in PL/SQL programs. We'll also show the syntax for creating collection types. We'll present the three different initialization techniques with additional examples, and we'll discuss the new built-in "methods," EXTEND, TRIM, and DELETE, for managing collection content. This chapter also contains an introduction to the new "collection pseudo-functions" that Oracle8 provides to deal with nonatomic values in table columns. Although we can't cover every aspect of SQL usage, the examples will give you a sense of how important -- and useful -- these new devices can be, despite their complexity. We also include a reference section that details all of the built-in methods for collections: for each we'll show its specification, an example, and some programming considerations. The chapter concludes with a brief discussion of which type of collection is most appropriate for some common situations. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 19.1 Types of Collections Oracle now supports three types of collections: ● PL/SQL tables are singly dimensioned, unbounded, sparse collections of homogeneous elements and are available only in PL/SQL (see Chapter 10). These are now called index-by tables. ● Nested tables are also singly dimensioned, unbounded collections of homogeneous elements. They are initially dense but can become sparse through deletions. Nested tables are available in both PL/SQL and the database (for example, as a column in a table). ● VARRAYs, like the other two collection types, are also singly dimensioned collections of homogeneous elements. However, they are always bounded and never sparse. Like nested tables, they can be used in PL/SQL and in the database. Unlike nested tables, when you store and retrieve a VARRAY, its element order is preserved. Using a nested table or VARRAY, you can store and retrieve nonatomic data in a single column. For example, the employee table used by the HR department could store the date of birth for each employee's dependents in a single column, as shown in Table 19.1. Table 19.1: Storing a Nonatomic Column of Dependents in a Table of Employees Id (NUMBER) Name (VARCHAR2) Dependents_ages (Dependent_birthdate_t) 10010 Zaphod Beeblebrox 12-JAN-1763 4-JUL-1977 22-MAR-2021 10020 Molly Squiggly 15-NOV-1968 15-NOV-1968 10030 Joseph Josephs Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 10040 Cepheus Usrbin 27-JUN-1995 9-AUG-1996 19-JUN-1997 10050 Deirdre Quattlebaum 21-SEP-1997 It's not terribly difficult to create such a table. First we define the collection type: CREATE TYPE Dependent_birthdate_t AS VARRAY(10) OF DATE; Now we can use it in the table definition: CREATE TABLE employees ( id NUMBER, name VARCHAR2(50), .other columns ., Dependents_ages Dependent_birthdate_t ); We can populate this table using the following INSERT syntax, which relies on the type's default constructor to transform a list of dates into values of the proper datatype: INSERT INTO employees VALUES (42, 'Zaphod Beeblebrox', ., Dependent_birthdate_t( '12-JAN-1765', '4-JUL-1977', '22-MAR-2021')); One slight problem: most of us have been trained to view nonatomic data as a design flaw. So why would we actually want to do this? In some situations (for those in which you don't need to scan the contents of all the values in all the rows), theoreticians and practitioners alike consider nonatomic data to be perfectly acceptable. Even the conscience of the relational model, Chris Date, suggests that relational domains could contain complex values, including lists.[ 1] Some database designers have believed for years that the large percentage of nonatomic data inherent in their applications demands a nonrelational solution. [1] See Hugh Darwen and C. J. Date, "The Third Manifesto," SIGMOD Record, Volume 24 Number 1, March 1995. Setting aside theoretical arguments about "natural" data representations, Oracle collections provide a dramatic advantage from an application programmer's perspective: you can pass an entire collection Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. between the database and PL/SQL using a single fetch. This feature alone could have significant positive impact on application performance. As we've mentioned, within PL/SQL both nested tables and VARRAYs are ordered collections of homogeneous elements. Both bear some resemblance to the PL/SQL Version 2 table datatype, the elder member of the "collection" family. The new types are also singly dimensioned arrays, but they differ in areas such as sparseness (not exactly), how they're initialized (via a constructor), and whether they can be null (yes). One chief difference between nested tables and VARRAYs surfaces when we use them as column datatypes. Although using a VARRAY as a column's datatype can achieve much the same result as a nested table, VARRAY data must be predeclared to be of a maximum size, and is actually stored "inline" with the rest of the table's data. Nested tables, by contrast, are stored in special auxiliary tables called store tables, and there is no pre- set limit on how large they can grow. For this reason, Oracle Corporation says that VARRAY columns are intended for "small" arrays, and that nested tables are appropriate for "large" arrays. As we've mentioned, the old Version 2 table datatype is now called an index-by table , in honor of the INDEX BY BINARY_INTEGER syntax required when declaring such a type. Despite the many benefits of the new collection types, index-by tables have one important unique feature: initial sparseness. Table 19.2 illustrates many of the additional differences among index-by tables and the new collection types. Table 19.2: Comparing Oracle Collection Types Characteristic Index-By Table Nested Table VARRAY Dimensionality Single Single Single Usable in SQL? No Yes Yes Usable as column datatype in a table? No Yes; data stored "out of line" (in separate table) Yes; data stored "in line" (in same table) Uninitialized state Empty (cannot be null); elements undefined Atomically null; illegal to reference elements Atomically null; illegal to reference elements Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Initialization Automatic, when declared Via constructor, fetch, assignment Via constructor, fetch, assignment In PL/SQL, elements referenced via BINARY_INTEGER (-2,147,483,647 2,147,483,647) Positive integer between 1 and 2,147,483,647 Positive integer between 1 and 2,147,483,647 Sparse? Yes Initially, no; after deletions, yes No Bounded? No Can be extended Yes Can assign value to any element at any time? Yes No; may need to EXTEND first No; may need to EXTEND first, and cannot EXTEND past upper bound Means of extending Assign value to element with a new subscript Use built-in EXTEND procedure (or TRIM to condense), with no predefined maximum EXTEND (or TRIM), but only up to declared maximum size Can be compared for equality? No No No Retains ordering and subscripts when stored in and retrieved from database? N/A No Yes The inevitable question is: Which construct should I use? This chapter reviews some examples of the new collections and offers some suggestions in this area. The short answer: ● Nested tables are more flexible than VARRAYs for table columns. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... (in PL/SQL only) PL/SQL record types To show something other than a table of scalars, let's look at an example of a VARRAY of objects Here we define an object type that will contain information about documents: CREATE TYPE Doc_ t AS OBJECT ( doc_ id INTEGER, name VARCHAR2(512), author VARCHAR2(60), url VARCHAR2(2000) ); We can then define a collection type to hold a list of these objects: CREATE TYPE Doc_ array_t... discussion of REFs) Consider this example: CREATE TYPE Doc_ ref_array_t AS TABLE OF REF Doc_ t; This statement says "create a user-defined type to hold lists of pointers to document objects." You can use a nested table of REFs as you would any other nested table: as a column, as an attribute in an object type, or as the type of a PL/SQL variable NOTE: While Oracle 8.0.3 allows you to create homogeneous collections,... q q q Oracle, not the programmer, assigns the subscripts of l_colors when fetched from the database Oracle' s assigned subscripts begin with 1 (as opposed to 0, as you may be used to in some other languages) and increment by 1 Fetching satisfies the requirement to initialize the local collection variable before assigning values to elements We didn't initialize l_colors with a constructor, but PL/SQL. .. ORDER member function tells Oracle how to compare values in the column Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Previous: 19.3 Syntax for Declaring Collection Datatypes 19.3 Syntax for Declaring Collection Datatypes Oracle PL/SQL Programming, 2nd Edition Next: 19.5 Collection Pseudo-Functions Book Index 19.5 Collection PseudoFunctions The Oracle Library Navigation... initial sparseness If your code must run in both Oracle7 and Oracle8 , you can use only index-by tables We'll revisit these suggestions in more detail at the end of the chapter Before diving in, though, let's review a few of the new terms: Collection A term which can have several different meanings: r r r A nested table, index-by table, or VARRAY datatype A PL/SQL variable of type nested table, index-by... a "nested table column" Store table The physical table which Oracle creates to hold values of the inner table Unfortunately, the term "nested table" can be a bit misleading A nested table, when declared and used in PL/SQL, is not nested at all! It is instead fairly similar to an array Even when you use a nested table as a table column, in Oracle 8.0 you can only nest these structures to a single level... ), as a placeholder: variable_of_element_type := function () (subscript); Previous: 19.1 Types of Collections Oracle PL/SQL Programming, 2nd Edition 19.1 Types of Collections Book Index Next: 19.3 Syntax for Declaring Collection Datatypes 19.3 Syntax for Declaring Collection Datatypes The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates All rights reserved Please purchase PDF Split-Merge... nested table types and index-by table types in a PL/SQL program is the absence of the INDEX BY BINARY_INTEGER clause The syntactic differences between nested table and VARRAY type declarations are: q q The use of the keyword VARRAY The limit on its number of elements Previous: 19.2 Creating the New Collections 19.2 Creating the New Collections Oracle PL/SQL Programming, 2nd Edition Book Index Next:... exceed the limit that you define when you create the type Previous: 18.7 Making the Objects Option Work 18.7 Making the Objects Option Work Oracle PL/SQL Programming, 2nd Edition Book Index Next: 19.2 Creating the New Collections 19.2 Creating the New Collections The Oracle Library Navigation Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Copyright (c) 2000 O'Reilly & Associates... makes the datatype available to use for a variety of purposes: columns in database tables, variables in PL/SQL programs, and attributes of object types 2 You can declare the collection type within a PL/SQL program using TYPE IS syntax This collection type will then be available only for use within PL/SQL Let's look at a few examples that illustrate how to create collections 19.2.1 Collections "In the . sparse arrays in PL/SQL. Known as the " ;PL/SQL table," this structure is thoroughly documented in Chapter 10, PL/SQL Tables. PL/SQL8 introduces. Collection Built-Ins Example: PL/SQL- to-Server Integration Collections Housekeeping Which Collection Type Should I Use? In PL/SQL Version 2, Oracle introduced the

Ngày đăng: 15/12/2013, 04:15

TỪ KHÓA LIÊN QUAN

w