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

PL/SQL User’s Guide and Reference phần 8 pptx

48 358 0

Đ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 đề Cursors in PL/SQL
Trường học Oracle Corporation
Chuyên ngành Database Management
Thể loại Guide
Định dạng
Số trang 48
Dung lượng 153,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

Also, you can use the%TYPE attribute to provide thedatatype of a previously declared record.A cursor body must have aSELECT statement and the sameRETURN clause as itscorresponding cursor

Trang 1

Cursors

To execute a multi-row query, Oracle opens an unnamed work area that storesprocessing information An explicit cursor lets you name the work area, access theinformation, and process the rows individually For more information, see

"Managing Cursors" on page 5-6

Trang 2

This identifies a cursor parameter; that is, a variable declared as the formalparameter of a cursor A cursor parameter can appear in a query wherever aconstant can appear The formal parameters of a cursor must beIN parameters Thequery can also reference other PL/SQL variables within its scope

db_table_name cursor_name cursor_variable_name

% ROWTYPE

record_name % TYPE record_type_name

rowtype

Trang 3

a previously declared cursor Also, you can use the%TYPE attribute to provide thedatatype of a previously declared record.

A cursor body must have aSELECT statement and the sameRETURN clause as itscorresponding cursor spec Also, the number, order, and datatypes of select items intheSELECT clause must match theRETURN clause

%ROWTYPE

This attribute provides a record type that represents a row in a database table or arow fetched from a previously declared cursor or cursor variable Fields in therecord and corresponding columns in the row have the same names and datatypes

select_statement

This is a query that returns a result set of rows Its syntax is like that ofselect_into_statement without theINTO clause See"SELECT INTO Statement" onpage 11-154 If the cursor declaration declares parameters, each parameter must beused in the query

%TYPE

This attribute provides the datatype of a previously declared user-defined record

Usage Notes

You must declare a cursor before referencing it in anOPEN,FETCH, orCLOSE

statement And, you must declare a variable before referencing it in a cursordeclaration The word SQL is reserved by PL/SQL for use as the default name forimplicit cursors and cannot be used in a cursor declaration

Trang 4

You cannot assign values to a cursor name or use it in an expression However,cursors and variables follow the same scoping rules For more information, see

"Scope and Visibility" on page 2-38

You retrieve data from a cursor by opening it, then fetching from it Because the

FETCH statement specifies the target variables, using anINTO clause in theSELECT

statement of acursor_declaration is redundant and invalid

The scope of cursor parameters is local to the cursor, meaning that they can bereferenced only within the query used in the cursor declaration The values ofcursor parameters are used by the associated query when the cursor is opened Thequery can also reference other PL/SQL variables within its scope

The datatype of a cursor parameter must be specified without constraints Forexample, the following parameter declarations are illegal:

CURSOR c1 (emp_id NUMBER NOT NULL, dept_no NUMBER(2)) illegal

Examples

Some examples of cursor declarations follow:

CURSOR c1 IS SELECT empno, ename, job, sal FROM emp WHERE sal > 2000;

CURSOR c2 RETURN dept%ROWTYPE IS SELECT * FROM dept WHERE deptno = 10;

CURSOR c3 (start_date DATE) IS SELECT empno, sal FROM emp WHERE hiredate > start_date;

Related Topics

CLOSE Statement, FETCH Statement, OPEN Statement, SELECT INTO Statement

Trang 5

alias table_reference

)

Trang 6

This clause lets you return values from the deleted rows, thereby eliminating theneed toSELECT the rows beforehand You can retrieve the column values intovariables and/or host variables, or into collections and/or host arrays However,you cannot use theRETURNING clause for remote or parallel deletes

subquery

This is aSELECT statement that provides a set of rows for processing Its syntax islike that ofselect_into_statement without theINTO clause See"SELECTINTO Statement" on page 11-154

table_reference

This specifies a table or view, which must be accessible when you execute the

DELETE statement, and for which you must haveDELETE privileges

TABLE (subquery2)

The operand ofTABLE is aSELECT statement that returns a single column value,which must be a nested table OperatorTABLE informs Oracle that the value is acollection, not a scalar value

