Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
37
Добавлен:
16.04.2013
Размер:
5.97 Mб
Скачать

6

Performing SQL Operations from PL/SQL

Knowledge is of two kinds. We know a subject ourselves, or we know where we can find information upon it. —Samuel Johnson

This chapter shows how PL/SQL supports the SQL commands, functions, and operators that let you manipulate Oracle data.

This chapter contains these topics:

Overview of SQL Support in PL/SQL on page 6-1

Performing DML Operations from PL/SQL (INSERT, UPDATE, and DELETE) on page 6-5

Issuing Queries from PL/SQL on page 6-7

Querying Data with PL/SQL on page 6-9

Querying Data with PL/SQL: Explicit Cursor FOR Loops on page 6-9

Using Cursor Variables (REF CURSORs) on page 6-19

Using Cursor Expressions on page 6-27

Overview of Transaction Processing in PL/SQL on page 6-29

Doing Independent Units of Work with Autonomous Transactions on page 6-35

Overview of SQL Support in PL/SQL

By extending SQL, PL/SQL offers a unique combination of power and ease of use. You can manipulate Oracle data flexibly and safely because PL/SQL fully supports all SQL data manipulation statements (except EXPLAIN PLAN), transaction control statements, functions, pseudocolumns, and operators. PL/SQL also supports dynamic SQL, which enables you to execute SQL data definition, data control, and session control statements dynamically. In addition, PL/SQL conforms to the current ANSI/ISO SQL standard.

Data Manipulation

To manipulate Oracle data, you use the INSERT, UPDATE, DELETE, SELECT, and LOCK TABLE commands. INSERT adds new rows of data to database tables; UPDATE modifies rows; DELETE removes unwanted rows; SELECT retrieves rows that meet your search criteria; and LOCK TABLE temporarily limits access to a table.

Performing SQL Operations from PL/SQL 6-1

Overview of SQL Support in PL/SQL

Transaction Control

Oracle is transaction oriented; that is, Oracle uses transactions to ensure data integrity. A transaction is a series of SQL data manipulation statements that does a logical unit of work. For example, two UPDATE statements might credit one bank account and debit another. It is important not to allow one operation to succeed while the other fails.

At the end of a transaction that makes database changes, Oracle makes all the changes permanent or undoes them all. If your program fails in the middle of a transaction, Oracle detects the error and rolls back the transaction, restoring the database to its former state.

You use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION commands to control transactions. COMMIT makes permanent any database changes made during the current transaction. ROLLBACK ends the current transaction and undoes any changes made since the transaction began. SAVEPOINT marks the current point in the processing of a transaction. Used with ROLLBACK, SAVEPOINT undoes part of a transaction. SET TRANSACTION sets transaction properties such as read-write access and isolation level.

SQL Functions

For example, the following example shows some queries that call SQL functions:

DECLARE

job_count NUMBER; emp_count NUMBER;

BEGIN

SELECT COUNT(DISTINCT job_id) INTO job_count FROM employees; SELECT COUNT(*) INTO emp_count FROM employees;

END;

/

SQL Pseudocolumns

PL/SQL recognizes the SQL pseudocolumns: CURRVAL, LEVEL, NEXTVAL, ROWID, and ROWNUM. In PL/SQL, pseudocolumns are only allowed in SQL queries, not in INSERT / UPDATE / DELETE statements, or in other PL/SQL statements such as assignments or conditional tests.

CURRVAL and NEXTVAL

A sequence is a schema object that generates sequential numbers. When you create a sequence, you can specify its initial value and an increment. CURRVAL returns the current value in a specified sequence.

Before you can reference CURRVAL in a session, you must use NEXTVAL to generate a number. A reference to NEXTVAL stores the current sequence number in CURRVAL. NEXTVAL increments the sequence and returns the next value. To get the current or next value in a sequence, use dot notation:

sequence_name.CURRVAL sequence_name.NEXTVAL

After creating a sequence, you can use it to generate unique sequence numbers for transaction processing. You can use CURRVAL and NEXTVAL only in a SELECT list, the VALUES clause, and the SET clause. The following example shows how to generate a new sequence number and refer to that same number in more than one statement:

6-2 PL/SQL User's Guide and Reference

Overview of SQL Support in PL/SQL

CREATE TABLE employees_temp AS SELECT employee_id, first_name FROM employees; CREATE TABLE employees_temp2 AS SELECT employee_id, first_name FROM employees;

DECLARE

next_value NUMBER; BEGIN

--The NEXTVAL value is the same no matter what table you select from. SELECT employees_seq.NEXTVAL INTO next_value FROM dual;

--You usually use NEXTVAL to create unique numbers when inserting data. INSERT INTO employees_temp VALUES (employees_seq.NEXTVAL, 'value 1');

--If you need to store the same value somewhere else, you use CURRVAL. INSERT INTO employees_temp2 VALUES (employees_seq.CURRVAL, 'value 1');

--Because NEXTVAL values might be referenced by different users and

--applications, and some NEXTVAL values might not be stored in the

--database, there might be gaps in the sequence.

END;

/

DROP TABLE employees_temp;

DROP TABLE employees_temp2;

Each time you reference the NEXTVAL value of a sequence, the sequence is incremented immediately and permanently, whether you commit or roll back the transaction.

LEVEL

You use LEVEL with the SELECT CONNECT BY statement to organize rows from a database table into a tree structure. You might use sequence numbers to give each row a unique identifier, and refer to those identifiers from other rows to set up parent-child relationships.

LEVEL returns the level number of a node in a tree structure. The root is level 1, children of the root are level 2, grandchildren are level 3, and so on.

In the START WITH clause, you specify a condition that identifies the root of the tree. You specify the direction in which the query traverses the tree (down from the root or up from the branches) with the PRIOR operator.

ROWID

ROWID returns the rowid (binary address) of a row in a database table. You can use variables of type UROWID to store rowids in a readable format.

When you select or fetch a physical rowid into a UROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value to a character string. You can compare the UROWID variable to the ROWID pseudocolumn in the WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched from a cursor. For an example, see "Fetching Across Commits" on page 6-34.

ROWNUM

ROWNUM returns a number indicating the order in which a row was selected from a table. The first row selected has a ROWNUM of 1, the second row has a ROWNUM of 2, and so on. If a SELECT statement includes an ORDER BY clause, ROWNUMs are assigned to the retrieved rows before the sort is done; use a subselect (shown in the following example) to get the first n sorted rows.

You can use ROWNUM in an UPDATE statement to assign unique values to each row in a table, or in the WHERE clause of a SELECT statement to limit the number of rows retrieved:

Performing SQL Operations from PL/SQL 6-3

Overview of SQL Support in PL/SQL

CREATE TABLE employees_temp AS SELECT * FROM employees;

DECLARE

CURSOR c1 IS SELECT employee_id, salary FROM employees_temp WHERE salary > 2000 AND ROWNUM <= 10; -- 10 arbitrary rows

CURSOR c2 IS SELECT * FROM

(SELECT employee_id, salary FROM employees_temp WHERE salary > 2000 ORDER BY salary DESC)

WHERE ROWNUM < 5; -- first 5 rows, in sorted order

BEGIN

-- Each row gets assigned a different number UPDATE employees_temp SET employee_id = ROWNUM;

END;

/

DROP TABLE employees_temp;

The value of ROWNUM increases only when a row is retrieved, so the only meaningful uses of ROWNUM in a WHERE clause are

... WHERE ROWNUM < constant;

... WHERE ROWNUM <= constant;

SQL Operators

PL/SQL lets you use all the SQL comparison, set, and row operators in SQL statements. This section briefly describes some of these operators. For more information, see Oracle Database SQL Reference.

Comparison Operators

Typically, you use comparison operators in the WHERE clause of a data manipulation statement to form predicates, which compare one expression to another and yield TRUE, FALSE, or NULL. You can use the comparison operators listed below to form predicates. You can combine predicates using the logical operators AND, OR, and NOT.

Operator

Description

 

 

ALL

Compares a value to each value in a list or returned

 

by a subquery and yields TRUE if all of the

 

individual comparisons yield TRUE.

ANY, SOME

Compares a value to each value in a list or returned

 

by a subquery and yields TRUE if any of the

 

individual comparisons yields TRUE.

BETWEEN

Tests whether a value lies in a specified range.

EXISTS

Returns TRUE if a subquery returns at least one row.

IN

Tests for set membership.

IS NULL

Tests for nulls.

LIKE

Tests whether a character string matches a specified

 

pattern, which can include wildcards.

 

 

Set Operators

Set operators combine the results of two queries into one result. INTERSECT returns all distinct rows selected by both queries. MINUS returns all distinct rows selected by the first query but not by the second. UNION returns all distinct rows selected by either query. UNION ALL returns all rows selected by either query, including all duplicates.

6-4 PL/SQL User's Guide and Reference

Соседние файлы в папке Oracle 10g