PL/SQL User''''s Guide and Reference 10g Release phần 8 ppsx

52 222 0
PL/SQL User''''s Guide and Reference 10g Release phần 8 ppsx

Đ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

Cursors 13-40 PL/SQL User's Guide and Reference %TYPE Provides the datatype of a previously declared user-defined record. Usage Notes You must declare a cursor before referencing it in an OPEN, FETCH, or CLOSE statement. You must declare a variable before referencing it in a cursor declaration. The word SQL is reserved by PL/SQL as the default name for implicit cursors, and cannot be used in a cursor declaration. 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 of PL/SQL Identifiers" on page 2-14. You retrieve data from a cursor by opening it, then fetching from it. Because the FETCH statement specifies the target variables, using an INTO clause in the SELECT statement of a cursor_declaration is redundant and invalid. The scope of cursor parameters is local to the cursor, meaning that they can be referenced only within the query used in the cursor declaration. The values of cursor parameters are used by the associated query when the cursor is opened. The query can also reference other PL/SQL variables within its scope. The datatype of a cursor parameter must be specified without constraints, that is, without precision and scale for numbers, and without length for strings. 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 DELETE Statement PL/SQL Language Elements 13-41 DELETE Statement The DELETE statement removes entire rows of data from a specified table or view. For a full description of the DELETE statement, see Oracle Database SQL Reference. Syntax Keyword and Parameter Description alias Another (usually short) name for the referenced table or view. Typically referred to later in the WHERE clause. BULK COLLECT Returns columns from the deleted rows into PL/SQL collections, as specified by the RETURNING INTO list. The corresponding columns must store scalar (not composite) values. For more information, see "Reducing Loop Overhead for DML Statements and Queries (FORALL, BULK COLLECT)" on page 11-7. returning_clause Returns values from the deleted rows, eliminating the need to SELECT the rows first. You can retrieve the column values into individual variables or into collections. You cannot use the RETURNING clause for remote or parallel deletes. If the statement does not affect any rows, the values of the variables specified in the RETURNING clause are undefined. WHERE search_condition CURRENT OF cursor_name returning_clause ; schema_name . db_table_name view_name @ dblink_name table_reference RETURNING single_row_expression , INTO variable_name : host_variable_name , multiple_row_expression , BULK COLLECT INTO collection_name : host_array_name , returning_clause delete_statement DELETE FROM ( subquery TABLE ( subquery2 ) alias table_reference ) DELETE Statement 13-42 PL/SQL User's Guide and Reference subquery A SELECT statement that provides a set of rows for processing. Its syntax is like the select_into_statement without the INTO clause. See "SELECT INTO Statement" on page 13-123. table_reference A table or view, which must be accessible when you execute the DELETE statement, and for which you must have DELETE privileges. TABLE (subquery2) The operand of TABLE is a SELECT statement that returns a single column value, which must be a nested table. Operator TABLE informs Oracle that the value is a collection, not a scalar value. WHERE CURRENT OF cursor_name Refers to the latest row processed by the FETCH statement associated with the cursor identified by cursor_name. The cursor must be FOR UPDATE and must be open and positioned on a row. If the cursor is not open, the CURRENT OF clause causes an error. If the cursor is open, but no rows have been fetched or the last fetch returned no rows, PL/SQL raises the predefined exception NO_DATA_FOUND. WHERE search_condition Conditionally chooses rows to be deleted from the referenced table or view. Only rows that meet the search condition are deleted. If you omit the WHERE clause, all rows in the table or view are deleted. Usage Notes You can use the DELETE WHERE CURRENT OF statement after a fetch from an open cursor (this includes implicit fetches executed in a cursor FOR loop), provided the associated query is FOR UPDATE. This statement deletes the current row; that is, the one just fetched. The implicit cursor SQL and the cursor attributes %NOTFOUND, %FOUND, and %ROWCOUNT let you access useful information about the execution of a DELETE statement. Examples The following statement deletes the rows that match a condition: DELETE FROM bonus WHERE sales_amt < quota; The following statement returns two column values from a deleted row into local variables: 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; DELETE Statement PL/SQL Language Elements 13-43 You can combine the BULK COLLECT clause with a FORALL statement, in which case, the SQL engine bulk-binds column values incrementally. In the following example, if collection depts has 3 elements, each of which causes 5 rows to be deleted, then collection enums 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 returned previously. Related Topics FETCH Statement, INSERT Statement, SELECT INTO Statement, UPDATE Statement EXCEPTION_INIT Pragma 13-44 PL/SQL User's Guide and Reference EXCEPTION_INIT Pragma The pragma EXCEPTION_INIT associates an exception name with an Oracle error number. You can intercept any ORA- error and write a specific handler for it instead of using the OTHERS handler. For more information, see "Associating a PL/SQL Exception with a Number: Pragma EXCEPTION_INIT" on page 10-7. Syntax Keyword and Parameter Description error_number Any valid Oracle error number. These are the same error numbers (always negative) returned by the function SQLCODE. exception_name A user-defined exception declared within the current scope. PRAGMA Signifies that the statement is a compiler directive. Usage Notes You can use EXCEPTION_INIT in the declarative part of any PL/SQL block, subprogram, or package. The pragma must appear in the same declarative part as its associated exception, somewhere after the exception declaration. Be sure to assign only one exception name to an error number. Example The following pragma associates the exception deadlock_detected with Oracle error 60: DECLARE deadlock_detected EXCEPTION; PRAGMA EXCEPTION_INIT(deadlock_detected, -60); BEGIN EXCEPTION WHEN deadlock_detected THEN handle the error END; Related Topics AUTONOMOUS_TRANSACTION Pragma, Exceptions, SQLCODE Function PRAGMA EXCEPTION_INIT ( exception_name , error_number ) ; exception_init_pragma Exceptions PL/SQL Language Elements 13-45 Exceptions An exception is a runtime error or warning condition, which can be predefined or user-defined. Predefined exceptions are raised implicitly (automatically) by the runtime system. User-defined exceptions must be raised explicitly by RAISE statements. To handle raised exceptions, you write separate routines called exception handlers. For more information, see Chapter 10. Syntax Keyword and Parameter Description exception_name A predefined exception such as ZERO_DIVIDE, or a user-defined exception previously declared within the current scope. OTHERS Stands for all the exceptions not explicitly named in the exception-handling part of the block. The use of OTHERS is optional and is allowed only as the last exception handler. You cannot include OTHERS in a list of exceptions following the keyword WHEN. statement An executable statement. For the syntax of statement, see "Blocks" on page 13-8. WHEN Introduces an exception handler. You can have multiple exceptions execute the same sequence of statements by following the keyword WHEN with a list of the exceptions, separating them by the keyword OR. If any exception in the list is raised, the associated statements are executed. Usage Notes An exception declaration can appear only in the declarative part of a block, subprogram, or package. The scope rules for exceptions and variables are the same. But, unlike variables, exceptions cannot be passed as parameters to subprograms. Some exceptions are predefined by PL/SQL. For a list of these exceptions, see "Summary of Predefined PL/SQL Exceptions" on page 10-4. PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. exception_name EXCEPTION ; exception_declaration WHEN exception_name OR exception_name OTHERS THEN statement exception_handler Exceptions 13-46 PL/SQL User's Guide and Reference Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration. In such cases, you must use dot notation to specify the 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 handlers must 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 same keyword END that terminates the entire block. An exception handler can reference only 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 current block for a raised exception, the exception propagates according to the following rules: ■ If there is an enclosing block for the current block, the exception is passed on to that block. The enclosing block then becomes the current block. If a handler for the 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 the current block is the first block searched to find a handler for the newly raised exception. From there on, the exception propagates normally. 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 EXECUTE IMMEDIATE Statement PL/SQL Language Elements 13-47 EXECUTE IMMEDIATE Statement The EXECUTE IMMEDIATE statement executes a dynamic SQL statement or anonymous PL/SQL block. You can use it to issue SQL statements that cannot be represented directly in PL/SQL, or to build up statements where you do not know all the table names, WHERE clauses, and so on in advance. For more information, see Chapter 7. Syntax Keyword and Parameter Description bind_argument An expression whose value is passed to the dynamic SQL statement, or a variable that stores a value returned by the dynamic SQL statement. define_variable_name A variable that stores a selected column value. dynamic_string A string literal, variable, or expression that represents a single SQL statement or a PL/SQL block. It must be of type CHAR or VARCHAR2, not NCHAR or NVARCHAR2. INTO Used only for single-row queries, this clause specifies the variables or record into which column values are retrieved. For each value retrieved by the query, there must be a corresponding, type-compatible variable or field in the INTO clause. EXECUTE IMMEDIATE dynamic_string execute_immediate_statement INTO define_variable , record_name RETURNING RETURN INTO bind_argument , ; USING IN OUT IN OUT bind_argument , EXECUTE IMMEDIATE Statement 13-48 PL/SQL User's Guide and Reference record_name A user-defined or %ROWTYPE record that stores a selected row. RETURNING INTO Used only for DML statements that have a RETURNING clause (without a BULK COLLECT clause), this clause specifies the bind variables into which column values are returned. For each value returned by the DML statement, there must be a corresponding, type-compatible variable in the RETURNING INTO clause. USING Specifies a list of input and/or output bind arguments. The parameter mode defaults to IN. Usage Notes Except for multi-row queries, the dynamic string can contain any SQL statement (without the final semicolon) or any PL/SQL block (with the final semicolon). The string can also contain placeholders for bind arguments. You cannot use bind arguments to pass the names of schema objects to a dynamic SQL statement. You can place all bind arguments in the USING clause. The default parameter mode is IN. For DML statements that have a RETURNING clause, you can place OUT arguments in the RETURNING INTO clause without specifying the parameter mode, which, by definition, is OUT. If you use both the USING clause and the RETURNING INTO clause, the USING clause can contain only IN arguments. At run time, bind arguments replace corresponding placeholders in the dynamic string. Every placeholder must be associated with a bind argument in the USING clause and/or RETURNING INTO clause. You can use numeric, character, and string literals 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 to Dynamic SQL" on page 7-10. Dynamic SQL supports all the SQL datatypes. For example, define variables and bind arguments can be collections, LOBs, instances of an object type, and refs. Dynamic SQL does not support PL/SQL-specific types. For example, define variables and bind arguments cannot be Booleans or index-by tables. The only exception is that a PL/SQL record can appear in the INTO clause. You can execute a dynamic SQL statement repeatedly using new values for the bind arguments. You still incur some overhead, because EXECUTE IMMEDIATE re-prepares the dynamic string before every execution. The string argument to the EXECUTE IMMEDIATE command cannot be one of the national character types, such as NCHAR or NVARCHAR2. 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; EXECUTE IMMEDIATE Statement PL/SQL Language Elements 13-49 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; 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 [...]... a PL/SQL host environment and passed to PL/SQL as a bind variable Host cursor variables must be prefixed with a colon host_variable_name A variable declared in a PL/SQL host environment and passed to PL/SQL as a bind variable The datatype of the host variable must be implicitly convertible to the appropriate PL/SQL datatype Also, host variables must be prefixed with a colon 13-56 PL/SQL User's Guide and. .. in a PL/SQL host environment and passed to PL/SQL as a bind variable) into which column values are bulk fetched For each query select_item, there must be a corresponding, type-compatible array in the list Host arrays must be prefixed with a colon 13-60 PL/SQL User's Guide and Reference FETCH Statement host_cursor_variable_name A cursor variable declared in a PL/SQL host environment and passed to PL/SQL. .. INDEX and CREATE MATERIALIZED VIEW in Oracle Database SQL Reference 13- 68 PL/SQL User's Guide and Reference Functions exception_handler Associates an exception with a sequence of statements, which is executed when that exception is raised For the syntax of exception_handler, see "Exceptions" on page 13-45 expression An arbitrarily complex combination of variables, constants, literals, operators, and. .. use the addition and subtraction operators to increment or decrement a date value, as the following examples show: hire_date := '10-MAY-95'; hire_date := hire_date + 1; hire_date := hire_date - 5; 13- 58 PL/SQL User's Guide and Reference makes hire_date '11-MAY-95' makes hire_date '06-MAY-95' Expressions When PL/SQL evaluates a boolean expression, NOT has the highest precedence, AND has the next-highest... Results into Collections with the BULK COLLECT Clause" on page 11-15 13-66 PL/SQL User's Guide and Reference Functions Functions A function is a subprogram that can take parameters and return a single value A function has two parts: the specification and the body The specification (spec for short) begins with the keyword FUNCTION and ends with the RETURN clause, which specifies the datatype of the return... elements are also PLS_INTEGER or BINARY_INTEGER If the index collection is empty, an exception is raised and the FORALL statement is not executed index_name An undeclared identifier that can be referenced only within the FORALL statement and only as a collection subscript 13-64 PL/SQL User's Guide and Reference FORALL Statement The implicit declaration of index_name overrides any other declaration outside... variable; you can change its value and reference the value in any way An IN OUT parameter acts like an initialized variable; you can assign it a value, which can be assigned to another variable For information about the parameter modes, see Table 8 1 on page 8- 8 Avoid using the OUT and IN OUT modes with functions The purpose of a function is to take zero or more parameters and return a single value Functions... literal, a PL/SQL variable, or a SQL query that returns a single value For more information, see Oracle Database SQL Reference PL/SQL also lets you use a record variable here subquery A SELECT statement that provides a set of rows for processing Its syntax is like that of select_into_statement without the INTO clause See "SELECT INTO Statement" on page 13-123 13-74 PL/SQL User's Guide and Reference. .. exist when you exit the function The executable part contains statements that assign values, control execution, and manipulate data The exception-handling part contains handlers that deal with exceptions raised during execution For more information, see "Understanding PL/SQL Functions" on page 8- 3 Syntax , function_spec ( FUNCTION parameter_declaration ) function_name RETURN datatype ; ffunction_declaration... acct_bal; END balance; Related Topics Collection Methods, Packages, Procedures 13-70 PL/SQL User's Guide and Reference GOTO Statement GOTO Statement The GOTO statement branches unconditionally to a statement label or block label The label must be unique within its scope and must precede an executable statement or a PL/SQL block The GOTO statement transfers control to the labelled statement or block . host_array_name , returning_clause delete_statement DELETE FROM ( subquery TABLE ( subquery2 ) alias table _reference ) DELETE Statement 13-42 PL/SQL User's Guide and Reference subquery A SELECT statement that provides a set of rows. Pragma 13-44 PL/SQL User's Guide and Reference EXCEPTION_INIT Pragma The pragma EXCEPTION_INIT associates an exception name with an Oracle error number. You can intercept any ORA- error and write. ; exception_declaration WHEN exception_name OR exception_name OTHERS THEN statement exception_handler Exceptions 13-46 PL/SQL User's Guide and Reference Redeclaring predefined exceptions is error prone because your

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

Từ khóa liên quan

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

Tài liệu liên quan