Trang 7

DELETE Statement

WHERE CURRENT OF cursor_name

This clause refers to the latest row processed by theFETCH statement associatedwith the cursor identified bycursor_name The cursor must beFOR UPDATE andmust be open and positioned on a row If the cursor is not open, theCURRENT OF

clause causes an error

If the cursor is open, but no rows have been fetched or the last fetch returned norows, PL/SQL raises the predefined exceptionNO_DATA_FOUND

The implicit cursorSQL and the cursor attributes%NOTFOUND,%FOUND, and

%ROWCOUNT let you access useful information about the execution of aDELETE

statement

Examples

The following statement deletes from thebonus table all employees whose saleswere below quota:

DELETE FROM bonus WHERE sales_amt < quota;

The following statement returns two column values from a deleted row into localvariables:

DECLARE my_empno emp.empno%TYPE;

my_ename emp.ename%TYPE;

my_job emp.job%TYPE;

BEGIN

DELETE FROM emp WHERE empno = my_empno RETURNING ename, job INTO my_ename, my_job;

END;

Trang 8

DELETE Statement

You can combine theBULK COLLECT clause with aFORALL statement, in whichcase, the SQL engine bulk-binds column values incrementally In the followingexample, if collectiondepts has 3 elements, each of which causes 5 rows to bedeleted, then collectionenums has 15 elements when the statement completes:

FORALL j IN depts.FIRST depts.LAST DELETE FROM emp WHERE deptno = depts(j) RETURNING empno BULK COLLECT INTO enums;

The column values returned by each execution are added to the values returnedpreviously

Related Topics

FETCH Statement, SELECT Statement

Trang 9

EXCEPTION_INIT Pragma

EXCEPTION_INIT Pragma

The pragmaEXCEPTION_INIT associates an exception name with an Oracle errornumber That allows you to refer to any internal exception by name and to write aspecific handler for it instead of using theOTHERS handler For more information,see"Using EXCEPTION_INIT" on page 6-8

Syntax

Keyword and Parameter Description

error_number

This is any valid Oracle error number These are the same error numbers returned

by the functionSQLCODE

Usage Notes

You can useEXCEPTION_INIT in the declarative part of any PL/SQL block,subprogram, or package The pragma must appear in the same declarative part asits associated exception, somewhere after the exception declaration

Be sure to assign only one exception name to an error number

PRAGMA EXCEPTION_INIT ( exception_name , error_number ) ;

exception_init_pragma

Trang 10

PRAGMA EXCEPTION_INIT(deadlock_detected, -60);

BEGIN

EXCEPTION WHEN deadlock_detected THEN handle the error

END;

Related Topics

AUTONOMOUS_TRANSACTION Pragma, Exceptions, RESTRICT_REFERENCESPragma, SERIALLY_RESUABLE Pragma, SQLCODE

Trang 11

Exceptions

An exception is a runtime error or warning condition, which can be predefined oruser-defined Predefined exceptions are raised implicitly (automatically) by theruntime system User-defined exceptions must be raised explicitly byRAISE

statements To handle raised exceptions, you write separate routines calledexception handlers For more information, seeChapter 6, "Error Handling"

Trang 12

"Predefined Exceptions" on page 6-4 PL/SQL declares predefined exceptionsglobally in packageSTANDARD, so you need not declare them yourself.

Redeclaring predefined exceptions is error prone because your local declarationoverrides the global declaration In such cases, you must use dot notation to specifythe predefined exception, as follows:

EXCEPTION WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN

The exception-handling part of a PL/SQL block is optional Exception handlersmust come at the end of the block They are introduced by the keyword

EXCEPTION The exception-handling part of the block is terminated by the samekeywordEND that terminates the entire block An exception handler can referenceonly those variables that the current block can reference

An exception should be raised only when an error occurs that makes it undesirable

or impossible to continue processing If there is no exception handler in the currentblock for a raised exception, the exception propagates according to the followingrules:

■ If there is an enclosing block for the current block, the exception is passed on tothat block The enclosing block then becomes the current block If a handler forthe raised exception is not found, the process repeats

If there is no enclosing block for the current block, an unhandled exception error is

