Tài liệu Oracle SQL Jumpstart with Examples- P9 ppt

50 304 0
Tài liệu Oracle SQL Jumpstart with Examples- P9 ppt

Đ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

370 17.2 Using XML in Oracle later in this chapter. For now all I have done is copy the first two rows in Figure 17.10 and pasted and annotated them into Figure 17.11. Most relational database interpretation of XML is direct and dumps rows into two dimensions, as results would appear in row form, such as in this join. Note: Two-dimensional data is useful for platform-independent transfer between multiple databases. However, there are other, faster methods for achieving this task with Oracle Database. The beauty of XML is its potential object hierarchical nature, effectively allowing removal of duplicated data. Figure 17.11 clearly shows that dupli- cation is present in abundance. What can we do about this? We can use a function called XMLAGG to aggregate data. In its simplest form, XMLAGG is limited, because it appears to be capable of descending only into a single level of a hierarchy. XMLCONCAT does not help either in this respect because of conflict between the aggregation functions and the GROUP BY clause. The result of the following query as shown in Figure 17.12 is much better than that of Figure 17.11, but it is still not correct, as can be seen by appropriate annotations in Figure 17.12, because artists remain duplicated. SELECT XMLELEMENT("Artist", XMLATTRIBUTES(A.NAME "Name") Figure 17.11 Duplicating Parent Tags. Chap17.fm Page 370 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17.2 Using XML in Oracle 371 Chapter 17 , XMLFOREST(A.CITY "City", A.COUNTRY "Country") , XMLELEMENT("CD", XMLATTRIBUTES(CD.TITLE "Title" , G.GENRE "Genre") , XMLFOREST(CD.PRESSED_DATE "Released" , CD.LIST_PRICE "Price") , XMLAGG(XMLELEMENT("Song" , XMLATTRIBUTES(S.TITLE "Title" , T.TRACK_SEQ_NO "Track") , XMLFOREST(S.RECORDING_DATE "Recorded" , TRIM(S.PLAYING_TIME) "Length")) ))).GETSTRINGVAL() FROM ARTIST A JOIN SONG S ON(S.ARTIST_ID = A.ARTIST_ID) JOIN CDTRACK T ON(T.SONG_ID = S.SONG_ID) JOIN MUSICCD CD ON(CD.MUSICCD_ID = T.MUSICCD_ID) JOIN GENRE G ON(G.GENRE_ID = CD.GENRE_ID) GROUP BY A.NAME, A.CITY, A.COUNTRY, CD.TITLE, G.GENRE , CD.PRESSED_DATE, CD.LIST_PRICE; Figure 17.12 XMLAGG Removes Lowest- Level Duplication Layer. Chap17.fm Page 371 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 372 17.2 Using XML in Oracle The point to make about Figure 17.12 is that all duplication cannot be removed; thus the duplicated artist tags cannot be removed. The reason why is as follows: Even if an XMLAGG function could contain another embedded XMLAGG function, the GROUP BY clause cannot have more than a single layer. There are alternative methods of solving this multilay- ered duplication issue. Obviously, other XML generation methods can be used. Additionally, a CAST(MULTISET(… into a nested table for each subset may help. Other obvious answers are a FROM clause inline view embedded subquery and using PL/SQL, which may be the best option. Another point to make is that if programming languages have to be resorted to at the second layer of a hierarchy, then something like PL/SQL may be the better option than SQL/XML. In PL/SQL or another programming language, the complex query we have been using would be a simple multi- layered nested cursor procedure, dumping values using the DBMS_OUTPUT procedure. Therefore, I will not pursue this topic any further using SQL/XML. See Chapter 24 for details on PL/SQL. The SYS_XMLGEN function in the next section shows multilayered capabilities using CAST(MULTISET(… functionality and user-defined types. I still think PL/SQL might be easier to code. 17.2.1.2.2 The SYS_XMLGEN Function The SYS_XMLGEN function creates an XML document for each row read. Unfortunately, this function does not appear to work properly in my current release of Oracle Database 10g, but this is more or less how it is sup- posed to work. In general, it passes subset row arrays into subset type arrays (nested tables). CREATE OR REPLACE TYPE tSONG AS OBJECT( TITLE VARCHAR2(64), RECORDING_DATE DATE , PLAYING_TIME CHAR(10)); / CREATE OR REPLACE TYPE tSONG_LIST AS TABLE OF tSONG; / CREATE OR REPLACE TYPE tARTIST AS OBJECT( NAME VARCHAR2(32), CITY VARCHAR2(32) , COUNTRY VARCHAR2(32), SONG_LIST tSONG_LIST); / SELECT SYS_XMLGEN(tARTIST(A.NAME, A.CITY, A.COUNTRY, CAST(MULTISET(SELECT tSONG(S.TITLE , S.RECORDING_DATE, S.PLAYING_TIME) Chap17.fm Page 372 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17.2 Using XML in Oracle 373 Chapter 17 FROM SONG S WHERE S.ARTIST_ID = A.ARTIST_ID) AS tSONG_LIST))).GETCLOBVAL() AS ARTISTXML FROM ARTIST A; Now let’s look at how XML documents can be changed in an Oracle database. 17.2.2 XML and the Database In this section we examine XML and Oracle Database in three ways: (1) creating new XML documents in the database; (2) retrieving XML docu- ments stored in the database, both in whole and in part; and (3) changing XML documents stored in the database. 17.2.2.1 New XML Documents This command creates a table to store XML documents. This same table creation command has already been shown earlier in this chapter but is repeated here for convenience. CREATE TABLE XML (ID NUMBER NOT NULL, XML XMLType , CONSTRAINT XPK_XML PRIMARY KEY (ID)); There are various methods of adding XML data to a database. In short, an XML document string can be added as a CLOB object, typecast as XMLType datatype from a string, or added using XMLELEMENT and similar SQL/XML functions. The XMLELEMENT function produces an XMLType datatype. In this case, the query shown following is described by the XML document shown in Figure 17.12. This INSERT command will create an XMLType data object in the XML table just created. INSERT INTO XML(ID,XML) SELECT CD.MUSICCD_ID, XMLELEMENT("Artist" , XMLATTRIBUTES(A.NAME "Name") , XMLFOREST(A.CITY "City", A.COUNTRY "Country") , XMLELEMENT("CD", XMLATTRIBUTES(CD.TITLE "Title" , G.GENRE "Genre") , XMLFOREST(CD.PRESSED_DATE "Released" , CD.LIST_PRICE "Price") , XMLAGG(XMLELEMENT("Song", XMLATTRIBUTES(S.TITLE "Title" Chap17.fm Page 373 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 374 17.2 Using XML in Oracle , T.TRACK_SEQ_NO "Track") , XMLFOREST(S.RECORDING_DATE "Recorded" , TRIM(S.PLAYING_TIME) "Length"))))) FROM ARTIST A JOIN SONG S ON(S.ARTIST_ID = A.ARTIST_ID) JOIN CDTRACK T ON(T.SONG_ID = S.SONG_ID) JOIN MUSICCD CD ON(CD.MUSICCD_ID = T.MUSICCD_ID) JOIN GENRE G ON(G.GENRE_ID = CD.GENRE_ID) GROUP BY CD.MUSICCD_ID, A.NAME, A.CITY, A.COUNTRY, CD.TITLE , G.GENRE, CD.PRESSED_DATE, CD.LIST_PRICE; That was easy! Now let’s find out how to retrieve XML data. 17.2.2.2 Retrieving from XML Documents XMLType datatype column values can be retrieved using SQL SELECT commands, XML extraction functions, and special Oracle text operators. When extracting CLOB values, the SET LONG <lots> command is required in SQL*Plus in order to show enough of the string value in the CLOB object. SET LONG 80 is the default and restricts width to 80 char- acters, which is not much when it comes to XML. Here are four simple examples for showing entire XML value contents. The first two examples will return the entire XML value in a single row on a single line. The third and fourth examples will beautify the result, as shown in Figure 17.13. The fourth example specifically must have SET LONG <lots> applied, other- wise only one row will be returned. SET LONG 2000; SELECT X.XML.GETSTRINGVAL() AS Artist FROM XML X WHERE ID = 4; SELECT X.XML.GETCLOBVAL() AS Artist FROM XML X WHERE ID = 4; SELECT X.XML.EXTRACT('/*') AS Artist FROM XML X WHERE ID = 4; SELECT XML FROM XML WHERE ID = 4; Now let’s examine how to extract individual pieces from within an XML document. XML document subset parts are searched for and retrieved using pattern-matching methods and various functions. Pattern-matching methods are similar to regular expressions (see Chapter 14). An XML docu- ment is effectively parsed for specific strings or tags and then the parts within the matched patterns are returned. Various standard pattern-match- ing characters are used for XML subset searches: Chap17.fm Page 374 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17.2 Using XML in Oracle 375 Chapter 17  /. Specifies a root node either as the root of an entire XML tree or a subtree, and used as a multiple-path specification separation charac- ter. Thus Artist/CD/Song/Length finds all CDs with a Length tag.  //. Finds all child elements from a specified root. Therefore, /Artist// Length finds once again all CDs with a Length tag.  [ … ]. Used to build predicates within expressions such as /Art- ist[City="Vienna" or City="Boston"], which finds all artists resident in Vienna and Boston.  @. The @ sign is used in XML to access tag attributes. /Artist/ @Name will find the name Mozart in the tag <Artist Name="Mozart">. Before we show some examples, there are several functions we need to cover in addition to pattern-matching characters already described. Figure 17.13 Beautifying XMLType Datatype Output. Chap17.fm Page 375 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 376 17.2 Using XML in Oracle  EXISTSNODE (XMLType object, search path, expression). Searches for the expression in a path (search path) within an XML document XMLType object. This function will return 1 if a node exists.  EXTRACT (XMLType object, search path, expression). As already seen, the EXISTSNODE function verifies the presence of a string. The EXTRACT function returns the tag and its contents.  EXTRACTVALUE (XMLType object, search path, expression). This function finds the same strings or patterns as the EXTRACT function except it returns scalar values, as opposed to tags. Therefore, where the EXTRACT function returns <City>Los Angeles</City>, the EXTRACTVALUE function returns the value between the City tags, namely Los Angeles. Now let’s demonstrate by example. The first example finds the CD iden- tifier where that CD has at least one Length value (SONG.PLAYING_TIME) in its structure: SELECT ID FROM XML WHERE EXISTSNODE(XML , 'Artist/CD/Song/Length') = 1; This query will verify the previous query by looking at the data in the tables. Figure 17.14 shows both of these queries put together. Figure 17.14 Demonstrating /, //, and EXISTSNODE. Chap17.fm Page 376 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17.2 Using XML in Oracle 377 Chapter 17 SELECT DISTINCT(MUSICCD_ID) FROM CDTRACK WHERE SONG_ID IN (SELECT SONG_ID FROM SONG WHERE PLAYING_TIME IS NOT NULL); The next example extracts every City tag and the value within every City tag for all entries in the XML document. The result is shown in Figure 17.15. COLUMN TAG FORMAT A32 COLUM CITY FORMAT A20 SELECT ID, EXTRACT(XML, '/Artist/City') AS Tag , EXTRACTVALUE(XML, '/Artist/City') AS City FROM XML; The next two examples use EXTRACT to retrieve, EXISTSNODE to validate and predicate pattern matching to find multiple elements. Results are shown in Figures 17.16 and 17.17. Figure 17.15 Demonstrating EXTRACT and EXTRACTVALUE. Chap17.fm Page 377 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 378 17.2 Using XML in Oracle SELECT ID, EXTRACT(XML, '/Artist[City="Vienna"]') FROM XML WHERE EXISTSNODE(XML, '/Artist[City="Vienna"]') = 1; SELECT ID, EXTRACT(XML, '/Artist[City="Vienna" or City="Boston"]') FROM XML WHERE EXISTSNODE(XML, '/Artist[City="Vienna" or City="Boston"]') = 1; That covers data retrieval for XML documents in Oracle SQL. 17.2.2.3 Changing and Removing XML Document Content An XML document is stored internally as a CLOB or large binary text object. As a result, updating the contents of an XML document in an Figure 17.16 Demonstrating EXTRACT, EXISTSNODE, and a Single-Value Pattern Match. Figure 17.17 Demonstrating EXTRACT, EXISTSNODE, and a Multiple- Value Pattern Match. Chap17.fm Page 378 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17.2 Using XML in Oracle 379 Chapter 17 XMLType datatype simply replaces the entire document. The easiest method of changing XML document content is using the UPDATEXML function.  UPDATEXML(XMLType object, search path, expression [, search path, expression ], 'replace string'). The UPDATEXML function can be used to change pattern-matched parts of XML documents. There are some important things to remember about the UPDA- TEXML function:  UPDATEXML can be used to update single tags, tag attributes, and even entire subtrees.  Deleting XML document content is essentially the same as updating. If a value is to be removed, simply find it and set it to NULL using UPDATEXML.  Remember that the UPDATEXML function can only find and update what already exists in the XML structure. If some values are null valued when initially creating an XML document from relational tables, those values will not exist in the XML document at all, not even as tags. The only method of using UPDATEXML in this situa- tion is to edit an entire parent tag. Let’s change Mozart’s name and city as shown in Figures 17.15, 17.16, and 17.17. The result is shown in Figure 17.18. SET LONG 2000 WRAP ON LINESIZE 5000; UPDATE XML SET XML = UPDATEXML(XML, '/Artist/City/text()', 'Wien') WHERE ID = 12; UPDATE XML SET XML = UPDATEXML(XML, '/Artist/@Name', 'Wolfgang Amadeus Mozart') WHERE ID = 12; SELECT X.XML.EXTRACT('/*') FROM XML X WHERE X.ID = 12; Chap17.fm Page 379 Thursday, July 29, 2004 10:12 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... XML schemas This chapter has attempted to introduce the use of XML directly from within Oracle SQL XML is vastly more complex and detailed than presented in this chapter, both with respect to XML itself and to that of Oracle software This chapter is merely included to present the usefulness of XML with respect to both Oracle Database and relational databases in general The next chapter will begin coverage... items are stored in tables in an Oracle schema A schema is the Oracle user that owns the tables A user and a schema are the same thing as far as Oracle Database is concerned An Oracle relational database can contain many Oracle schemas A schema in Oracle is the equivalent of a single database in other relational databases such as Sybase or Ingres 18.1.1 Types of Tables Oracle Database 10g supports many... at first glance in Oracle documentation However, the focus of this book is on Oracle SQL and not database administration Database administration functionality for the CREATE TABLE command includes any physical storage parameters such as tablespace locations and most types of physical properties Therefore, we get to leave a lot of the syntax out because we are only dealing with Oracle SQL This makes it... part and parcel of an add-on option called Oracle Partitioning Oracle Partitioning working in concert with parallel processing and separate disk spindles or RAID arrays can provide fairly substantial performance improvements Oracle Partitioning and parallelism is an immense subject all by itself.2 Additionally, numerous interesting tricks can be done when using Oracle Partitioning All we want to do in... Database and relational databases in general The next chapter will begin coverage of Data Definition Language (DDL) commands by looking at tables 17.4 Endnotes 1 www.oracledbaexpert.com/menu/HTML.html 2 www.oracledbaexpert.com/menu/DHTML.html 3 www.oracledbaexpert.com/menu/xml.html 4 www.incits.org Chapter 17 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark This page intentionally... constraint prohibiting a column from being empty within a row Other than those points, the only thing to note is that DEFAULT clauses have been added to allow for column values with nothing added to them Various numeric columns will be set to zero if a row is added to the SALES where those defaulted columns are not specified In these cases, null values will be replaced with default values specified Note that the... stored with indexes, increasing data access performance Performance especially improves when the joined tables are most commonly accessed together, such as in a view or join query A cluster is much more of an index than an IOT is and therefore is covered in detail in Chapter 21 External Table A read-only table storing data external to the database, such as in a text file XMLType Table A table with an Oracle. .. divide rows, resulting in the most consistently sized partitions Composite Partitions Contains subpartitions within each separate partition: Range-Hash A range partition containing hash subpartitions within each range partition Range-List A range partition containing list value subpartitions within each range partition 18.3.6.1.1 Partition Indexing Partitions can have indexes How are indexes built for... listed in this section on Oracle Partitioning do not contain all available table creation partitioning syntax There is simply too much detail to include in this book Examples will suffice to get you started syntactically Refer to Oracle documentation for more information Note: CREATE TABLE partition syntax is shown in Figures 18.13 to 18.17 These syntax diagrams are cumulative with respect to annotations... create a table? How do we change and destroy tables? How are comments added to tables? What is the recycle bin? This chapter shows you how to do all sorts of stuff with tables Creating and changing of tables includes defining and creating structure within tables and making changes to those structures Subsequent chapters cover views and constraints This chapter concentrates solely on tables 18.1 What Is a . from within Oracle SQL. XML is vastly more complex and detailed than pre- sented in this chapter, both with respect to XML itself and to that of Oracle. an Oracle schema. A schema is the Oracle user that owns the tables. A user and a schema are the same thing as far as Oracle Database is concerned. An Oracle

Ngày đăng: 24/12/2013, 12:17

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan