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

Tài liệu processing queries by using explicit cursors ppt

34 301 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Processing queries by using explicit cursors
Trường học Oracle University
Chuyên ngành Database Management
Thể loại Bài giảng
Định dạng
Số trang 34
Dung lượng 232,64 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Processing Queries by Using Explicit Cursors 24Ć3You may need to use a multiple row SELECT statement within PL/SQL to process many rows.. Processing Queries by Using Explicit Cursors 24Ć

Trang 1

Processing Queries by Using

Explicit Cursors

24

Trang 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć2

Trang 3

Processing Queries by Using Explicit Cursors 24Ć3

You may need to use a multiple row SELECT statement within PL/SQL to process many rows To accomplish this, you declare and control explicit cursors, which are used in loops, including the cursor FOR loop.

At the end of this lesson, you should be able to

D Explain the difference between implicit and explicit cursors

D Declare and use explicit cursors to fetch rows from the database

D Create an explicit cursor containing parameters

D Write cursor FOR loops

Trang 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć4

Trang 5

Processing Queries by Using Explicit Cursors 24Ć5

statements and store processing information PL/SQL cursors let you name a privateSQL area and access its stored information The cursor directs all phases of

processing

Cursor Type Description

Implicit Declared by PL/SQL implicitly for all DML and PL/SQL

SELECT statements

Explicit Declared and named by the programmer and manipulated

through specific statements within the block’s executableactions

Recall that the SELECT statement in PL/SQL must only return a single row PL/SQLactually attempts to fetch two rows from an implicit cursor: one to satisfy the query,and a second to see if further rows were returned One method to eliminate this extrafetch is to use an explicit cursor

Explicit Cursor Functions

D Can process beyond the first row returned by the query, row by row

D Keep track of which row is currently being processed

D Allow the programmer to manually control them in the PL/SQL block

Trang 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć6

Trang 7

Processing Queries by Using Explicit Cursors 24Ć7

them The syntax for each step follows on the next pages

Controlling Explicit Cursors Using Four Commands

1. Declare the cursor

Declare the cursor by naming it and defining the structure of the query to beperformed within it

2. Open the cursor

The OPEN statement executes the query and binds any variables that are

referenced Rows identified by the query are called the active set and are nowavailable for fetching

3. Fetch data from the cursor

The FETCH statement loads the current row from the cursor into variables Eachfetch causes the cursor to move its pointer to the next row in the active set

Therefore, each fetch will access a different row returned by the query

In the flow diagram on the left page, each fetch tests the cursor for any existingrows If rows are found, it loads the current row into variables, else it closes thecursor

4. Close the cursor

The CLOSE statement releases the active set of rows It is now possible to reopenthe cursor to establish a fresh active set

Trang 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć8

Trang 9

Processing Queries by Using Explicit Cursors 24Ć9

Declaring the Cursor

Use the CURSOR statement to declare an explicit cursor You can define parameters

to allow substitution of values into the query when the cursor is opened You can alsoreference variables within the query, but you must declare them before the cursorstatement

Syntax

DECLARE

CURSOR cursor_name IS

select_statement;

where: cursor_name is a PL/SQL identifier

select_statement is a SELECT statement without an INTO

clause

Note: Do not include the INTO clause within the cursor declaration because it

appears later within the FETCH statement

1

Trang 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć10

Trang 11

Processing Queries by Using Explicit Cursors 24Ć11

Opening the Cursor

Open the cursor to execute the query and identify the active set after specifyingvalues for all input variables The cursor will now point to the first row in the activeset

Syntax

OPEN cursor_name;

where: cursor_name is the name of the previously-declared cursor

Note: If the query returns no rows when the cursor is opened, PL/SQL does not raise

an exception However, you can test the cursor’s status after a fetch

2

Trang 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć12

Trang 13

Processing Queries by Using Explicit Cursors 24Ć13

Fetching Data from the Cursor

Use the FETCH statement to retrieve the current row values into output variables.After the fetch, you can manipulate the variables by further statements

Syntax

FETCH cursor_name INTO variable1, variable2, ;

where: cursor_name is the name of the previously declared cursor

variable is an output variable to store the results

Guidelines

D Include the same number of variables within the INTO clause of the FETCHstatement as output columns in the SELECT statement, and be sure that the

datatypes are compatible

D Match each variable to correspond to the columns positionally

D Alternatively, define a record for the cursor and reference the record in the

FETCH INTO clause

D Test to see if the cursor contains rows If a fetch acquires no values, that is, thereare now rows left to process in the active set and no error is recorded

3

Trang 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć14

Trang 15

Processing Queries by Using Explicit Cursors 24Ć15

Closing the Cursor

Close the cursor after completing the processing of the SELECT statement This stepallows the cursor to be reopened, if required Therefore, you can establish an activeset several times

Syntax

CLOSE cursor_name;

where: cursor_name is the name of the previously declared cursor

Note: Do not attempt to fetch data from a cursor once it has been closed or the

INVALID_CURSOR exception will be raised

4

Trang 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć16

Trang 17

Processing Queries by Using Explicit Cursors 24Ć17

about a cursor When used, the attribute name is preceded by the cursor identifier

Cursor Attribute Description

%ISOPEN Boolean attribute that evaluates to TRUE if the cursor is

open

%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent

fetch does not return a row

%FOUND Boolean attribute that evaluates to TRUE until the most

recent fetch does not return a row; complement of

%NOTFOUND

%ROWCOUNT Numeric attribute that evaluates to the total number of rows

returned so far

Note: Do not reference cursor attributes directly within a SQL statement.

Controlling Multiple Fetches from Explicit Cursors

Typically, when you want to process several rows from an explicit cursor, you define

a loop to perform a fetch on each iteration Eventually, all rows in the active set will

be processed, and an unsuccessful fetch sets the %NOTFOUND attribute to TRUE.Use the explicit cursor attributes to test success of each fetch before any furtherreferences are made to the cursor If you omit an exit criteria, an infinite loop willresult

For more information, see

PL/SQL User’s Guide and Reference, Release 2.3 “Using Cursor Attributes” section.

Trang 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć18

Trang 19

Processing Queries by Using Explicit Cursors 24Ć19

open using the %ISOPEN cursor attribute, if necessary

Fetch rows in a loop Determine when to exit the loop by using cursor attributes

To retrieve an exact number of rows, fetch the rows in a numeric FOR loop, or fetchthe rows in a simple loop and determine when to exit the loop by using the

%ROWCOUNT cursor attribute

Note: If using %ROWCOUNT, add a test for no rows in the cursor by using the

%NOTFOUND attribute because the rowcount is not incremented if the fetchdoes not retrieve any rows

Trang 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć20

Trang 21

Processing Queries by Using Explicit Cursors 24Ć21

table You can also define a record based on the selected list of columns in an explicitcursor This is convenient for processing the rows of the active set since you cansimply fetch into the record Therefore, the values of the row are loaded directly intothe corresponding fields of the record

In the example, you can select the ROWID pseudo-column, and it will have a

corresponding field within the EMP_RECORD PL/SQL record

Trang 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć22

Trang 23

Processing Queries by Using Explicit Cursors 24Ć23

the query when it executes This means that you can open an explicit cursor severaltimes in a block, returning a different active set on each occasion

Parameter datatypes are the same as those for scalar variables, but you do not givethem sizes The parameter names are for references within the cursor’s query

parameter_name is the name of a parameter

datatype is a scalar datatype of the parameter

select_statement is a SELECT statement without the INTO

clause

When the cursor is opened, you pass values to each of the parameters positionally.You can pass values from PL/SQL or host variables as well as literals

Trang 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć24

Trang 25

Processing Queries by Using Explicit Cursors 24Ć25

cursor is opened, rows are fetched once for each iteration in the loop, and the cursor

is closed automatically when all rows have been processed The loop itself is

terminated automatically at the end of the iteration where the last row was fetched

where: record_name is the name of the implicitly-declared record

cursor_name is a PL/SQL identifier for the

previously-declared cursor

Guidelines

D Do not declare the record that controls the loop Its scope is only in the loop

D Test the cursor attributes during the loop, if required

D Supply the parameters for a cursor, if required, in parentheses following thecursor name in the FOR statement

D Do not use a cursor FOR loop when the cursor operations have to be handledmanually

Trang 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć26

Trang 27

Processing Queries by Using Explicit Cursors 24Ć27

clause within the cursor query, which locks the affected rows when the cursor isopened Since the Oracle7 Server releases locks at the end of the transaction, youshould not commit across fetches from an explicit cursor if FOR UPDATE is used

WHERE CURRENT OF Clause

Additionally, you can write your DELETE or UPDATE statement to contain the

WHERE CURRENT OF cursor_name clause to refer to the latest row processed by

the FETCH statement When you use this clause, the cursor you reference must existand must contain the FOR UPDATE clause in the cursor query, otherwise you willobtain an error This clause allows you to apply updates and deletes to the currentlyaddressed row without the need to explicitly reference the ROWID pseudo-column

Trang 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć28

Trang 29

Processing Queries by Using Explicit Cursors 24Ć29

Cursor Types

D Implicit cursors are used for all DML statements and single row queries

D Explicit cursors are used for queries of zero, one, or more rows

Explicit Cursor Commands

D Declare the cursor

D Open the cursor

D Fetch data from the cursor

D Close the cursor

Cursor Attributes

Evaluate the status of the cursor by using cursor attributes

Cursors with Parameters

Use parameters to open an explicit cursor several times in a block, returning a

different active set on each occasion

Cursor FOR Loops

Use cursor FOR loops as a shortcut to open the cursor, fetch rows once for each loopiteration, and automatically close the cursor after all rows are processed

Trang 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć30

Trang 31

Processing Queries by Using Explicit Cursors 24Ć31

table and populate another table with the results using a cursor FOR loop

Practice Contents

D Declaring and using a cursor to query rows of a table

D Using a cursor FOR loop

D Applying cursor attributes to test the cursor status

Trang 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć32

Trang 33

Processing Queries by Using Explicit Cursors 24Ć33

1. Create a procedure named TOP_DOGS1 that determines the top employees withrespect to salaries

a. Prepare for this exercise by creating a new table for storing employees andtheir salaries

PL/SQL> CREATE TABLE top_dogs

+> (name VARCHAR2(25),

+> salary NUMBER(11,2));

b. Add a parameter to accept the user input n for the top number of employees.

c. Write a cursor FOR loop to get the last names and salaries of the top n people,

with respect to salary, from the S_EMP table

d. Store the names and salaries in the TOP_DOGS table

e. Assume for the moment that no two employees have the same salary

f. Test the exercise under a variety of special cases, such as n = 0, n is greater

than the number of employees in the S_EMP table

g. Empty the TOP_DOGS table after each test

2. Create a stored procedure named ADD_STARS to reward all employees byappending an asterisk in the STARS column for every commission point

a. Prepare for this exercise by creating a new column in the S_EMP table forstoring asterisks (*)

PL/SQL> ALTER TABLE s_emp

+> ADD stars VARCHAR2(100);

b. Determine the commission percentage for the employee, rounded to thenearest whole number Also, consider the case where the employee has nocommission percent

c. Add an asterisk to a string of asterisks for every commission point For

example, if the employee has a commission percentage of 10, then the STARScolumn will contain ten asterisks

d. Update the STARS column for each employee with the string of asterisks

Trang 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 24Ć34

If you have time, complete the following exercise

3. Copy the TOP_DOGS1 procedure from exercise 1, and name it TOP_DOGS2.Modify the TOP_DOGS2 procedure to consider the case where several

employees in the exercise 1 have the same salary For each name listed, all nameshaving the same salary should also be listed

Execute the TOP_DOGS2 procedure Enter 6, 7, or 8 for n, then Ngao, Dumas, and Quick-To-See should all display If you enter 9, 10, or 11 for n, then

Nagayama, Magee, and Maduro should all display

Remember to empty the TOP_DOGS table after each test

Ngày đăng: 17/01/2014, 09:20

TỪ KHÓA LIÊN QUAN