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

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

41 387 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 41
Dung lượng 290,69 KB

Nội dung

TIMESTAMP_TO_SCN Function 13-138 PL/SQL User's Guide and Reference TIMESTAMP_TO_SCN Function Syntax return_value := TIMESTAMP_TO_SCN(timestamp); Purpose TIMESTAMP_TO_SCN takes an argument that represents a precise time, and returns the system change number (SCN) of the database at that moment in time. The returned value has the datatype NUMBER. Usage Notes This function is part of the flashback query feature. System change numbers provide a precise way to specify the database state at a moment in time, so that you can see the data as it was at that moment. Call this function to find out the system change number associated with the date and time to which you want to "flash back". Examples DECLARE right_now TIMESTAMP; yesterday TIMESTAMP; sometime TIMESTAMP; scn1 INTEGER; scn2 INTEGER; scn3 INTEGER; BEGIN Get the current SCN. right_now := SYSTIMESTAMP; scn1 := TIMESTAMP_TO_SCN(right_now); dbms_output.put_line('Current SCN is ' || scn1); Get the SCN from exactly 1 day ago. yesterday := right_now - 1; scn2 := TIMESTAMP_TO_SCN(yesterday); dbms_output.put_line('SCN from yesterday is ' || scn2); Find an arbitrary SCN somewhere between yesterday and today. (In a real program we would have stored the SCN at some significant moment.) scn3 := (scn1 + scn2) / 2; Find out what time that SCN was in effect. sometime := SCN_TO_TIMESTAMP(scn3); dbms_output.put_line('SCN ' || scn3 || ' was in effect at ' || TO_CHAR(sometime)); END; / Related Topics SCN_TO_TIMESTAMP Function %TYPE Attribute PL/SQL Language Elements 13-139 %TYPE Attribute The %TYPE attribute lets use the datatype of a field, record, nested table, database column, or variable in your own declarations, instead of hardcoding the type names. You can use the %TYPE attribute as a datatype specifier when declaring constants, variables, fields, and parameters. If the types that you reference change, your declarations are automatically updated. This technique saves you from making code changes when, for example, the length of a VARCHAR2 column is increased. For more information, see "Using the %TYPE Attribute" on page 2-9. Syntax Keyword and Parameter Description collection_name A nested table, index-by table, or varray previously declared within the current scope. cursor_variable_name A PL/SQL cursor variable previously declared within the current scope. Only the value of another cursor variable can be assigned to a cursor variable. db_table_name.column_name A table and column that must be accessible when the declaration is elaborated. object_name An instance of an object type, previously declared within the current scope. record_name A user-defined or %ROWTYPE record, previously declared within the current scope. record_name.field_name A field in a user-defined or %ROWTYPE record, previously declared within the current scope. variable_name A variable, previously declared in the same scope. collection_name cursor_variable_name object_name record_name . field_name db_table_name . column_name variable_name % TYPE type_attribute %TYPE Attribute 13-140 PL/SQL User's Guide and Reference Usage Notes The %TYPE attribute is particularly useful when declaring variables, fields, and parameters that refer to database columns. Your code can keep working even when the lengths or types of the columns change. The NOT NULL column constraint is not inherited by items declared using %TYPE. Examples DECLARE We know that BUFFER2 and BUFFER3 will be big enough to hold the answers. If we have to increase the size of BUFFER1, the other variables will change size as well. buffer1 VARCHAR2(13) := 'abCdefGhiJklm'; buffer2 buffer1%TYPE := UPPER(buffer1); buffer3 buffer1%TYPE := LOWER(buffer1); We know that this variable will be able to hold the contents of this table column. If the table is altered to make the column longer or shorter, this variable will change size as well. tname user_tables.table_name%TYPE; %TYPE is great for subprogram parameters too, no need to recompile the subprogram if the table column changes. PROCEDURE print_table_name(the_name user_tables.table_name%TYPE) IS BEGIN dbms_output.put_line('Table = ' || the_name); END; BEGIN SELECT table_name INTO tname FROM user_tables WHERE ROWNUM < 2; print_table_name(tname); END; / Constants and Variables, %ROWTYPE Attribute UPDATE Statement PL/SQL Language Elements 13-141 UPDATE Statement The UPDATE statement changes the values of specified columns in one or more rows in a table or view. For a full description of the UPDATE statement, see Oracle Database SQL Reference. Syntax Keyword and Parameter Description alias Another (usually short) name for the referenced table or view, typically used in the WHERE clause. column_name The column (or one of the columns) to be updated. It must be the name of a column in the referenced table or view. A column name cannot be repeated in the column_name list. Column names need not appear in the UPDATE statement in the same order that they appear in the table or view. returning_clause Returns values from updated rows, eliminating the need to SELECT the rows afterward. You can retrieve the column values into variables or host variables, or into collections or host arrays. You cannot use the RETURNING clause for remote or parallel updates. If the statement does not affect any rows, the values of the variables specified in the RETURNING clause are undefined. For the syntax of returning_clause, see "DELETE Statement" on page 13-41. SET column_name = sql_expression This clause assigns the value of sql_expression to the column identified by column_name. If sql_expression contains references to columns in the table being UPDATE ( subquery TABLE ( ) subquery2 alias table_reference ) SET column_name = sql_expression ( ) ( column_name , ) = ( ) , WHERE search_condition CURRENT OF cursor_name returning_clause ; subquery3 subquery4 update_statement SET column_name = sql_expression ( subque ) ( column_name , ) = ( sub ) , WHERE search_condition CURRENT OF cursor_name returning_clause ; UPDATE Statement 13-142 PL/SQL User's Guide and Reference updated, the references are resolved in the context of the current row. The old column values are used on the right side of the equal sign. SET column_name = (subquery3) Assigns the value retrieved from the database by subquery3 to the column identified by column_name. The subquery must return exactly one row and one column. SET (column_name, column_name, ) = (subquery4) Assigns the values retrieved from the database by subquery4 to the columns in the column_name list. The subquery must return exactly one row that includes all the columns listed. The column values returned by the subquery are assigned to the columns in the column list in order. The first value is assigned to the first column in the list, the second value is assigned to the second column in the list, and so on. The following example creates a table with correct employee IDs but garbled names. Then it runs an UPDATE statement with a correlated query, to retrieve the correct names from the EMPLOYEES table and fix the names in the new table. Create a table with all the right IDs, but messed-up names. CREATE TABLE e1 AS SELECT employee_id, UPPER(first_name) first_name, TRANSLATE(last_name,'aeiou','12345') last_name FROM employees; BEGIN Display the first 5 names to show they're messed up. FOR person IN (SELECT * FROM e1 WHERE ROWNUM < 6) LOOP dbms_output.put_line(person.first_name || ' ' || person.last_name); END LOOP; UPDATE e1 SET (first_name, last_name) = (SELECT first_name, last_name FROM employees WHERE employee_id = e1.employee_id); dbms_output.put_line('*** Updated ' || SQL%ROWCOUNT || ' rows. ***'); Display the first 5 names to show they've been fixed up. FOR person IN (SELECT * FROM e1 WHERE ROWNUM < 6) LOOP dbms_output.put_line(person.first_name || ' ' || person.last_name); END LOOP; END; / DROP TABLE e1; sql_expression Any valid SQL expression. For more information, see Oracle Database SQL Reference. 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. UPDATE Statement PL/SQL Language Elements 13-143 table_reference A table or view that must be accessible when you execute the UPDATE statement, and for which you must have UPDATE privileges. For the syntax of table_reference, see "DELETE Statement" on page 13-41. TABLE (subquery2) The operand of TABLE is a SELECT statement that returns a single column value, which must be a nested table or a varray. 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 specified cursor. 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 Chooses which rows to update in the database table. Only rows that meet the search condition are updated. If you omit this clause, all rows in the table are updated. Usage Notes You can use the UPDATE WHERE CURRENT OF statement after a fetch from an open cursor (including fetches done by a cursor FOR loop), provided the associated query is FOR UPDATE. This statement updates the row that was just fetched. The implicit cursor SQL and the cursor attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN let you access useful information about the execution of an UPDATE statement. Examples The following example demonstrates how to update table rows based on conditions, and how to store the updated values, columns, or entire rows in PL/SQL variables: Create some rows with values in all caps like (EMPLOYEES,TABLE) and (EMP_JOB_IX,INDEX). CREATE TABLE my_objects AS SELECT object_name, object_type FROM user_objects; DECLARE my_name my_objects.object_name%TYPE; my_type my_objects.object_type%TYPE; TYPE name_typ IS TABLE OF my_objects.object_name%TYPE INDEX BY PLS_INTEGER; TYPE type_typ IS TABLE OF my_objects.object_type%TYPE INDEX BY PLS_INTEGER; all_names name_typ; all_types type_typ; TYPE table_typ IS TABLE OF my_objects%ROWTYPE INDEX BY PLS_INTEGER; all_rows table_typ; BEGIN Show the first 10 rows as they originally were. FOR obj IN (SELECT * FROM my_objects WHERE ROWNUM < 11) LOOP dbms_output.put_line('Name = ' || obj.object_name || ', type = ' || obj.object_type); END LOOP; UPDATE Statement 13-144 PL/SQL User's Guide and Reference UPDATE my_objects SET object_name = LOWER(object_name) WHERE object_type = 'TABLE'; dbms_output.put_line('*** Updated ' || SQL%ROWCOUNT || ' rows. ***'); Show the first 10 rows after the update. Only some of the names (the table names) have been changed to lowercase. FOR obj IN (SELECT * FROM my_objects WHERE ROWNUM < 11) LOOP dbms_output.put_line('Name = ' || obj.object_name || ', type = ' || obj.object_type); END LOOP; Update a single row, and store the values of updated (or unchanged) columns in variables. UPDATE my_objects SET object_name = INITCAP(object_name) WHERE object_name = 'employees' RETURNING object_name, object_type INTO my_name, my_type; dbms_output.put_line('*** Updated ' || SQL%ROWCOUNT || ' rows. ***'); dbms_output.put_line('Affected this row: ' || my_name || ', ' || my_type); Update many rows, storing the values of updated (or unchanged) columns in collections of records. Can't use 'RETURNING *', have to list the columns individually. UPDATE my_objects SET object_name = INITCAP(object_name) WHERE object_type IN ('TRIGGER','VIEW','SEQUENCE') RETURNING object_name, object_type BULK COLLECT INTO all_rows; dbms_output.put_line('*** Updated ' || SQL%ROWCOUNT || ' rows. ***'); FOR i IN all_rows.FIRST all_rows.LAST LOOP dbms_output.put_line('Affected this row: ' || all_rows(i).object_name || ', ' || all_rows(i).object_type); END LOOP; Update many rows, storing the values of updated (or unchanged) columns in separate collections. (Generally less useful than using collections of records as above.) UPDATE my_objects SET object_name = INITCAP(object_name) WHERE object_type IN ('INDEX','PROCEDURE') RETURNING object_name, object_type BULK COLLECT INTO all_names, all_types; dbms_output.put_line('*** Updated ' || SQL%ROWCOUNT || ' rows. ***'); FOR i IN all_names.FIRST all_names.LAST LOOP dbms_output.put_line('Affected this row: ' || all_names(i) || ', ' || all_types(i)); END LOOP; END; / DROP TABLE my_objects; Related Topics DELETE Statement, FETCH Statement, INSERT Statement Sample PL/SQL Programs A-1 A Sample PL/SQL Programs This appendix tells you where to find collections of sample PL/SQL programs, for your own study and testing. Where to Find PL/SQL Sample Programs You can find some sample programs in the PL/SQL demo directory. For the location of the directory, see the Oracle installation guide for your system. These samples are typically older ones based on the SCOTT schema, with its EMP and DEPT tables. Most examples in this book have been made into complete programs that you can run under the HR sample schema, with its EMPLOYEES and DEPARTMENTS tables. The Oracle Technology Network web site has a PL/SQL section with many sample programs to download, at http://otn.oracle.com/tech/pl_sql/. These programs demonstrate many language features, particularly the most recent ones. You can use some of the programs to compare performance of PL/SQL across database releases. For examples of calling PL/SQL from other languages, see Oracle Database Java Developer's Guide and Pro*C/C++ Programmer's Guide. Exercises for the Reader Here are some PL/SQL programming constructs that are helpful to know. After learning from the sample programs in this book and on the web, check to see that you are familiar with writing each of these constructs. ■ An anonymous PL/SQL block. ■ A PL/SQL stored procedure. ■ A SQL CALL statement that invokes a stored procedure. An anonymous block that invokes the stored procedure. ■ A PL/SQL stored function. ■ A SQL query that calls the stored function. ■ A PL/SQL package. ■ An anonymous block or a stored procedure that calls a packaged procedure. A SQL query that calls a packaged function. ■ A SQL*Plus script, or a set of scripts called from a master script, that creates a set of procedures, functions, and packages. Exercises for the Reader A-2 PL/SQL User's Guide and Reference ■ A FORALL statement (instead of a regular loop) to issue multiple INSERT, UPDATE, or DELETE statements. Understanding CHAR and VARCHAR2 Semantics in PL/SQL B-1 B Understanding CHAR and VARCHAR2 Semantics in PL/SQL This appendix explains the semantic differences between the CHAR and VARCHAR2 base types. These subtle but important differences come into play when you assign, compare, insert, update, select, or fetch character values. This appendix contains these topics: ■ Assigning Character Values on page B-1 ■ Comparing Character Values on page B-2 ■ Inserting Character Values on page B-2 ■ Selecting Character Values on page B-3 Assigning Character Values When you assign a character value to a CHAR variable, if the value is shorter than the declared length of the variable, PL/SQL blank-pads the value to the declared length. Information about trailing blanks in the original value is lost. In the following example, the value assigned to last_name includes six trailing blanks, not just one: last_name CHAR(10) := 'CHEN '; note trailing blank If the character value is longer than the declared length of the CHAR variable, PL/SQL aborts the assignment and raises the predefined exception VALUE_ERROR. PL/SQL neither truncates the value nor tries to trim trailing blanks. For example, given the declaration acronym CHAR(4); the following assignment raises VALUE_ERROR: acronym := 'SPCA '; note trailing blank When you assign a character value to a VARCHAR2 variable, if the value is shorter than the declared length of the variable, PL/SQL neither blank-pads the value nor strips trailing blanks. Character values are assigned intact, so no information is lost. If the character value is longer than the declared length of the VARCHAR2 variable, PL/SQL aborts the assignment and raises VALUE_ERROR. PL/SQL neither truncates the value nor tries to trim trailing blanks. [...]... length, 10- 14 evaluation short-circuit, 2-19 exception handlers, 10- 13 OTHERS handler, 10- 2 using RAISE statement in, 10- 12 using SQLCODE function in, 10- 14 using SQLERRM function in, 10- 14 EXCEPTION_INIT pragma, 10- 7 syntax, 13-44 using with RAISE_APPLICATION_ERROR, exception-handling part of function, 8-4 of PL/SQL block, 1-4 of procedure, 8-3 exceptions, 10- 1 declaring, 10- 6 predefined, 10- 4 propagation,... -selector) n := v2 (10) .a; (6) indexed name followed by component -selector n := f1 (10) .a; (7) function call followed by component -selector n := f2 (10) (10) .a; (8) function call followed by indexing -followed by component selector n := scott.pkg1.f2 (10) (10) .a; (9) function call (which is a dot- D-2 PL/SQL User's Guide and Reference Understanding Capture -n := scott.pkg1.f1.n; (10) END f1;... VARCHAR2 variable, PL/SQL aborts the assignment and raises VALUE_ERROR Note: The same rules apply when fetching Understanding CHAR and VARCHAR2 Semantics in PL/SQL B-3 Selecting Character Values B-4 PL/SQL User's Guide and Reference C Obfuscating Source Code with the PL/SQL Wrap Utility This appendix shows you how to run the wrap utility wrap is a standalone program that obfuscates PL/SQL source code,... PL/SQL The name-resolution rules for SQL and PL/SQL are similar You can avoid the few minor differences if you follow the capture avoidance rules For compatibility, the SQL rules are more permissive than the PL/SQL rules That is, the SQL rules, which are mostly context sensitive, recognize as legal more situations and DML statements than the PL/SQL rules do D-6 PL/SQL User's Guide and Reference E PL/SQL. .. block, 1-4 of procedure, 8-3 exceptions, 10- 1 declaring, 10- 6 predefined, 10- 4 propagation, 10- 10 raised in declaration, 10- 13 raised in handler, 10- 14 raising with RAISE statement, 10- 9 reraising, 10- 12 scope rules, 10- 6 syntax, 13-45 user-defined, 10- 6 WHEN clause, 10- 13 executable part of function, 8-4 of PL/SQL block, 1-4 of procedure, 8-3 EXECUTE IMMEDIATE statement, 7-2 EXECUTE privilege, 8-17... parameters You can write a PL/SQL application in a completely object-oriented way You can write a PL/SQL application in a mostly procedural way, using objects and object types to work around limitations on PL/SQL variables and parameters How Do I Create a PL/SQL Procedure? There are several ways to create different kinds of PL/SQL procedures and functions: CREATE PROCEDURE and CREATE FUNCTION statements... PL/SQL requires another program, such as SQL*Plus, to read and display the data passed to DBMS_OUTPUT (SQL*Plus does not display DBMS_OUTPUT data unless you issue the command SET SERVEROUTPUT ON first.) Other PL/SQL APIs for doing I/O are HTP (for displaying output on a web page), DBMS_PIPE (for passing information back and forth between PL/SQL and operating-system commands), UTL_FILE (for reading and. .. create varrays, nested tables, and associative arrays of objects You can write PL/SQL procedures and functions that accept objects as parameters You can pass objects as parameters to these procedures and functions You can also return objects from functions You can write member procedures and functions for an object type in PL/SQL You can create overloaded PL/SQL procedures and functions by defining different... how PL/SQL resolves references to names in potentially ambiguous SQL and procedural statements This appendix contains these topics: ■ What Is Name Resolution? on page D-1 ■ Examples of Qualified Names and Dot Notation on page D-2 ■ Differences in Name Resolution Between SQL and PL/SQL on page D-3 ■ Understanding Capture on page D-3 ■ Avoiding Inner Capture in DML Statements on page D-4 ■ Qualifying References... before distributing it PL/SQL User's Guide and Reference Limitations of the PL/SQL Wrap Utility Limitations of the PL/SQL Wrap Utility ■ ■ ■ ■ ■ ■ Although wrapping a compilation unit helps to hide the algorithm and makes reverse-engineering hard, Oracle Corporation does not recommend it as a secure method for hiding passwords or table names Because the source code is parsed by the PL/SQL compiler, not . the PL/SQL Wrap Utility C-4 PL/SQL User's Guide and Reference How PL/SQL Resolves Identifier Names D-1 D How PL/SQL Resolves Identifier Names This appendix explains how PL/SQL resolves references. variable, PL/SQL aborts the assignment and raises VALUE_ERROR. PL/SQL neither truncates the value nor tries to trim trailing blanks. Comparing Character Values B-2 PL/SQL User's Guide and Reference Comparing. statements. Understanding CHAR and VARCHAR2 Semantics in PL/SQL B-1 B Understanding CHAR and VARCHAR2 Semantics in PL/SQL This appendix explains the semantic differences between the CHAR and VARCHAR2 base

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