Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
2,26 MB
Nội dung
320 15.2 Transaction Control your DML command to fail rather than wait if another user is updating the same row you try to update. Another common use is assigning large trans- actions to very large rollback segments. Figure 15.2 shows the syntax of the SET TRANSACTION command Let’s query an ARTIST row and start a read-only transaction using the following commands. SQL*Plus Worksheet displays “Transaction set.” in the lower pane. The result is shown in Figure 15.3. SELECT ARTIST_ID, NAME, ZIP FROM ARTIST WHERE NAME = 'Puddle of Mudd'; SET TRANSACTION READ ONLY; Now let’s try to change the zip code using the following script. UPDATE ARTIST SET ZIP='10099' WHERE NAME = 'Puddle of Mudd'; Figure 15.4 shows an error message. No changes can be made to the database inside a read-only transaction. In addition, a read-only transaction does not see changes to the database made by other users after the transac- tion starts. This might be useful when you are generating a set of reports that summarize data and must be consistent from beginning to end. For Figure 15.3 A Transaction Is Set. Chap15.fm Page 320 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15.2 Transaction Control 321 Chapter 15 example, you run a summary of sales from the beginning of the year up to today and then (in the same transaction) run a detail report of sales activity. If users are updating the SALES table between your first and second reports, the two reports will not match. Use a read-only transaction to pre- serve the state of the database when you begin the first report. Note: Setting read-only transactions can cause serious concurrency issues for other users. Applications will not be able to respond properly when other users preserve data for exclusive use. This type of activity is inadvis- able because it could upset end users (your clients). The default transaction setting is READ WRITE, which allows changes and sees other users’ changes immediately after being committed. The current transaction can be completed using the COMMIT or ROLLBACK commands. Other options are transaction isolation levels, which can be set to SERI- ALIZABLE or READ COMMITTED. The default mode is ISOLATION LEVEL READ COMMITTED, where SQL will wait until any locks on data it wants to modify are released. Using the SET TRANSACTION ISO- LATION LEVEL SERIALIZABLE command, SQL commands handle locking differently. If a problem is encountered, the SERIALIZABLE option will cause a transaction to fail immediately without waiting. This can be useful in a batch job that runs overnight, where it is preferable to stop the entire batch job as opposed to risking the overnight job spilling over into daytime hours. Figure 15.4 Read-Only Transactions Prevent Database Changes. Chap15.fm Page 321 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 322 15.2 Transaction Control Note: Once again, be aware of conflict with concurrent applications and potentially upsetting clients. 15.2.3 The SAVEPOINT Command Another transaction-related command you may want to use is the SAVE- POINT command. The syntax is simply as follows, where the label implies a point within a transaction to undo changes back to: SAVEPOINT label; SAVEPOINT is useful when you are making many changes to the data- base and you want the ability to undo only part of the changes made. For example, you have inserted some testing rows into a table specifically to test an UPDATE command. You want to be able to undo the UPDATE com- mand while keeping the inserted rows. This way, you can repeat the UPDATE command. Demonstrating using the SAVEPOINT command, we can do the fol- lowing: Begin by updating a zip code and creating a target label (SAVE- POINT). Then make a different change to the same row already updated and query to see row changes. The result of the following script is shown in Figure 15.5. UPDATE ARTIST SET ZIP='10099' WHERE NAME = 'Puddle of Mudd'; SAVEPOINT AFTERUPDATE; UPDATE ARTIST SET NAME='Mud Puddle' WHERE NAME = 'Puddle of Mudd'; SELECT ARTIST_ID, NAME, ZIP FROM ARTIST WHERE NAME = 'Mud Puddle'; In the next script, we undo (rollback) the name change, done after the SAVEPOINT label, and query again. We see that the name change no longer exists, but the zip code is still changed. In other words, the first update is stored and the second is removed. The result of the following script is shown in Figure 15.6. Chap15.fm Page 322 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15.2 Transaction Control 323 Chapter 15 ROLLBACK TO SAVEPOINT AFTERUPDATE; SELECT ARTIST_ID, NAME, ZIP FROM ARTIST WHERE NAME = 'Mud Puddle'; SELECT ARTIST_ID, NAME, ZIP FROM ARTIST WHERE NAME = 'Puddle of Mudd'; Finally, we can undo the remaining change from the first UPDATE command and end the transaction using a ROLLBACK command. The rest of this chapter deals with making changes to the database using DML commands to add, change, and remove data. We begin with the INSERT command. Figure 15.5 Two Updates to the Same Row with a SAVEPOINT Label Between the Updates. Chap15.fm Page 323 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 324 15.3 Adding Data (INSERT) 15.3 Adding Data (INSERT) Adding new rows into a table is done with the INSERT command. The INSERT command can be used to add to a single table or multiple tables. The syntax of the single-table INSERT command is shown in Figure 15.7. You can insert one row into a table using expressions, individual subque- ries for each column, or a single subquery for all columns. For a single sub- query filling all columns, use a subquery that retrieves multiple rows instead of a list of literal values. We cover the multiple-table INSERT command shortly. The RETURNING portion of the INSERT, UPDATE, and DELETE statements is essentially PL/SQL (see Chapter 24) but is covered here as well for the sake of completeness. Note: Any literal value such as “hello” or the number 50,000 is an expres- sion. See Chapter 14 for more information on expressions. Figure 15.6 Undo Changes Back to a SAVEPOINT Label. Chap15.fm Page 324 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15.3 Adding Data (INSERT) 325 Chapter 15 15.3.1 Inserting One Row Let’s start with an easy example, adding a single row to the INSTRU- MENT table. INSERT INTO INSTRUMENT VALUES (INSTRUMENT_ID_SEQ.NEXTVAL ,(SELECT INSTRUMENT_ID FROM INSTRUMENT WHERE NAME = 'String') , 'Harp'); You do not need to list what value goes into which column if you list the values in the same order as columns appear in the table, and all table col- umns are filled. In this case, there are only three columns to worry about. The first column uses a sequence that generates a number that is used as the unique identifier for the instrument. See Chapter 22 for details on sequences. The NEXTVAL function always returns the next available value from a sequence. The second column finds the strings section in the INSTRUMENTS table, the same table. The third column adds a new instrument name. Here is an example in which you list the columns in a different order than they appear in the table, additionally omitting columns. INSERT INTO MUSICCD (MUSICCD_ID, TITLE, PLAYING_TIME) VALUES (MUSICCD_ID_SEQ.NEXTVAL, 'SPIDER-MAN','60:35'); Figure 15.7 Single Table INSERT Command Syntax. Chap15.fm Page 325 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 326 15.3 Adding Data (INSERT) When you omit columns, Oracle Database 10 g sets missing columns to null values except when a default value is defined for a column. In that case, Oracle fills the column with the default value. If you omit any non- nullable columns, which do not have a default value setting, then an error will result. 15.3.2 Inserting with a Subquery You can also insert a group of rows all at once using a subquery instead of a list of values. Each row returned by the subquery becomes a row inserted into the table. In this example, we create a table and insert rows using a subquery. CREATE TABLE TESTMUSICCD( TITLE VARCHAR2(32 ) , ARTIST_NAME VARCHAR2(32) NOT NULL , PRESSED_DATE DATE , ARTIST_COUNTRY VARCHAR2(32)); Now we use an INSERT statement to query the ARTIST and MUS- ICCD tables and load the resulting rows into the new table. INSERT INTO TESTMUSICCD SELECT DISTINCT M.TITLE, A.NAME, M.PRESSED_DATE , A.COUNTRY FROM ARTIST A , SONG S, CDTRACK T, MUSICCD M WHERE A.ARTIST_ID = S.ARTIST_ID AND S.SONG_ID = T.SONG_ID AND T.MUSICCD_ID = M.MUSICCD_ID; This INSERT command creates 13 rows at once. Figure 15.8 shows the new rows using the following simple query: SELECT * FROM TESTMUSICCD; The rows in the table have not yet been saved to the database. We could save them by executing a COMMIT command. And now that you have some data in a new table, you can experiment with updates and deletes. However, first let’s examine multiple-table inserts. Chap15.fm Page 326 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15.3 Adding Data (INSERT) 327 Chapter 15 15.3.3 The Multiple-Table INSERT Command Figure 15.9 describes the syntax for the multiple-table form of the INSERT command. Now let’s look at an example, once again using the data warehouse SALES table as a basis. The following query shows a breakdown for the SALES table by retailer. Next, we use the SALES table to create three sepa- rate empty tables. Following that we insert rows into all of the three sepa- rate tables at once. The rows will originate from the SALES table, using a single multiple-table INSERT command, inserting into the three tables based on the retailer data in each row. The initial query is shown in Figure 15.10, showing the breakdown of the SALES table based on retailers (RETAILER_ID). SELECT (SELECT NAME FROM RETAILER WHERE RETAILER_ID = S.RETAILER_ID) "Retailer" , COUNT(S.RETAILER_ID) "Sales" FROM SALES S GROUP BY S.RETAILER_ID; Now we can create three empty tables from the SALES table. The WHERE clause using the ROWNUM < 1 condition is a simple method of copying the structure of the SALES table without copying any rows. See Top-N queries in Chapter 5. Figure 15.8 The New Rows Were Derived from a Subquery Join on Four Tables. Chap15.fm Page 327 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 328 15.3 Adding Data (INSERT) CREATE TABLE AMAZON AS SELECT * FROM SALES WHERE ROWNUM < 1; CREATE TABLE BANDN AS SELECT * FROM SALES WHERE ROWNUM < 1; CREATE TABLE CDSHOP AS SELECT * FROM SALES WHERE ROWNUM < 1; Figure 15.9 Multiple-Table INSERT Command Syntax. Figure 15.10 SALES Table Entries Are Distributed Among Three Different Retailers. Chap15.fm Page 328 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15.3 Adding Data (INSERT) 329 Chapter 15 The following script is the multiple-table INSERT command, filling all three tables with the appropriate rows in the three new tables. In this case, an ELSE clause is not required, and the FIRST option can be used. INSERT FIRST WHEN RETAILER_ID = (SELECT RETAILER_ID FROM RETAILER WHERE NAME = 'Amazon') THEN INTO AMAZON WHEN RETAILER_ID = (SELECT RETAILER_ID FROM RETAILER WHERE NAME = 'Barnes and Noble') THEN INTO BANDN WHEN RETAILER_ID = (SELECT RETAILER_ID FROM RETAILER WHERE NAME = 'CD Shop') THEN INTO CDSHOP SELECT * FROM SALES; Figure 15.11 shows resulting table counts after the execution of the mul- tiple-table INSERT command, distributing sales entries to the three sepa- rate retailer tables. The correct row counts can be verified by comparing row counts between those shown in Figures 15.10 and 15.11. That covers the INSERT command and adding data. Let’s look at other DML commands, starting with the UPDATE command used to change existing data. Figure 15.11 SALES Table Entries Distributed into Three Separate Retailer Tables. Chap15.fm Page 329 Thursday, July 29, 2004 10:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... TIMESTAMP(4) WITH TIME ZONE Same as TIMESTAMP except the value includes the time zone of the user that inserts or updates the value TIMESTAMP(p) WITH LOCAL TIME ZONE p = fractions of a second TIMESTAMP(4) WITH LOCAL TIME ZONE Same as TIMESTAMP except the value converts the date to the time zone of the database, and displays the time in the local time zone for the viewer ROWID None ROWID Internal Oracle datatype... result is shown in Figure 16.5 PL /SQL can be used to access individual VARRAY elements See Chapter 24 for details on PL /SQL SELECT INSTRUMENTS FROM ARTIST; 16.2.4.2 Using Nested Table Collections A nested table is effectively created as a table within another table You will notice in this section frequent use of the keyword TABLE The TABLE keyword is used to access the table within the table, the former... functionality exist? What are special Oracle datatypes? This chapter examines simple, complex, and object datatypes Additionally, this chapter includes user-defined datatypes plus details of special object datatype functions Object functions are included in this chapter because they are specific to object datatypes Object functions do not belong with single-row functions in Chapter 9 or with grouping functions in... in one place Let’s begin with what could be termed simple datatypes 16.1 Simple Datatypes I like to classify simple datatypes as those containing single scalar values, such as strings, numbers, and dates Table 16.1 shows a summary of Oracle simple datatypes 339 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 340 16.1 Simple Datatypes Table 16.1 Oracle Simple Datatypes Datatype... WHERE A.NAME = T.ARTIST_NAME); SQL* Plus Worksheet will reply, “13 rows updated.” Note: Updated rows must comply with any constraints defined for a table If one row does not comply, all rows updated by the statement are automatically rolled back You can also update more than one column, whether you are updating one row or many rows For example, change the title and the country with one update command In... user-defined datatypes 16.2.3 User-Defined Datatypes Creating an object type with the CREATE TYPE command, such as a VARRAY or nested table type, creates a user-defined datatype Oracle sometimes refers to user-defined datatypes as user types All these user-defined datatypes are available for use in column definitions, just like the standard Oracle Database 10g datatypes You will see how this works when you reach... feature of Oracle Database 9i and much improved in Oracle Database 10g Chapter 15 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 336 15.6 Merging New and Old Data (MERGE) The MERGE command enables a combination insert and update to a table using a single DML command 15.6 Merging New and Old Data (MERGE) There are some enhancements to the MERGE command between Oracle Database... UPDATE TESTMUSICCD SET ARTIST_COUNTRY='Brazil' WHERE ARTIST_NAME = 'Jewel'; SQL* Plus Worksheet will reply, “1 row updated.” The same syntax can be used to update more than one row Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 15.4 Changing Data (UPDATE) 15.4.2 331 Updating Many Rows There are three rows with the name and country of Sheryl Crow because there are three of her... CD by typing this DELETE command: DELETE FROM TESTMUSICCD WHERE TITLE = 'C''mon, C''mon'; SQL* Plus Worksheet will reply: “1 row deleted.” Notice the use of quotation marks in the title The title has two single quotes in it where the data actually has a single quote This is called a string escape sequence Because Oracle Database 10g uses single quote marks to delimit literal values, you must indicate... this watermark 340 16.1 Simple Datatypes Table 16.1 Oracle Simple Datatypes Datatype Parameters Example VARCHAR2(n) n = 1 to 4,000 VARCHAR2(25) Text string with variable length up to 4,000 bytes If the column data’s length is shorter than n, Oracle adjusts the length of the column to the size of the data Trailing blanks are truncated Use VARCHAR2 in favor of CHAR to avoid wasting space VARCHAR is . columns, Oracle Database 10 g sets missing columns to null values except when a default value is defined for a column. In that case, Oracle fills the column with. rest of this chapter deals with making changes to the database using DML commands to add, change, and remove data. We begin with the INSERT command. Figure