passed back to the host environment

Only one exception at a time can be active in the exception-handling part of a block.Therefore, if an exception is raised inside a handler, the block that encloses thecurrent block is the first block searched to find a handler for the newly raisedexception From there on, the exception propagates normally

Trang 13

Example

The following PL/SQL block has two exception handlers:

DECLARE bad_emp_id EXCEPTION;

bad_acct_no EXCEPTION;

.

BEGIN

EXCEPTION WHEN bad_emp_id OR bad_acct_no THEN user-defined ROLLBACK;

WHEN ZERO_DIVIDE THEN predefined INSERT INTO inventory VALUES (part_number, quantity); COMMIT;

END;

Related Topics

Blocks, EXCEPTION_INIT Pragma, RAISE Statement

Trang 14

EXECUTE IMMEDIATE Statement

EXECUTE IMMEDIATE Statement

TheEXECUTE IMMEDIATE statement prepares (parses) and immediately executes adynamic SQL statement or anonymous PL/SQL block For more information, seeChapter 10, "Native Dynamic SQL"

EXECUTE IMMEDIATE dynamic_string

execute_immediate_statement

INTO

define_variable ,

record_name

RETURNING RETURN

IN OUT

bind_argument ,

Trang 15

EXECUTE IMMEDIATE Statement

USING

This clause specifies a list of input and/or output bind arguments If you do notspecify a parameter mode, it defaults toIN

Usage Notes

Except for multi-row queries, the dynamic string can contain any SQL statement

(without the terminator) or any PL/SQL block (with the terminator) The string can

also contain placeholders for bind arguments However, you cannot use bindarguments to pass the names of schema objects to a dynamic SQL statement For theright way, see"Passing the Names of Schema Objects" on page 10-11

You can place all bind arguments in theUSING clause The default parameter mode

isIN For DML statements that have aRETURNING clause, you can placeOUT

arguments in theRETURNING INTO clause without specifying the parameter mode,which, by definition, isOUT If you use both theUSING clause and theRETURNINGINTO clause, theUSING clause can contain onlyIN arguments

Trang 16

EXECUTE IMMEDIATE Statement

At run time, bind arguments replace corresponding placeholders in the dynamicstring So, every placeholder must be associated with a bind argument in theUSING

clause and/orRETURNING INTO clause You can use numeric, character, and stringliterals as bind arguments, but you cannot use Boolean literals (TRUE,FALSE, and

NULL) To pass nulls to the dynamic string, you must use a workaround See

"Passing Nulls" on page 10-13

Numeric, character, and string literals are allowed in theUSING clause, but Booleanliterals (TRUE,FALSE,NULL) are not To pass nulls to the dynamic string, you mustuse a workaround (see"Passing Nulls" on page 10-13)

Dynamic SQL supports all the SQL datatypes So, for example, define variables andbind arguments can be collections,LOBs, instances of an object type, and refs As arule, dynamic SQL does not support PL/SQL-specific types So, for example, definevariables and bind arguments cannot be Booleans or index-by tables The onlyexception is that a PL/SQL record can appear in theINTO clause

You can execute a dynamic SQL statement repeatedly using new values for the bindarguments However, you incur some overhead becauseEXECUTE IMMEDIATE

re-prepares the dynamic string before every execution

Examples

The following PL/SQL block contains several examples of dynamic SQL:

DECLARE sql_stmt VARCHAR2(200);

plsql_block VARCHAR2(500);

emp_id NUMBER(4) := 7566;

salary NUMBER(7,2);

dept_id NUMBER(2) := 50;

dept_name VARCHAR2(14) := ’PERSONNEL’;

location VARCHAR2(13) := ’DALLAS’;

emp_rec emp%ROWTYPE;

BEGIN EXECUTE IMMEDIATE ’CREATE TABLE bonus (id NUMBER, amt NUMBER)’;

sql_stmt := ’INSERT INTO dept VALUES (:1, :2, :3)’;

EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;

sql_stmt := ’SELECT * FROM emp WHERE empno = :id’;

EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;

plsql_block := ’BEGIN emp_pkg.raise_salary(:id, :amt); END;’; EXECUTE IMMEDIATE plsql_block USING 7788, 500;

