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

PL/SQL User''''s Guide and Reference 10g Release phần 9 pps

46 281 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

Định dạng
Số trang 46
Dung lượng 200,26 KB

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

Nội dung

OPEN StatementOPEN Statement TheOPEN statement executes the query associated with a cursor.. Unless you want to accept default values, each formal parameter in the cursordeclaration must

Trang 1

The following example shows that you can nest object types:

CREATE TYPE Address AS OBJECT ( street_address VARCHAR2(35), city VARCHAR2(15), state CHAR(2), zip_code INTEGER );

CREATE TYPE Person AS OBJECT ( first_name VARCHAR2(15), last_name VARCHAR2(15), birthday DATE,

home_address Address, nested object type phone_number VARCHAR2(15),

ss_number INTEGER, );

Related Topics

Functions,Packages,Procedures

Trang 2

OPEN Statement

OPEN Statement

TheOPEN statement executes the query associated with a cursor It allocates databaseresources to process the query and identifies the result set the rows that match thequery conditions The cursor is positioned before the first row in the result set Formore information, see"Querying Data with PL/SQL" on page 6-9

Usage Notes

Generally, PL/SQL parses an explicit cursor only the first time it is opened and parses

a SQL statement (creating an implicit cursor) only the first time the statement isexecuted All the parsed SQL statements are cached A SQL statement is reparsed only

if it is aged out of the cache by a new SQL statement Although you must close acursor before you can reopen it, PL/SQL need not reparse the associatedSELECTstatement If you close, then immediately reopen the cursor, a reparse is definitely notneeded

Rows in the result set are not retrieved when theOPEN statement is executed TheFETCH statement retrieves the rows With aFOR UPDATE cursor, the rows are lockedwhen the cursor is opened

If formal parameters are declared, actual parameters must be passed to the cursor Theformal parameters of a cursor must beIN parameters; they cannot return values toactual parameters The values of actual parameters are used when the cursor isopened The datatypes of the formal and actual parameters must be compatible Thequery can also reference PL/SQL variables declared within its scope

Unless you want to accept default values, each formal parameter in the cursordeclaration must have a corresponding actual parameter in theOPEN statement.Formal parameters declared with a default value do not need a corresponding actualparameter They assume their default values when theOPEN statement is executed.You can associate the actual parameters in anOPEN statement with the formalparameters in a cursor declaration using positional or named notation

If a cursor is currently open, you cannot use its name in a cursorFOR loop

Trang 3

OPEN Statement

Examples

Given the cursor declaration:

CURSOR parts_cur IS SELECT part_num, part_price FROM parts;

the following statement opens the cursor:

OPEN parts_cur;

Given the cursor declaration:

CURSOR emp_cur(my_ename VARCHAR2, my_comm NUMBER DEFAULT 0)

IS SELECT * FROM emp WHERE

any of the following statements opens the cursor:

Trang 4

OPEN-FOR Statement

OPEN-FOR Statement

TheOPEN-FOR statement executes the query associated with a cursor variable Itallocates database resources to process the query and identifies the result set therows that meet the query conditions The cursor variable is positioned before the firstrow in the result set For more information, see"Using Cursor Variables (REF

select_statement

A query associated withcursor_variable, which returns a set of values The querycan reference bind variables and PL/SQL variables, parameters, and functions Thesyntax ofselect_statement is similar to the syntax for

select_into_statement defined in"SELECT INTO Statement" on page 13-123,except that the cursorselect_statement cannot have anINTO clause

/* anonymous PL/SQL block in host environment */

BEGIN OPEN :emp_cv FOR SELECT * FROM emp;

OPEN :dept_cv FOR SELECT * FROM dept;

OPEN :grade_cv FOR SELECT * FROM salgrade;

OPEN :pay_cv FOR SELECT * FROM payroll;

OPEN :ins_cv FOR SELECT * FROM insurance;

FOR select_statement ;

open_for_statement

Trang 5

OPEN-FOR Statement

Unlike cursors, cursor variables do not take parameters Instead, you can pass wholequeries (not just parameters) to a cursor variable

Although a PL/SQL stored procedure or function can open a cursor variable and pass

it back to a calling subprogram, the calling and called subprograms must be in thesame instance You cannot pass or return cursor variables to procedures and functionscalled through database links

When you declare a cursor variable as the formal parameter of a subprogram thatopens the cursor variable, you must specify theIN OUT mode That way, thesubprogram can pass an open cursor back to the caller

Examples

To centralize data retrieval, you can group type-compatible queries in a storedprocedure When called, the following packaged procedure opens the cursor variableemp_cv for the chosen query:

CREATE PACKAGE emp_data AS TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;

PROCEDURE open_emp_cv (emp_cv IN OUT EmpCurTyp, choice IN INT);

END emp_data;

CREATE PACKAGE BODY emp_data AS PROCEDURE open_emp_cv (emp_cv IN OUT EmpCurTyp, choice IN INT) IS BEGIN

IF choice = 1 THEN OPEN emp_cv FOR SELECT * FROM emp WHERE comm IS NOT NULL;

ELSIF choice = 2 THEN OPEN emp_cv FOR SELECT * FROM emp WHERE sal > 2500;

ELSIF choice = 3 THEN OPEN emp_cv FOR SELECT * FROM emp WHERE deptno = 20;

IF choice = 1 THEN OPEN generic_cv FOR SELECT * FROM emp;

ELSIF choice = 2 THEN OPEN generic_cv FOR SELECT * FROM dept;

ELSIF choice = 3 THEN OPEN generic_cv FOR SELECT * FROM salgrade;

Trang 6

OPEN-FOR-USING Statement

OPEN-FOR-USING Statement

TheOPEN-FOR-USING statement associates a cursor variable with a query, executesthe query, identifies the result set, positions the cursor before the first row in the resultset, then zeroes the rows-processed count kept by%ROWCOUNT For more information,see"Building a Dynamic Query with Dynamic SQL" on page 7-4

Because this statement can use bind variables to make the SQL processing moreefficient, use theOPEN-FOR-USING statement when building a query where youknow theWHERE clauses in advance Use theOPEN-FOR statement when you need theflexibility to process a dynamic query with an unknown number ofWHERE clauses

OPEN

cursor_variable_name : host_cursor_variable_name

Trang 7

OPEN-FOR-USING Statement

The dynamic string can contain any multi-rowSELECT statement (without theterminator) The string can also contain placeholders for bind arguments However,you cannot use bind arguments to pass the names of schema objects to a dynamic SQLstatement

Every placeholder in the dynamic string must be associated with a bind argument intheUSING clause Numeric, character, and string literals are allowed in theUSINGclause, but Boolean literals (TRUE,FALSE,NULL) are not To pass nulls to the dynamicstring, you must use a workaround See"Passing Nulls to Dynamic SQL"on page 7-10.Any bind arguments in the query are evaluated only when the cursor variable isopened To fetch from the cursor using different bind values, you must reopen thecursor variable with the bind arguments set to their new values

Dynamic SQL supports all the SQL datatypes For example, bind arguments can becollections,LOBs, instances of an object type, and refs As a rule, dynamic SQL doesnot support PL/SQL-specific types For instance, bind arguments cannot be Booleans

my_ename VARCHAR2(15);

my_sal NUMBER := 1000;

BEGIN OPEN emp_cv FOR open cursor variable 'SELECT ename, sal FROM emp WHERE sal > :s' USING my_sal;

Trang 8

Packages

A package is a schema object that groups logically related PL/SQL types, items, andsubprograms Use packages when writing a set of related subprograms that form anapplication programming interface (API) that you or others might reuse Packageshave two parts: a specification (spec for short) and a body For more information, see

Chapter 9, "Using PL/SQL Packages"

Trang 9

"Using Invoker's Rights Versus Definer's Rights (AUTHID Clause)" on page 8-15.

PRAGMA SERIALLY_REUSABLE ;

Trang 10

Defines the underlying implementation of an explicit cursor For the syntax of

cursor_body, see"Cursors" on page 13-38

Declares an object (instance of an object type) For the syntax of

object_declaration, see"Object Types" on page 13-86

"RESTRICT_REFERENCES Pragma" on page 13-113

The pragma asserts that a function does not read and/or write database tables and/orpackage variables For more information about the purity rules and pragma

RESTRICT_REFERENCES, see Oracle Database Application Developer's Guide

-Fundamentals.

PRAGMA SERIALLY_REUSABLE

Marks a package as serially reusable, if its state is needed only for the duration of one

call to the server (for example, an OCI call to the server or a server-to-server remote

procedure call) For more information, see Oracle Database Application Developer's Guide

- Fundamentals.

Trang 11

You cannot define packages in a PL/SQL block or subprogram.

Most packages have a spec and a body The spec is the interface to your applications; itdeclares the types, variables, constants, exceptions, cursors, and subprograms

available for use The body fully defines cursors and subprograms, and so implementsthe spec

Only subprograms and cursors have an underlying implementation If a spec declaresonly types, constants, variables, exceptions, and call specs, the package body isunnecessary The body can still be used to initialize items declared in the spec:

CREATE PACKAGE emp_actions AS

application You can debug, enhance, or replace a package body without changing thepackage spec, which saves you from recompiling subprograms that call the package

Trang 12

Cursors and subprograms declared in a package spec must be defined in the packagebody Other program items declared in the package spec cannot be redeclared in thepackage body

To match subprogram specs and bodies, PL/SQL does a token-by-token comparison oftheir headers Except for white space, the headers must match word for word

Otherwise, PL/SQL raises an exception

Variables declared in a package keep their values throughout a session, so you can setthe value of a package variable in one procedure, and retrieve the same value in adifferent procedure

Related Topics

Collections,Cursors,Exceptions,Functions,Procedures,Records

Trang 13

Procedures

A procedure is a subprogram that can take parameters and be called Generally, youuse a procedure to perform an action A procedure has two parts: the specification andthe body The specification (spec for short) begins with the keywordPROCEDURE andends with the procedure name or a parameter list Parameter declarations are optional.Procedures that take no parameters are written without parentheses The procedurebody begins with the keywordIS(orAS) and ends with the keywordENDfollowed by

an optional procedure name

The procedure body has three parts: an optional declarative part, an executable part,and an optional exception-handling part The declarative part contains declarations oftypes, cursors, constants, variables, exceptions, and subprograms These items arelocal and cease to exist when you exit the procedure The executable part containsstatements that assign values, control execution, and manipulate Oracle data Theexception-handling part contains handlers that deal with exceptions raised duringexecution For more information, see"Understanding PL/SQL Procedures" onpage 8-3

Trang 14

The optionalCREATE clause creates stored procedures, which are stored in the Oracledatabase and can be called from other applications You can execute theCREATEstatement interactively from SQL*Plus or from a program using native dynamic SQL

expression

A combination of variables, constants, literals, operators, and function calls Thesimplest expression consists of a single variable When the declaration is elaborated,the value ofexpression is assigned to the parameter The value and the parametermust have compatible datatypes

function_declaration procedure_declaration

BEGIN statement PRAGMA AUTONOMOUS_TRANSACTION ;

Trang 15

function_declaration

Declares a function For the syntax offunction_declaration, see"Functions" onpage 13-67

IN, OUT, IN OUT

Parameter modes that define the behavior of formal parameters AnIN parameterpasses values to the subprogram being called AnOUT parameter returns values to thecaller of the subprogram AnIN OUT parameter lets passes initial values to the

subprogram being called and returns updated values to the caller

parameter_name

A formal parameter, which is a variable declared in a procedure spec and referenced inthe procedure body

PRAGMA AUTONOMOUS_TRANSACTION

Marks a function as autonomous An autonomous transaction is an independent

transaction started by the main transaction Autonomous transactions let you suspendthe main transaction, do SQL operations, commit or roll back those operations, thenresume the main transaction For more information, see"Doing Independent Units ofWork with Autonomous Transactions" on page 6-35

Inside a procedure, anIN parameter acts like a constant; you cannot assign it a value

AnOUT parameter acts like a local variable; you can change its value and reference thevalue in any way AnIN OUTparameter acts like an initialized variable; you can assign

it a value, which can be assigned to another variable For summary information aboutthe parameter modes, seeTable 8–1 on page 8-8

Trang 16

UnlikeOUTandIN OUTparameters,INparameters can be initialized to default values.For more information, see"Using Default Values for Subprogram Parameters" onpage 8-9

Before exiting a procedure, explicitly assign values to allOUT formal parameters AnOUT actual parameter can have a value before the subprogram is called However,when you call the subprogram, the value is lost unless you specify the compiler hintNOCOPY or the subprogram exits with an unhandled exception

You can write the procedure spec and body as a unit Or, you can separate theprocedure spec from its body That way, you can hide implementation details byplacing the procedure in a package You can define procedures in a package bodywithout declaring their specs in the package spec However, such procedures can becalled only from inside the package

At least one statement must appear in the executable part of a procedure TheNULLstatement meets this requirement

Examples

The following procedure debits a bank account:

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS old_balance REAL;

new_balance REAL;

overdrawn EXCEPTION;

BEGIN SELECT bal INTO old_balance FROM accts WHERE acctno = acct_id;

new_balance := old_balance - amount;

IF new_balance < 0 THEN RAISE overdrawn;

ELSE UPDATE accts SET bal = new_balance WHERE acctno = acct_id;

END IF;

EXCEPTION WHEN overdrawn THEN .

Trang 17

Keyword and Parameter Description

exception_name

A predefined or user-defined exception For a list of the predefined exceptions, see

"Summary of Predefined PL/SQL Exceptions" on page 10-4

Usage Notes

PL/SQL blocks and subprograms shouldRAISE an exception only when an errormakes it impractical to continue processing You can code aRAISE statement for agiven exception anywhere within the scope of that exception

When an exception is raised, if PL/SQL cannot find a handler for it in the currentblock, the exception propagates to successive enclosing blocks, until a handler is found

or there are no more blocks to search If no handler is found, PL/SQL returns an

unhandled exception error to the host environment.

In an exception handler, you can omit the exception name in aRAISE statement,which raises the current exception again This technique allows you to take someinitial corrective action (perhaps just logging the problem), then pass control toanother handler that does more extensive correction When an exception is reraised,the first block searched is the enclosing block, not the current block

Example

The following example raises an exception when an inventoried part is out of stock, orwhen a divide-by-zero situation is about to occur:

DECLARE out_of_stock EXCEPTION;

quantity_on_hand NUMBER := 0;

denominator NUMBER := 0;

BEGIN

IF quantity_on_hand = 0 THEN RAISE out_of_stock;

END IF;

IF denominator = 0 THEN raise ZERO_DIVIDE;

Trang 18

RAISE Statement

EXCEPTION WHEN out_of_stock THEN dbms_output.put_line('No more parts in stock.');

WHEN ZERO_DIVIDE THEN dbms_output.put_line('Attempt to divide by zero.');

WHEN OTHERS THEN dbms_output.put_line('Some other kind of problem ');

END;

/

Related Topics

Exceptions

Trang 19

Records

Records are composite variables that can store data values of different types, similar to

astruct type in C, C++, or Java For more information, see"What Is a PL/SQLRecord?" on page 5-32

In PL/SQL records are useful for holding data from table rows, or certain columnsfrom table rows For ease of maintenance, you can declare variables as

table%ROWTYPE or cursor%ROWTYPE instead of creating new record types

Trang 20

You can defineRECORD types and declare user-defined records in the declarative part

of any block, subprogram, or package

A record can be initialized in its declaration:

DECLARE TYPE TimeTyp IS RECORD ( seconds SMALLINT := 0, minutes SMALLINT := 0, hours SMALLINT := 0 );

You can use the%TYPEattribute to specify the datatype of a field You can add theNOTNULL constraint to any field declaration to prevent the assigning of nulls to that field.Fields declared asNOT NULL must be initialized

DECLARE TYPE DeptRecTyp IS RECORD (

deptno NUMBER(2) NOT NULL := 99, dname departments.department_name%TYPE, loc departments.location_id%TYPE, region regions%ROWTYPE

);

dept_rec DeptRecTyp;

BEGIN dept_rec.dname := 'PURCHASING';

Instead of assigning values separately to each field in a record, you can assign values

to all fields at once:

■ You can assign one user-defined record to another if they have the same datatype.(Having fields that match exactly is not enough.) You can assign a%ROWTYPErecord to a user-defined record if their fields match in number and order, andcorresponding fields have compatible datatypes

■ You can use theSELECT orFETCH statement to fetch column values into a record.The columns in the select-list must appear in the same order as the fields in yourrecord

You can declare and reference nested records That is, a record can be the component

of another record:

DECLARE TYPE TimeTyp IS RECORD ( minutes SMALLINT, hours SMALLINT );

TYPE MeetingTyp IS RECORD ( day DATE,

time_of TimeTyp, nested record

Trang 21

place VARCHAR2(20), purpose VARCHAR2(50) );

meeting MeetingTyp;

seminar MeetingTyp;

BEGIN seminar.time_of := meeting.time_of;

dept_rec DeptRecTyp;

BEGIN SELECT department_id, department_name, location_id INTO dept_rec FROM departments WHERE department_id = 20;

Trang 22

RESTRICT_REFERENCES Pragma

RESTRICT_REFERENCES Pragma

To be callable from SQL statements, a stored function must obey certain "purity" rules,which control side-effects (See"Controlling Side Effects of PL/SQL Subprograms" onpage 8-22.) The fewer side-effects a function has, the better it can be optimized within

a query, particular when thePARALLEL_ENABLE orDETERMINISTIC hints are used.The same rules that apply to the function itself also apply to any functions or

procedures that it calls

If any SQL statement inside the function body violates a rule, you get an error at runtime (when the statement is parsed) To check for violations of the rules at compiletime, you can use the compiler directivePRAGMA RESTRICT_REFERENCES Thispragma asserts that a function does not read and/or write database tables and/orpackage variables Functions that do any of these read or write operations are difficult

to optimize, because any call might produce different results or encounter errors

For more information, see Oracle Database Application Developer's Guide - Fundamentals.

,

RNDS WNDS RNPS WNPS TRUST

,

) ;

pragma_restrict_refs

Trang 23

RESTRICT_REFERENCES Pragma

TRUST

Asserts that the subprogram can be trusted not to violate one or more rules This value

is needed for functions written in C or Java that are called from PL/SQL, sincePL/SQL cannot verify them at run time

When you specifyTRUST, the function body is not checked for violations of theconstraints listed in the pragma The function is trusted not to violate them Skippingthese checks can improve performance

If you specifyDEFAULT instead of a subprogram name, the pragma applies to allsubprograms in the package spec or object type spec (including the system-definedconstructor for object types) You can still declare the pragma for individualsubprograms, overriding the default pragma

ARESTRICT_REFERENCES pragma can apply to only one subprogram declaration Apragma that references the name of overloaded subprograms always applies to themost recent subprogram declaration

Typically, you only specify this pragma for functions If a function calls procedures,then you need to specify the pragma for those procedures as well

Examples

This example asserts that the functionBALANCE writes no database state (WNDS) andreads no package state (RNPS) That is, it does not issue any DDL or DML statements,and does not refer to any package variables, and neither do any procedures orfunctions that it calls It might issue queries or assign values to package variables

CREATE PACKAGE loans AS FUNCTION balance(account NUMBER) RETURN NUMBER;

PRAGMA RESTRICT_REFERENCES (balance, WNDS, RNPS);

END loans;

/ DROP PACKAGE loans;

Related Topics

AUTONOMOUS_TRANSACTION Pragma,EXCEPTION_INIT Pragma,

SERIALLY_REUSABLE Pragma

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

TỪ KHÓA LIÊN QUAN