Tài liệu Oracle PL/SQL by Example- P10 ppt

50 364 0
Tài liệu Oracle PL/SQL by Example- P10 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

LAB 18.2 The BULK COLLECT Clause LAB OBJECTIVE After completing this lab, you will be able to . Use the BULK COLLECT clause The BULK COLLECT clause fetches the batches of results and brings them back from SQL to PL/SQL. For example, consider a cursor against the STUDENT table that returns the student’s ID, first name, and last name. After this cursor is opened, the rows are fetched one by one until all of them have been processed. Then this cursor is closed. These steps are illustrated in the following example: FOR EXAMPLE DECLARE CURSOR student_cur IS SELECT student_id, first_name, last_name FROM student; BEGIN FOR rec IN student_cur LOOP DBMS_OUTPUT.PUT_LINE ('student_id: '||rec.student_id); DBMS_OUTPUT.PUT_LINE ('first_name: '||rec.first_name); DBMS_OUTPUT.PUT_LINE ('last_name: '||rec.last_name); END LOOP; END; Recall that the cursor FOR loop opens and closes the cursor and fetches cursor records implicitly. The same task of fetching records from the STUDENT table can be accomplished by employing the BULK COLLECT clause. The difference here is that the BULK COLLECT clause fetches all rows from the STUDENT table at once. Because BULK COLLECT fetches multiple rows, these rows are stored in collection variables. Consider a modified version of the previous example, in which the cursor processing is replaced by the BULK COLLECT clause: LAB 18.2 422 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. FOR EXAMPLE DECLARE Define collection type and variables to be used by the BULK COLLECT clause TYPE student_id_type IS TABLE OF student.student_id%TYPE; TYPE first_name_type IS TABLE OF student.first_name%TYPE; TYPE last_name_type IS TABLE OF student.last_name%TYPE; student_id_tab student_id_type; first_name_tab first_name_type; last_name_tab last_name_type; BEGIN Fetch all student data at once via BULK COLLECT clause SELECT student_id, first_name, last_name BULK COLLECT INTO student_id_tab, first_name_tab, last_name_tab FROM student; FOR i IN student_id_tab.FIRST student_id_tab.LAST LOOP DBMS_OUTPUT.PUT_LINE ('student_id: '||student_id_tab(i)); DBMS_OUTPUT.PUT_LINE ('first_name: '||first_name_tab(i)); DBMS_OUTPUT.PUT_LINE ('last_name: '||last_name_tab(i)); END LOOP; END; This script declares three nested table types and variables. These variables are used to store data returned by the SELECT statement with the BULK COLLECT clause. DID YOU KNOW? When nested tables are populated using the SELECT BULK COLLECT INTO statement, they are initial- ized and extended automatically. Recall that typically a nested table must be initialized prior to its use by calling a constructor function that has the same name as its nested table type. After it has been initialized, it must be extended using the EXTEND method before the next value can be assigned to it. To display this data, the collections are looped through using a numeric FOR loop. Note how lower and upper limits for the loop counter are specified using the FIRST and LAST methods. The BULK COLLECT clause is similar to a cursor loop in that it does not raise a NO_DATA_ FOUND exception when the SELECT statement does not return any records. As a result, it is considered a good practice to check if a resulting collection contains any data. Because the BULK COLLECT clause does not restrict the size of a collection and extends it auto- matically, it is also a good idea to limit the result set when a SELECT statement returns large LAB 18.2 The BULK COLLECT Clause 423 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. amounts of data. This can be achieved by using BULK COLLECT with a cursor SELECT and by adding the LIMIT option. FOR EXAMPLE DECLARE CURSOR student_cur IS SELECT student_id, first_name, last_name FROM student; Define collection type and variables to be used by the BULK COLLECT clause TYPE student_id_type IS TABLE OF student.student_id%TYPE; TYPE first_name_type IS TABLE OF student.first_name%TYPE; TYPE last_name_type IS TABLE OF student.last_name%TYPE; student_id_tab student_id_type; first_name_tab first_name_type; last_name_tab last_name_type; Define variable to be used by the LIMIT clause v_limit PLS_INTEGER := 50; BEGIN OPEN student_cur; LOOP Fetch 50 rows at once FETCH student_cur BULK COLLECT INTO student_id_tab, first_name_tab, last_name_tab LIMIT v_limit; EXIT WHEN student_id_tab.COUNT = 0; FOR i IN student_id_tab.FIRST student_id_tab.LAST LOOP DBMS_OUTPUT.PUT_LINE ('student_id: '||student_id_tab(i)); DBMS_OUTPUT.PUT_LINE ('first_name: '||first_name_tab(i)); DBMS_OUTPUT.PUT_LINE ('last_name: '||last_name_tab(i)); END LOOP; END LOOP; CLOSE student_cur; END; This script employs a BULK COLLECT clause with the LIMIT option to fetch 50 rows from the STUDENT table at once. In other words, each collection contains, at most, 50 records. To accomplish this, the BULK COLLECT clause is used in conjunction with the cursor loop. Note LAB 18.2 424 The BULK COLLECT Clause Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. that in this case, the loop’s exit condition is based on the number of records in the collection rather than the student_cur%NOTFOUND attribute. Note how the numeric FOR loop that displays information on the screen has been moved inside the cursor loop. This is done because every new batch of 50 records fetched by the BULK COLLECT replaces the previous batch of 50 records fetched in the previous iteration. So far you have seen examples of the BULK COLLECT clause fetching data into collections where the underlying elements are simple data types such as NUMBER or VARCHAR2. However, the BULK COLLECT clause can be used to fetch data into collections of records or objects. Collections of objects are discussed in Chapter 23, “Object Types in Oracle.” Consider a modified version of the previous example, in which student data is fetched into a collection of user-defined records: FOR EXAMPLE DECLARE CURSOR student_cur IS SELECT student_id, first_name, last_name FROM student; Define record type TYPE student_rec IS RECORD (student_id student.student_id%TYPE, first_name student.first_name%TYPE, last_name student.last_name%TYPE); Define collection type TYPE student_type IS TABLE OF student_rec; Define collection variable student_tab student_type; Define variable to be used by the LIMIT clause v_limit PLS_INTEGER := 50; BEGIN OPEN student_cur; LOOP Fetch 50 rows at once FETCH student_cur BULK COLLECT INTO student_tab LIMIT v_limit; EXIT WHEN student_tab.COUNT = 0; FOR i IN student_tab.FIRST student_tab.LAST LOOP DBMS_OUTPUT.PUT_LINE ('student_id: '||student_tab(i).student_id); DBMS_OUTPUT.PUT_LINE ('first_name: '|| student_tab(i).first_name); LAB 18.2 The BULK COLLECT Clause 425 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. FOR EXAMPLE (continued) DBMS_OUTPUT.PUT_LINE ('last_name: '|| student_tab(i).last_name); END LOOP; END LOOP; CLOSE student_cur; END; So far you have seen how to use the BULK COLLECT clause with the SELECT statement. However, often BULK COLLECT is used with the INSERT, UPDATE, and DELETE statements as well. In this case, the BULK COLLECT clause is used in conjunction with the RETURNING clause, as shown here: FOR EXAMPLE DECLARE Define collection types and variables TYPE row_num_type IS TABLE OF NUMBER INDEX BY PLS_INTEGER; TYPE row_text_type IS TABLE OF VARCHAR2(10) INDEX BY PLS_INTEGER; row_num_tab row_num_type; row_text_tab row_text_type; BEGIN DELETE FROM TEST RETURNING row_num, row_text BULK COLLECT INTO row_num_tab, row_text_tab; DBMS_OUTPUT.PUT_LINE ('Deleted '||SQL%ROWCOUNT ||' rows:'); FOR i IN row_num_tab.FIRST row_num_tab.LAST LOOP DBMS_OUTPUT.PUT_LINE ('row_num = '||row_num_tab(i)|| ' row_text = ' ||row_text_tab(i)); END LOOP; COMMIT; END; This script deletes records from the TEST table created in Lab 18.1. Note that the DELETE state- ment returns ROW_NUM and ROW_TEXT values using the RETURNING clause. These values are then fetched by the BULK COLLECT clause into two collections, row_num_tab and row_text_tab, which are displayed on the screen. When run, this script produces the following output: Deleted 7 rows: row_num = 2 row_text = row 2 LAB 18.2 426 The BULK COLLECT Clause Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. row_num = 3 row_text = row 3 row_num = 4 row_text = row 4 row_num = 6 row_text = row 6 row_num = 8 row_text = row 8 row_num = 9 row_text = row 9 row_num = 10 row_text = row 10 PL/SQL procedure successfully completed. Throughout this chapter you have seen how to use the FORALL statement and BULK COLLECT clause. Next, consider an example that combines both. This example is based on the script ch18_1a.sql, which selects some data from the ZIPCODE table and inserts it into the MY_ZIPCODE table. Changes are shown in bold. FOR EXAMPLE DECLARE Declare collection types TYPE string_type IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER; TYPE date_type IS TABLE OF DATE INDEX BY PLS_INTEGER; Declare collection variables to be used by the FORALL statement zip_tab string_type; city_tab string_type; state_tab string_type; cr_by_tab string_type; cr_date_tab date_type; mod_by_tab string_type; mod_date_tab date_type; v_counter PLS_INTEGER := 0; v_total INTEGER := 0; BEGIN Populate individual collections SELECT * BULK COLLECT INTO zip_tab, city_tab, state_tab, cr_by_tab, cr_date_tab, mod_by_tab, mod_date_tab FROM zipcode WHERE state = 'CT'; Populate MY_ZIPCODE table FORALL i in 1 zip_tab.COUNT INSERT INTO my_zipcode (zip, city, state, created_by, created_date, modified_by, modified_date) VALUES (zip_tab(i), city_tab(i), state_tab(i), cr_by_tab(i), cr_date_tab(i), mod_by_tab(i), mod_date_tab(i)); COMMIT; LAB 18.2 The BULK COLLECT Clause 427 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ▼ FOR EXAMPLE (continued) Check how many records were added to MY_ZIPCODE table SELECT COUNT(*) INTO v_total FROM my_zipcode WHERE state = 'CT'; DBMS_OUTPUT.PUT_LINE (v_total||' records were added to MY_ZIPCODE table'); END; LAB 18.2 EXERCISES This section provides exercises and suggested answers, with discussion related to how those answers resulted. The most important thing to realize is whether your answer works.You should figure out the implications of the answers and what the effects are of any different answers you may come up with. 18.2.1 Use the BULK COLLECT Statement In this exercise, you create various scripts that select and modify data in the MY_INSTRUCTOR table in bulk. Create the MY_INSTRUCTOR table as follows. If this table already exists, drop it and then re-create it. CREATE TABLE my_instructor AS SELECT * FROM instructor; Complete the following tasks: A) Create the following script: Select the instructor ID, first name, and last name from the MY_INSTRUCTOR table, and display them on the screen. Note that the data should be fetched in bulk. ANSWER: This script should look similar to the following: ch18_2a.sql, version 1.0 SET SERVEROUTPUT ON; DECLARE Define collection types and variables to be used by the BULK COLLECT clause TYPE instructor_id_type IS TABLE OF my_instructor.instructor_id%TYPE; TYPE first_name_type IS TABLE OF my_instructor.first_name%TYPE; TYPE last_name_type IS TABLE OF my_instructor.last_name%TYPE; instructor_id_tab instructor_id_type; first_name_tab first_name_type; last_name_tab last_name_type; BEGIN Fetch all instructor data at once via BULK COLLECT clause LAB 18.2 428 Lab 18.2 Exercises Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. SELECT instructor_id, first_name, last_name BULK COLLECT INTO instructor_id_tab, first_name_tab, last_name_tab FROM my_instructor; FOR i IN instructor_id_tab.FIRST instructor_id_tab.LAST LOOP DBMS_OUTPUT.PUT_LINE ('instructor_id: '||instructor_id_tab(i)); DBMS_OUTPUT.PUT_LINE ('first_name: '||first_name_tab(i)); DBMS_OUTPUT.PUT_LINE ('last_name: '||last_name_tab(i)); END LOOP; END; The declaration portion of this script contains definitions of three collection types and variables. The executable portion of the script populates collection variables using the SELECT statement with the BULK COLLECT clause. Finally, it displays on the screen data stored in the collection variables by looping through them. When run, this script produces the following output: instructor_id: 101 first_name: Fernand last_name: Hanks instructor_id: 102 first_name: Tom last_name: Wojick instructor_id: 103 first_name: Nina last_name: Schorin instructor_id: 104 first_name: Gary last_name: Pertez instructor_id: 105 first_name: Anita last_name: Morris instructor_id: 106 first_name: Todd last_name: Smythe instructor_id: 107 first_name: Marilyn last_name: Frantzen instructor_id: 108 first_name: Charles last_name: Lowry instructor_id: 109 first_name: Rick last_name: Chow instructor_id: 110 first_name: Irene last_name: Willig PL/SQL procedure successfully completed. LAB 18.2 Lab 18.2 Exercises 429 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. As mentioned previously, the BULK COLLECT clause is similar to the cursor loop in that it does not raise a NO_DATA_FOUND exception when the SELECT statement does not return any rows. Consider deleting all the rows from the MY_INSTRUCTOR table and then executing this script again. In this case the output is as follows: SQL> DELETE FROM my_instructor; 10 rows deleted. SQL> SET SERVEROUTPUT ON; SQL> DECLARE 2 Define collection types and variables to be used by the 3 BULK COLLECT clause 4 TYPE instructor_id_type IS TABLE OF my_instructor.instructor_id%TYPE; 5 TYPE first_name_type IS TABLE OF my_instructor.first_name%TYPE; 6 TYPE last_name_type IS TABLE OF my_instructor.last_name%TYPE; 7 8 instructor_id_tab instructor_id_type; 9 first_name_tab first_name_type; 10 last_name_tab last_name_type; 11 12 BEGIN 13 Fetch all instructor data at once via BULK COLLECT clause 14 SELECT instructor_id, first_name, last_name 15 BULK COLLECT INTO instructor_id_tab, first_name_tab, last_name_tab 16 FROM my_instructor; 17 18 FOR i IN instructor_id_tab.FIRST instructor_id_tab.LAST 19 LOOP 20 DBMS_OUTPUT.PUT_LINE ('instructor_id: '||instructor_id_tab(i)); 21 DBMS_OUTPUT.PUT_LINE ('first_name: '||first_name_tab(i)); 22 DBMS_OUTPUT.PUT_LINE ('last_name: '||last_name_tab(i)); 23 END LOOP; 24 END; 25 / You see the following error message: DECLARE * ERROR at line 1: ORA-06502: PL/SQL: numeric or value error ORA-06512: at line 18 Note that the error message refers to line 18, which contains a FOR loop that iterates through the collections and displays the results on the screen. Note that the SELECT statement with the BULK LAB 18.2 430 Lab 18.2 Exercises Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. COLLECT clause does not cause any errors.To prevent this error from happening, you can modify the script as follows. Changes are shown in bold. ch18_2b.sql, version 2.0 SET SERVEROUTPUT ON; DECLARE Define collection types and variables to be used by the BULK COLLECT clause TYPE instructor_id_type IS TABLE OF my_instructor.instructor_id%TYPE; TYPE first_name_type IS TABLE OF my_instructor.first_name%TYPE; TYPE last_name_type IS TABLE OF my_instructor.last_name%TYPE; instructor_id_tab instructor_id_type; first_name_tab first_name_type; last_name_tab last_name_type; BEGIN Fetch all instructor data at once via BULK COLLECT clause SELECT instructor_id, first_name, last_name BULK COLLECT INTO instructor_id_tab, first_name_tab, last_name_tab FROM my_instructor; IF instructor_id_tab.COUNT > 0 THEN FOR i IN instructor_id_tab.FIRST instructor_id_tab.LAST LOOP DBMS_OUTPUT.PUT_LINE ('instructor_id: '||instructor_id_tab(i)); DBMS_OUTPUT.PUT_LINE ('first_name: '||first_name_tab(i)); DBMS_OUTPUT.PUT_LINE ('last_name: '||last_name_tab(i)); END LOOP; END IF; END; This version of the script contains an IF-THEN statement that encloses the FOR loop.The IF-THEN statement checks if one of the collections is nonempty, thus preventing the numeric or value error. WATCH OUT! If you have deleted records from the MY_INSTRUCTOR table, you need to roll back your changes or populate it with the records from the INSTRUCTOR table again before proceeding with the exercise. B) Modify the newly created script as follows: Fetch no more than five rows at a time from the MY_INSTRUCTOR table. ANSWER: The script should look similar to the following. Changes are shown in bold. ch18_2c.sql, version 3.0 SET SERVEROUTPUT ON; DECLARE CURSOR instructor_cur IS LAB 18.2 Lab 18.2 Exercises 431 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... name implies, anonymous blocks have no name and thus cannot be called by another block They are not stored in the database and must be compiled and then run each time the script is loaded The PL/SQL block in a subprogram is a named block that can accept parameters and that can be invoked from an application that can communicate with the Oracle database server A subprogram can be compiled and stored in... CHAPTER 19 Procedures CHAPTER OBJECTIVES In this chapter, you will learn about Creating procedures Passing parameters into and out of procedures All the PL/SQL you have written up to this point has been anonymous blocks that were run as scripts and compiled by the database server at runtime Now you will begin using modular code Modular code is a way to build a program from distinct parts (modules), each... and how to write the type of stored code known as procedures In Lab 19.2, you will learn about passing parameters into and out of procedures BENEFITS OF MODULAR CODE A PL/SQL module is any complete logical unit of work The five types of PL/SQL modules are anonymous blocks that are run with a text script (this is the type you have used so far), procedures, functions, packages, and triggers Using modular... collection of records In this version, the collection type is based on the row type record returned by the cursor: ch18_2e.sql, version 5.0 SET SERVEROUTPUT ON; DECLARE CURSOR instructor_cur IS SELECT instructor_id, first_name, last_name FROM my_instructor; Define collection type and variable to be used by the BULK COLLECT clause TYPE instructor_type IS TABLE OF instructor_cur%ROWTYPE; instructor_tab... you may come up with 20.1.1 Create Stored Functions This exercise starts by creating your first function A) Put the create script for the function in the preceding example into a text file Open SQL*Plus, log into the student schema, and run the script from the preceding example What do you expect to see? Explain the function line by line ANSWER: When a function has been compiled without errors, the SQL*Plus... variable called v_description that is used later on by the RETURN clause This variable stores the value of the description of the course provided at the run time, and is initialized via the SELECT INTO statement Once initialized, the value of the v_description variable is returned to the calling environment via the RETURN clause Note the two exceptions employed by the function The first is the NO_DATA_FOUND... remove this watermark Lab 20.1 Exercises LAB 20.1 453 ANSWER: Because the PL/SQL block has a lexical parameter of &cnumber, the user is prompted as follows: Enter value for cnumber: If you enter 350, you see the following: old 4: v_descript := show_description(&sv_cnumber); new 4: v_descript := show_description(350); Java Developer II PL/SQL procedure successfully completed This means that the value for... SELECT statement: SELECT UPPER('bill') FROM DUAL; The Oracle- supplied function UPPER is a function that returns the uppercase value of the parameter that was passed in Note that for a user-defined function to be called in a SQL expression, it must be a ROW function, not a GROUP function, and the datatypes must be SQL datatypes The datatypes cannot be PL/SQL datatypes such as Boolean, table, or record... instructor_rec IS RECORD (instructor_id my_instructor.instructor_id%TYPE, first_name my_instructor.first_name%TYPE, last_name my_instructor.last_name%TYPE); Define collection type and variable to be used by the BULK COLLECT clause TYPE instructor_type IS TABLE OF instructor_rec; instructor_tab instructor_type; v_limit PLS_INTEGER := 5; BEGIN OPEN instructor_cur; LOOP Fetch partial instructor data at... triggers Using modular code offers two main benefits: It is more reusable, and it is more manageable You create a procedure either in SQL*Plus or in one of the many tools for creating and debugging stored PL/SQL code If you are using SQL*Plus, you need to write your code in a text editor and then run it at the SQL*Plus prompt Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark CHAPTER . state, created _by, created_date, modified _by, modified_date) VALUES (zip_tab(i), city_tab(i), state_tab(i), cr _by_ tab(i), cr_date_tab(i), mod _by_ tab(i), mod_date_tab(i)); COMMIT; LAB. VARCHAR2(100) INDEX BY PLS_INTEGER; TYPE date_type IS TABLE OF DATE INDEX BY PLS_INTEGER; Declare collection variables to be used by the FORALL statement zip_tab