Trang 17

EXECUTE IMMEDIATE Statement

sql_stmt := ’UPDATE emp SET sal = 2000 WHERE empno = :1 RETURNING sal INTO :2’;

EXECUTE IMMEDIATE sql_stmt USING emp_id RETURNING INTO salary;

EXECUTE IMMEDIATE ’DELETE FROM dept WHERE deptno = :num’ USING dept_id;

EXECUTE IMMEDIATE ’ALTER SESSION SET SQL_TRACE TRUE’;

END;

Related Topics

OPEN-FOR-USING Statement

Trang 18

EXIT Statement

EXIT Statement

You use theEXIT statement to exit a loop TheEXIT statement has two forms: theunconditionalEXIT and the conditionalEXIT WHEN With either form, you canname the loop to be exited For more information, see"Iterative Control: LOOP andEXIT Statements" on page 3-6

label_name) is exited immediately For the syntax ofboolean_expression, see

WHILE TRUE LOOP END LOOP;

In such cases, you must use anEXIT statement to exit the loop

EXIT

label_name WHEN boolean_expression

;

exit_statement

Trang 19

EXIT Statement

If you use anEXIT statement to exit a cursorFOR loop prematurely, the cursor isclosed automatically The cursor is also closed automatically if an exception is raisedinside the loop

Examples

TheEXIT statement in the following example is illegal because you cannot exitfrom a block directly; you can exit only from a loop:

DECLARE amount NUMBER;

maximum NUMBER;

BEGIN

BEGIN .

IF amount >= maximum THEN EXIT; illegal; use RETURN instead END IF;

END;

The following loop normally executes ten times, but it will exit prematurely if thereare less than ten rows to fetch:

FOR i IN 1 10 LOOP FETCH c1 INTO emp_rec;

EXIT WHEN c1%NOTFOUND;

total_comm := total_comm + emp_rec.comm;

END LOOP;

The following example illustrates the use of loop labels:

<<outer>>

FOR i IN 1 10 LOOP

<<inner>>

FOR j IN 1 100 LOOP .

EXIT outer WHEN exits both loops END LOOP inner;

END LOOP outer;

Related Topics

Expressions, LOOP Statements

Trang 20

(

boolean_expression character_expression date_expression numeric_expression

)

expression

AND OR

NOT

boolean_constant_name boolean_function_call boolean_literal boolean_variable_name other_boolean_form

NOT

boolean_constant_name boolean_function_call boolean_literal boolean_variable_name other_boolean_form

boolean_expression

Trang 21

character_constant_name character_function_call character_literal character_variable_name

%

FOUND ISOPEN NOTFOUND

IN ( expression

,

)

other_boolean_form

Trang 22

( index )

** exponent

numeric_subexpression

Trang 23

Keyword and Parameter Description

BETWEEN

This comparison operator tests whether a value lies in a specified range It means

"greater than or equal to low value and less than or equal to high value."

boolean_constant_name

This identifies a constant of typeBOOLEAN, which must be initialized to the value

TRUE,FALSE, orNULL Arithmetic operations on Boolean constants are illegal

boolean_expression

This is an expression that yields the Boolean valueTRUE,FALSE, orNULL

date_constant_name date_function_call date_literal date_variable_name

: host_variable_name

: indicator_name

date_expression

+ _ numeric_expression

numeric_subexpression

+ –

* / numeric_subexpression

numeric_expression

Trang 24

This identifies a variable of typeBOOLEAN Only the valuesTRUE,FALSE, andNULL

can be assigned to aBOOLEAN variable You cannot select or fetch column valuesinto aBOOLEAN variable Also, arithmetic operations onBOOLEAN variables areillegal

%BULK_ROWCOUNT

Designed for use with theFORALL statement, this is a composite attribute of theimplicit cursorSQL For more information, see"SQL Cursor" on page 11-163

character_constant_name

This identifies a previously declared constant that stores a character value It must

be initialized to a character value or a value implicitly convertible to a charactervalue

Ngày đăng: 07/08/2014, 11:22

TỪ KHÓA LIÊN QUAN