Ngày đăng: 21/01/2014, 08:20

Từ khóa liên quan

Mục lục

  • Oracle PL/SQL by example

  • Contents

  • Acknowledgments

  • About the Authors

  • Introduction

  • CHAPTER 1 PL/SQL Concepts

    • LAB 1.1 PL/SQL in Client/Server Architecture

      • 1.1.1 Use PL/SQL Anonymous Blocks

      • 1.1.2 Understand How PL/SQL Gets Executed

      • LAB 1.2 PL/SQL in SQL*Plus

        • 1.2.1 Use Substitution Variables

        • 1.2.2 Use the DBMS_OUTPUT.PUT_LINE Statement

        • Chapter 1 Try It Yourself

        • CHAPTER 2 General Programming Language Fundamentals

          • LAB 2.1 PL/SQL Programming Fundamentals

            • 2.1.1 Make Use of PL/SQL Language Components

            • 2.1.2 Make Use of PL/SQL Variables

            • 2.1.3 Handle PL/SQL Reserved Words

            • 2.1.4 Make Use of Identifiers in PL/SQL

            • 2.1.5 Make Use of Anchored Datatypes

            • 2.1.6 Declare and Initialize Variables

            • 2.1.7 Understand the Scope of a Block, Nested Blocks, and Labels

            • Chapter 2 Try It Yourself

            • CHAPTER 3 SQL in PL/SQL

              • LAB 3.1 Making Use of DML in PL/SQL

                • 3.1.1 Use the Select INTO Syntax for Variable Initialization

                • 3.1.2 Use DML in a PL/SQL Block

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

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

Tài liệu liên quan