Introduction to Oracle PL/SQL Programming - SkillBuilders

26 downloads 3873 Views 474KB Size Report
Introduction to Oracle PL/SQLProgramming. Page i. Table of Contents. 0. How to Use This .... PL/SQL Program Structure. ...... Package Specification Example.
Introduction to Oracle PL/SQL Programming V2.1 - Lessons 11-End

Introduction to Oracle PL/SQLProgramming

Page i

Table of Contents 0. How to Use This Course.............................................................................. 0.1 Lesson Objectives .........................................................................................................0.2 Target Audience............................................................................................................0.3 Course Objectives .........................................................................................................0.4 Course Book Layout .....................................................................................................0.5 Conventions Used .........................................................................................................0.6 Getting Help..................................................................................................................0.7 1. Introduction to PL/SQL................................................................................ 1.1 Lesson Objectives .........................................................................................................1.2 What is PL/SQL? ..........................................................................................................1.3 Why Use PL/SQL? .......................................................................................................1.4 PL/SQL Program Structure...........................................................................................1.6 Anonymous Blocks.......................................................................................................1.7 Compile Errors..............................................................................................................1.9 Output to SQL*Plus....................................................................................................1.10 Procedures...................................................................................................................1.11 Procedure Compile Errors ..........................................................................................1.12 Functions.....................................................................................................................1.14 Packages......................................................................................................................1.15 Data Dictionary...........................................................................................................1.17 Triggers.......................................................................................................................1.18 Tools for Development ...............................................................................................1.20 Working in SQL*Plus.................................................................................................1.21 Introduction to PL/SQL Workshops ...........................................................................1.22 2. Language Fundamentals............................................................................. 2.1 Lesson Objectives ........................................................................................................2.2 Statements.....................................................................................................................2.3 PL/SQL Symbols ..........................................................................................................2.4 Common PL/SQL Datatypes ........................................................................................2.5 Declaring Variables… ..................................................................................................2.7 %TYPE .......................................................................................................................2.10 © 2006 SkillBuilders, Inc.

V2.1

Introduction to Oracle PL/SQLProgramming

Page ii

PL/SQL Records .........................................................................................................2.11 Records: %ROWTYPE...............................................................................................2.12 Programmer Defined Records ....................................................................................2.13 Language Fundamentals Workshop A........................................................................2.16 Variable Scope............................................................................................................2.17 Nested Blocks .............................................................................................................2.18 Functions.....................................................................................................................2.19 IF Statement................................................................................................................2.20 CASE ..........................................................................................................................2.21 Simple CASE..............................................................................................................2.22 Searched CASE...........................................................................................................2.23 Simple Loops ..............................................................................................................2.24 Nested Loops ..............................................................................................................2.25 Numeric FOR Loop ....................................................................................................2.26 PL/SQL Arrays ...........................................................................................................2.27 Simple Array Example................................................................................................2.28 Array Methods ............................................................................................................2.29 Language Fundamentals Workshop B........................................................................2.31 3. PL/SQL and SQL: Basics ............................................................................ 3.1 Lesson Objectives ........................................................................................................3.2 SELECT INTO Statement ............................................................................................3.3 Implicit Cursor Loops...................................................................................................3.5 Basics Workshop A (Cursor Loop) ..............................................................................3.6 DML in PL/SQL ...........................................................................................................3.7 Cursor Attributes...........................................................................................................3.8 Embedding DDL...........................................................................................................3.9 Basics Workshop B (NDS) .........................................................................................3.10 4. PL/SQL and SQL: Cursors .......................................................................... 4.1 Lesson Objectives .........................................................................................................4.2 What is a Cursor?..........................................................................................................4.3 Cursor Processing .........................................................................................................4.4 Cursor Attributes...........................................................................................................4.7 Cursors Workshop A ....................................................................................................4.8 Dynamic Cursors ..........................................................................................................4.9 Dynamic Cursor Example...........................................................................................4.10 Variable Scope & Cursors ..........................................................................................4.11 Problem Example........................................................................................................4.12 Cursor Parameters.......................................................................................................4.13 Cursor Record .............................................................................................................4.14 Cursor FOR LOOP .....................................................................................................4.15 FOR LOOP Example ..................................................................................................4.16 © 2006 SkillBuilders, Inc.

V2.1

Introduction to Oracle PL/SQLProgramming

Page iii

FOR LOOP Example .................................................................................................4.17 Cursors Optional Workshop B....................................................................................4.18 Referencing the Current Row .....................................................................................4.19 FOR UPDATE Example ............................................................................................4.20 FOR UPDATE Example.............................................................................................4.21 Cursors Optional Workshop C....................................................................................4.23 5. PL/SQL and SQL: Bulk Processing ...........................................................5.1 Lesson Objectives ........................................................................................................5.2 Bulk Processing ............................................................................................................5.3 Bulk Collect ..................................................................................................................5.4 Bulk Collect: SELECT INTO......................................................................................5.5 Bulk Collect: Multiple Arrays ......................................................................................5.6 Bulk Collect: Array of Records ....................................................................................5.7 Bulk Collect: FETCH with LIMIT ...............................................................................5.8 Bulk Processing Workshop A ......................................................................................5.9 Bulk DELETE.............................................................................................................5.11 Bulk INSERT..............................................................................................................5.13 Returning into Arrays .................................................................................................5.14 Summary.....................................................................................................................5.15 Bulk Processing Workshop B .....................................................................................5.16 6. Procedures ................................................................................................... 6.1 Lesson Objectives .........................................................................................................6.2 What is a Procedure? ....................................................................................................6.3 Abbreviated Syntax.......................................................................................................6.4 Simple Example............................................................................................................6.6 Review: Compile Errors ...............................................................................................6.7 Procedure Signatures ....................................................................................................6.8 Calling Procedures........................................................................................................6.9 Procedure Synonyms ..................................................................................................6.10 Referencing Parameters by Name...............................................................................6.11 Returning Sets: REF CURSOR ..................................................................................6.12 Dropping Procedures ..................................................................................................6.13 Dependencies ..............................................................................................................6.14 ALTER COMPILE .....................................................................................................6.15 Privileges ....................................................................................................................6.16 Execute Privilege ........................................................................................................6.17 The Data Dictionary....................................................................................................6.18 Procedures Workshop .................................................................................................6.19

© 2006 SkillBuilders, Inc.

V2.1

Introduction to Oracle PL/SQLProgramming

Page iv

7. Functions...................................................................................................... 7.1 Lesson Objectives .........................................................................................................7.2 What is a Function? ......................................................................................................7.3 Abbreviated Syntax.......................................................................................................7.4 Simple Example............................................................................................................7.5 Calling Functions..........................................................................................................7.6 The Data Dictionary......................................................................................................7.7 Functions Workshop A .................................................................................................7.8 Table Functions.............................................................................................................7.9 Building a Table Function ..........................................................................................7.10 Using a Table Function...............................................................................................7.12 Pipelined Functions.....................................................................................................7.14 Pipelined Example ......................................................................................................7.15 Test Data Generator ....................................................................................................7.16 Functions Workshop B ...............................................................................................7.19 8. Error Handling.............................................................................................. 8.1 Lesson Objectives .........................................................................................................8.2 Types of Errors .............................................................................................................8.3 Runtime Errors..............................................................................................................8.4 Exception Concepts ......................................................................................................8.5 Predefined Named Exceptions......................................................................................8.8 Syntax ...........................................................................................................................8.9 Handling Exceptions...................................................................................................8.10 Recovering from Errors ..............................................................................................8.11 Logging Exceptions… ................................................................................................8.12 RAISE_APPLICATION_ERROR .............................................................................8.14 RAE Example .............................................................................................................8.15 Error Handling Workshop .........................................................................................8.16 Raising Exceptions .....................................................................................................8.17 Raising User Exceptions.............................................................................................8.18 EXCEPTION_INIT ....................................................................................................8.20 Summary.....................................................................................................................8.22 9. Packages ......................................................................................................9.1 Lesson Objectives .........................................................................................................9.2 Concepts........................................................................................................................9.3 Package Benefits...........................................................................................................9.4 Package Benefits Diagram............................................................................................9.5 Package Contents..........................................................................................................9.6 Package Specification Syntax.......................................................................................9.7 Package Specification Example....................................................................................9.8

© 2006 SkillBuilders, Inc.

V2.1

Introduction to Oracle PL/SQLProgramming

Page v

Package Body Syntax ...................................................................................................9.9 Package Body Example ..............................................................................................9.10 Privileges ....................................................................................................................9.11 Calling Packaged Objects ...........................................................................................9.12 Initialization Code.......................................................................................................9.13 Session Variables........................................................................................................9.14 Package Body Variables .............................................................................................9.15 Packages Workshop A ................................................................................................9.16 Package Overloading ..................................................................................................9.17 Overloading Example .................................................................................................9.18 Packages Workshop B ................................................................................................9.19 Compiling Packages ...................................................................................................9.20 DROP Package ...........................................................................................................9.21 Packages Workshop C ................................................................................................9.22 Supplied Packages ......................................................................................................9.23 Summary.....................................................................................................................9.24 10. Triggers .................................................................................................... 10.1 Lesson Objectives .......................................................................................................10.2 Trigger Concepts.........................................................................................................10.3 Trigger Execution .......................................................................................................10.5 Create Trigger Syntax.................................................................................................10.6 Row Trigger................................................................................................................10.7 :OLD Reference Variable ..........................................................................................10.8 :NEW Reference Variable ..........................................................................................10.9 Trigger Attributes .....................................................................................................10.11 Audit Trigger ............................................................................................................10.13 Derived Value Trigger ..............................................................................................10.14 Restrictions ...............................................................................................................10.15 Security Privileges ....................................................................................................10.16 Triggers Workshop A ...............................................................................................10.17 Statement Level Trigger ..........................................................................................10.19 Triggers Workshop B................................................................................................10.20 Autonomous Transactions ........................................................................................10.21 Autonomous Trigger.................................................................................................10.22 Triggers Workshop C................................................................................................10.23 INSTEAD OF Triggers.............................................................................................10.24 ۞ Sybase / MS SQL Server vs. Oracle Triggers .....................................................10.26 Triggers Workshop D ...............................................................................................10.27 11. File I/O Using UTL_FILE .......................................................................... 11.1 Lesson Objectives .......................................................................................................11.2 UTL_FILE Concepts ..................................................................................................11.3 © 2006 SkillBuilders, Inc.

V2.1

Introduction to Oracle PL/SQLProgramming

Page vi

Setup ...........................................................................................................................11.4 Unix File Permissions.................................................................................................11.5 Opening Files..............................................................................................................11.7 Closing Files ...............................................................................................................11.9 Reading Files ............................................................................................................11.11 Reading Files Example .............................................................................................11.12 Writing Files .............................................................................................................11.15 Writing Files - PUT ..................................................................................................11.16 Writing Files - PUT_LINE .......................................................................................11.17 Writing Files - NEW_LINE......................................................................................11.18 Writing Files - PUTF ................................................................................................11.19 Writing Files Example ..............................................................................................11.20 UTL_FILE Workshop...............................................................................................11.21 12. Using DBMS_JOB .................................................................................... 12.1 Lesson Objectives .......................................................................................................12.2 What is DBMS_JOB?.................................................................................................12.3 Setup ...........................................................................................................................12.4 DBMS_JOB.SUBMIT................................................................................................12.5 SUBMIT Example ......................................................................................................12.6 Running a Job .............................................................................................................12.7 Cleaning Up Broken Jobs ...........................................................................................12.8 Removing a Job ..........................................................................................................12.9 Changing Job Parameters..........................................................................................12.10 Viewing Job Information ..........................................................................................12.11 Using DBMS_JOB Workshop..................................................................................12.12 13. Profile and Tune....................................................................................... 13.1 Lesson Objectives .......................................................................................................13.2 Introduction to Tuning PL/SQL..................................................................................13.3 DBMS_PROFILER ....................................................................................................13.4 Profiler Setup ..............................................................................................................13.5 Using Profiler..............................................................................................................13.6 Testing ........................................................................................................................13.7 Reporting ....................................................................................................................13.8 Profile & Tune PLSQL Workshop .............................................................................13.9 A. Dynamic SQL .............................................................................................. A.1 What is Dynamic SQL? ...............................................................................................A.2 NDS vs. DBMS_SQL ..................................................................................................A.3 NDS Statement Summary............................................................................................A.5 NDS Single-Row Query Syntax ..................................................................................A.6 © 2006 SkillBuilders, Inc.

V2.1

Introduction to Oracle PL/SQLProgramming

Page vii

NDS Single-Row INSERT Example ...........................................................................A.7 NDS Multi-Row Query Syntax....................................................................................A.8 NDS Multi-Row Query Example ................................................................................A.9 NDS PL/SQL Example..............................................................................................A.10 DBMS_SQL Procedures Summary ...........................................................................A.11 DBMS_SQL Example ...............................................................................................A.12 Privileges ...................................................................................................................A.13 Dynamic SQL Workshop...........................................................................................A.14 B. Table Descriptions ..................................................................................... B.1

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.1

Lesson 11 File I/O Using UTL_FILE

© 2006 SkillBuilders, Inc.

© 2006 SkillBuilders, Inc.

SKILLBUILDERS

V2.1

File I/O Using UTL_FILE

11.2

11.2

Lesson Objectives ¾ File Input/Output in PL/SQL ¾ Open and close operating system files ¾ Read and write to operating system files ¾ Handling exceptions raised during file processing

© 2006 SkillBuilders, Inc.

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.3

11.3

UTL_FILE Concepts ¾ Extension package ¾ Provides input and output to text files on the server ¾

Can be network drive accessible from server

¾ Supports common language I/O functions ¾ ¾

opening, closing reading, writing, appending

© 2006 SkillBuilders, Inc.

UTL_FILE is an extension package of the original Oracle PL/SQL language that allows input and output to text files on the server. Note that the text files referred to are on the server only and not on the client. UTL_FILE supports common I/O functions such as opening, closing, reading, writing and appending of files. This package is available with versions of PL/SQL 2.3 and higher. UTL_FILE is different from the DBMS_OUTPUT package which allows input and output to a screen, not a file. ۞ Sybase and MS SQL Server do not have direct equivalents to UTL_FILE. Use their bcp utility to export and import ASCII files.

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.4

11.4

Setup ¾ Create a directory to point to OS file system SQL> SQL> create create or or replace replace directory directory class class as as 'c:\temp'; 'c:\temp'; Directory Directory created. created. SQL> SQL> grant grant read, read, write write on on directory directory class class to to public; public; Grant Grant succeeded. succeeded.

© 2006 SkillBuilders, Inc.

The starting point for using UTL_FILE is to create an Oracle directory. The directory is an Oracle object that points to a server-based operating system directory. Like all Oracle objects, the directory is protected from other database users. You must GRANT READ and write privileges on it to users who need to use UTL_FILE to access the directory. Supplemental Notes CREATE ANY DIRECTORY privilege is required to create a directory. The database will require OS privileges to read/write to the OS directory named in the CREATE DIRECTORY commands (typically, this is accomplished by granting the OS privileges to the OS user “ORACLE”). Prior to 9i, access was made to the OS by setting the UTL_FILE_DIR parameter in the INIT.ORA file.

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.5

11.5

Unix File Permissions ¾ Using SQL*Plus on the server side $$ -rw-rw-rw-rw-rw-rw- 11 oracle oracle dba dba 00 timestamp timestamp filename1 filename1

¾ Using SQL*Plus on the client side $$ -rw-rw-rw-rw-rw-rw- 11 user user group group 00 timestamp timestamp filename2 filename2 ¾

Before executing a PL/SQL program on the client side, any files that don’t exist need to be created $$ touch touch filename filename $$ chmod chmod 777 777 filename filename

© 2006 SkillBuilders, Inc.

File Permissions Different file permission situations arise based on where a PL/SQL program is executed on a UNIX operating system. For Windows systems, the user only needs to have permission to access the directory in which the UTL_FILE package will be manipulating files. Server Side Execution When executing PL/SQL using SQL*Plus on the server side from either the command line or in batch mode all files will be created with the following owner, group and permissions. $ -rw-rw-rw-

1

oracle

dba

0

timestamp

filename1

Since the owner and group of the SQL*Plus executable file(which resides in your $ORACLE_HOME/bin sub directory) is owned by oracle and in the DBA group the file will get created with these settings Client Side Execution When executing PL/SQL using SQL*Plus on the client side all files will be created with the following owner, group and permissions $ -rw-rw-rw-

1

user

group

0

timestamp

filename2

continued . . .

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.6

File Initialization Before executing the PL/SQL programs from the client side any files that do not exist could be created in order to circumvent any permission problems. touch is a UNIX command that creates a zero length file if it does not exist or updates an already existing file with a current timestamp. $ touch filename $ chmod 777 filename After the file is created using touch, the permissions need to be set using the chmod command.

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.7

11.7

Opening Files ¾ FILE_TYPE ¾ ¾

A file is pointed to by a handle which is its own type A file handle, like any other variable, must be declared before a file can be opened v_filehandle_name v_filehandle_name UTL_FILE.FILE_TYPE; UTL_FILE.FILE_TYPE;

¾ FOPEN ¾

The UTL_FILE function used to open a file UTL_FILE.FOPEN(location, UTL_FILE.FOPEN(location, filename, filename, mode mode [, max_linesize]); [, max_linesize]); © 2006 SkillBuilders, Inc.

There are 2 subprograms within the UTL_FILE package that handle the opening of files, FILE_TYPE and FOPEN. FILE_TYPE is used to type a variable of the correct type to hold the handle returned by the FOPEN function. When FOPEN is called, it returns a file handle (pointer) to the file it opened. The variable that receives that file handle must be typed correctly using FILE_TYPE before the FOPEN function is called. FOPEN Parameters: ¾ location - the fully qualified directory path ¾ filename - the actual file name ¾ mode - mode for opening the file (r: read, w: write, a: append) ¾ max_linesize – allows lines larger than the default (1023 bytes) up to 32K to be accepted. The maximum number of files that can be opened using FOPEN at once is 50. Supplemental Notes Testing FOPEN with IS_OPEN A file can be tested to see if it is already open by using the IS_OPEN function. The IS_OPEN function takes one parameter as input, a file handle of type FILE_TYPE and returns one value as output, a boolean (true for open, false for closed). UTL_FILE.IS_OPEN (file_handle) ;

continued . . . .

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.8

Exceptions There are several possible exceptions (errors) that may occur when attempting to open a file: UTL_FILE.INVALID_PATH

Directory of filename is incorrect

UTL_FILE.INVALID_MODE

Incorrect open mode specified

UTL_FILE.INVALID_OPERATION

Operating system error (i.e. File permissions file does not exist)

UTL_FILE.INTERNAL_ERROR

Oracle internal error

or

So, your EXCEPTION block might contain: EXCEPTION WHEN UTL_FILE.INVALID_PATH THEN RAISE_APPLICATION_ERROR (-20051, 'Invalid Path'); WHEN UTL_FILE.INVALID_MODE THEN RAISE_APPLICATION_ERROR (-20052, 'Invalid Mode'); WHEN UTL_FILE.INTERNAL_ERROR THEN RAISE_APPLICATION_ERROR (-20053, 'Internal Error'); WHEN UTL_FILE.INVALID_OPERATION THEN RAISE_APPLICATION_ERROR (-20054, 'Invalid Operation'); END;

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.9

11.9

Closing Files ¾ FCLOSE ¾

The UTL_FILE function used to close a file UTL_FILE.FCLOSE(file UTL_FILE.FCLOSE(file handle); handle);

¾ FCLOSE_ALL ¾

The UTL_FILE function used to close all open files at once UTL_FILE.FCLOSE_ALL; UTL_FILE.FCLOSE_ALL;

© 2006 SkillBuilders, Inc.

An open file can be closed by the UTL_FILE package using the FCLOSE procedure. The FCLOSE procedure takes one parameter as input, a file handle of type FILE_TYPE and has no return value. All open files can also be closed at once using the UTL_FILE procedure FCLOSE_ALL. FCLOSE_ALL procedure takes no input parameters and has no return values.

The

Exceptions UTL_FILE.INVALID_FILEHANDLE

File handle does not point to an open file

UTL_FILE.WRITE_ERROR

Oracle error during write

UTL_FILE.INTERNAL_ERROR

Oracle internal error

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.10

Closing Files Example (including exception processing block)

CREATE OR REPLACE PROCEDURE p_utl_close IS v_filehandle_input UTL_FILE.FILE_TYPE; BEGIN IF NOT UTL_FILE.IS_OPEN (v_filehandle_input) THEN v_filehandle_input := UTL_FILE.FOPEN(‘CLASS’ , 'input_file.txt', 'r'); END IF; UTL_FILE.FCLOSE (v_filehandle_input); EXCEPTION WHEN UTL_FILE.INVALID_PATH THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20051, 'Invalid Path'); WHEN UTL_FILE.INVALID_MODE THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20052, 'Invalid Mode'); WHEN UTL_FILE.INTERNAL_ERROR THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20053, 'Internal Error'); WHEN UTL_FILE.INVALID_OPERATION THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20054, 'Invalid Operation'); WHEN UTL_FILE.WRITE_ERROR THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20055, 'Write Error'); WHEN OTHERS THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20056, 'Others Error'); END; /

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.11

11.11

Reading Files ¾ GET_LINE ¾

The UTL_FILE function used to read a file UTL_FILE.GET_LINE(file UTL_FILE.GET_LINE(file handle, handle, buffer); buffer);

© 2006 SkillBuilders, Inc.

A file can be read by the UTL_FILE package using the GET_LINE procedure. The GET_LINE procedure takes one parameter as input, a file handle of type FILE_TYPE and returns one line of text into a buffer variable of type VARCHAR2. Note: The maximum length of an input line that can be read by the UTL_FILE procedure GET_LINE is 32K. Exceptions UTL_FILE.INVALID_FILEHANDLE

File handle does not point to an open file

UTL_FILE.READ_ERROR

Oracle error during read

UTL_FILE.INTERNAL_ERROR

Oracle internal error

UTL_FILE.INVALID_OPERATION

File not properly opened

VALUE_ERROR

Line of text does not fit into buffer variable

NO_DATA_FOUND

Last line of text is read from file

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.12

11.12

Reading Files Example SQL> SQL> CREATE CREATE OR OR REPLACE REPLACE PROCEDURE PROCEDURE readit readit 22 IS IS 33 v_filehandle_input v_filehandle_input UTL_FILE.FILE_TYPE; UTL_FILE.FILE_TYPE; 44 v_newline VARCHAR2(32767); v_newline VARCHAR2(32767); 55 BEGIN BEGIN 66 v_filehandle_input v_filehandle_input := := 77 UTL_FILE.FOPEN(‘CLASS','functions.sql', UTL_FILE.FOPEN(‘CLASS','functions.sql', 'r', 'r', 32767 32767 ); ); 88 loop loop 99 BEGIN BEGIN 10 UTL_FILE.GET_LINE(v_filehandle_input,v_newline); 10 UTL_FILE.GET_LINE(v_filehandle_input,v_newline); 11 DBMS_OUTPUT.PUT_LINE(v_newline); 11 DBMS_OUTPUT.PUT_LINE(v_newline); 12 EXCEPTION 12 EXCEPTION 13 WHEN 13 WHEN NO_DATA_FOUND NO_DATA_FOUND THEN THEN EXIT EXIT ;; 14 END; 14 END; 15 15 end end loop; loop; 16 UTL_FILE.FCLOSE 16 UTL_FILE.FCLOSE (v_filehandle_input) (v_filehandle_input) ;; 17 17 end; end; SQL> SQL> exec exec readit readit 18 select 18 // select unistr('\0300') unistr('\0300') from from dual; dual; Procedure Procedure created. created.

select select compose('de' compose('de' || || unistr('\0300') unistr('\0300') )) from from dual; dual; PL/SQL PL/SQL procedure procedure successfully successfully completed. completed. © 2006 SkillBuilders, Inc.

In this example, the GET_LINE procedure is executed within a loop until the NO_DATA_FOUND exception is raised. At that time, the loop is exited and processing continues. Why is there a nested BEGIN…END within the LOOP construct? Recall that when an exception is raised, control passes to the EXCEPTION block. By nesting another BEGIN…END within the outer one, we can code the inner block’s exceptions to handle only the specific errors that are related to the GET_LINE procedure. The outer EXCEPTION block would handle exceptions related to the outer BEGIN…END. This helps to tighten up code and insures that exceptions are handled immediately within the block that caused the error rather than having to propagate the error to a calling, or outer, block. Refer to the supplied script UTL_FILE_DEMO.SQL for a working copy of this example.

continued…

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.13

Another Reading Files Example CREATE OR REPLACE PROCEDURE p_utl_read IS v_filehandle_input UTL_FILE.FILE_TYPE; v_newline VARCHAR2 (32767); BEGIN IF NOT UTL_FILE.IS_OPEN (v_filehandle_input) THEN v_filehandle_input := UTL_FILE.FOPEN('CLASS','input_file.txt', 'r'); END IF; LOOP BEGIN UTL_FILE.GET_LINE (v_filehandle_input, v_newline); DBMS_OUTPUT.PUT_LINE (v_newline); EXCEPTION WHEN NO_DATA_FOUND THEN EXIT; END; END LOOP; UTL_FILE.FCLOSE (v_filehandle_input); EXCEPTION WHEN UTL_FILE.INVALID_PATH THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20051, 'Invalid Path'); WHEN UTL_FILE.INVALID_MODE THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20052, 'Invalid Mode'); WHEN UTL_FILE.INTERNAL_ERROR THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20053, 'Internal Error'); . . . . continued . . . .

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.14

Reading Files Example (continued)

. . . . WHEN UTL_FILE.INVALID_OPERATION THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20054, 'Invalid Operation'); WHEN UTL_FILE.WRITE_ERROR THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20055, 'Invalid Operation'); WHEN UTL_FILE.INVALID_FILEHANDLE THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR(-20056, 'Invalid Filehandle’); WHEN UTL_FILE.READ_ERROR THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20057, 'Read Error'); WHEN VALUE_ERROR THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20058, 'Value Error'); WHEN OTHERS THEN UTL_FILE.FCLOSE_ALL; RAISE_APPLICATION_ERROR (-20059, 'Others Error'); END; /

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.15

11.15

Writing Files ¾ PUT ¾

Outputs a text string to a file without a newline

¾ PUT_LINE ¾

Outputs a text string to a file with a newline

¾ NEW_LINE ¾

Outputs a single newline to a file

¾ PUTF ¾

Outputs a formatted string to a file without a newline and accepts up to 5 substitution strings into the formatted string © 2006 SkillBuilders, Inc.

A file can be written to by the UTL_FILE package using any of the following procedures: PUT, PUT_LINE, NEW_LINE or PUTF. All procedures use a file handle of type FILE_TYPE and other various input parameters based on their individual functionality. Before a UTL_FILE write procedure may be used, the output file must be opened with a mode of “w” or “a”. NOTE: Release 8.1.5 has a bug that can produce a “no_data_found” exception on the PUT_LINE call. This is fixed in 8.1.6. Workaround is to OPEN w/o specifying length, CLOSE, then reopen with the length. Visit http://asktom.oracle.com and search on “no_data_found utl_file.put_line” for a complete description.

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.16

11.16

Writing Files- PUT ¾ PUT ¾

Outputs a text string to the specified file pointed to by the file handle without a newline character at the end of the string

UTL_FILE.PUT UTL_FILE.PUT (file (file handle, handle, buffer); buffer);

© 2006 SkillBuilders, Inc.

The PUT procedure takes two arguments as input, a file handle of type FILE_TYPE and a buffer variable of type VARCHAR2. The PUT procedure outputs a text string to the specified file pointed to by the file handle. The PUT procedure has no return values. Supplemental Notes ¾ The maximum length of an output line that can be written by the UTL_FILE procedure PUT is 32K. ¾ The PUT command will not add a newline character to the end of the string.

Exceptions UTL_FILE.INVALID_FILEHANDLE

File handle does not point to an open file

UTL_FILE.INVALID_OPERATION

File not properly opened for reading

UTL_FILE.WRITE_ERROR

Oracle error during write

UTL_FILE.INTERNAL_ERROR

Oracle internal error

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.17

11.17

Writing Files- PUT_LINE ¾ PUT_LINE ¾

Outputs a text string to the specified file pointed to by the file handle with a newline character at the end of the string

UTL_FILE.PUT_LINE UTL_FILE.PUT_LINE (file (file handle, handle, buffer); buffer);

© 2006 SkillBuilders, Inc.

The PUT_LINE procedure takes two arguments as input, a file handle of type FILE_TYPE and a buffer variable of type VARCHAR2. The PUT_LINE procedure outputs a text string to the specified file pointed to by the file handle. The PUT_LINE procedure has no return values. Notes ¾ The maximum length of an output line that can be written by the UTL_FILE procedure PUT_LINE is 32K. ¾ The PUT command will add a newline character to the end of the string.

Exceptions UTL_FILE.INVALID_FILEHANDLE

File handle does not point to an open file

UTL_FILE.INVALID_OPERATION

File not properly opened for reading

UTL_FILE.WRITE_ERROR

Oracle error during write

UTL_FILE.INTERNAL_ERROR

Oracle internal error

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.18

11.18

Writing Files- NEW_LINE ¾ NEW_LINE ¾

Outputs a single newline character to the specified file pointed to by the file handle

UTL_FILE.NEW_LINE UTL_FILE.NEW_LINE (file (file handle, handle, lines:=#); lines:=#);

© 2006 SkillBuilders, Inc.

The NEW_LINE procedure takes two arguments as input, a file handle of type FILE_TYPE and a lines variable of type NATURAL. The NEW_LINE procedure outputs a single newline character to the specified file pointed to by the file handle. The default number for the lines variable is one. The NEW_LINE procedure has no return values. Exceptions UTL_FILE.INVALID_FILEHANDLE

File handle does not point to an open file

UTL_FILE.INVALID_OPERATION

File not properly opened for reading

UTL_FILE.WRITE_ERROR

Oracle error during write

UTL_FILE.INTERNAL_ERROR

Oracle internal error

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.19

11.19

Writing Files- PUTF ¾ PUTF ¾

Outputs a formatted string

UTL_FILE.PUTF UTL_FILE.PUTF (file (file handle, handle, format, format, substitution substitution string string 1-5); 1-5);

Similar to the FPRINTF function in C © 2006 SkillBuilders, Inc.

PUTF is a put with Formatting. It outputs a formatted string to the file pointed to by the file handle without a newline character at the end of the string and accepts up to 5 substitution strings into the formatted string

© 2006 SkillBuilders, Inc.

V2.1

File I/O Using UTL_FILE

11.20

11.20

Writing Files Example .. .. .. .. UTL_FILE.PUT(v_filehandle_output, UTL_FILE.PUT(v_filehandle_output, v_newline) v_newline) ;; UTL_FILE.NEW_LINE(v_filehandle_output) UTL_FILE.NEW_LINE(v_filehandle_output) ;; UTL_FILE.PUT_LINE(v_filehandle_output, UTL_FILE.PUT_LINE(v_filehandle_output, v_newline); v_newline); UTL_FILE.PUTF(v_filehandle_output UTL_FILE.PUTF(v_filehandle_output ,'This ,'This %s %s will will %s %s aa \n \n %s %s %s %s value value %s' %s' ,'string' ,'string' ,'have' ,'have' ,'single' ,'single' ,'NULL'); ,'NULL'); .. .. .. ..

© 2006 SkillBuilders, Inc.

In this example, each of the 4 procedures for writing to files is demonstrated. This code would be added immediately following the GET_LINE loop construct in the reading files example to write out the information read from the input file. String arguments are substituted in the format string, in order, for each %s. Additional %s gets . /n in the string represents a newline character. If the V_NEWLINE variable contained the string ‘This is your life Charlie Brown’, the information written to the output file from the example code would appear as follows: This is your life Charlie Brown

SQL> alter alter system system set set job_queue_processes=10 job_queue_processes=10 scope=both; scope=both; System System altered. altered.

© 2006 SkillBuilders, Inc.

The following INIT.ORA parameter is required for job scheduling: ¾

JOB_QUEUE_PROCESSES: A value between 0 and 1000 that indicates the maximum number of Jnnn processes that can be started. The default value is 0. The value must be non-zero for job scheduling to occur. A non-zero value starts the CJQ0 process.

ALTER SYSTEM privilege is required to adjust initialization parameters; assistance from your DBA.

© 2006 SkillBuilders, Inc.

this will likely require

V2.1

Using DBMS_JOB

12.5

12.5

DBMS_JOB.SUBMIT ¾ SUBMIT procedure puts job on the job queue SQL> SQL> desc desc dbms_job dbms_job PROCEDURE PROCEDURE SUBMIT SUBMIT Argument Type In/Out Argument Name Name Type In/Out Default? Default? ------------------------------------------------------------------------------------ ----------------------- ------ --------------JOB BINARY_INTEGER OUT JOB BINARY_INTEGER OUT WHAT VARCHAR2 IN WHAT VARCHAR2 IN NEXT_DATE DATE IN DEFAULT NEXT_DATE DATE IN DEFAULT INTERVAL VARCHAR2 IN DEFAULT INTERVAL VARCHAR2 IN DEFAULT NO_PARSE BOOLEAN IN DEFAULT NO_PARSE BOOLEAN IN DEFAULT INSTANCE BINARY_INTEGER IN DEFAULT INSTANCE BINARY_INTEGER IN DEFAULT FORCE BOOLEAN IN DEFAULT FORCE BOOLEAN IN DEFAULT © 2006 SkillBuilders, Inc.

The SUBMIT procedure is used to submit a job to the job queue for later execution. Users require EXECUTE privilege on DBMS_JOB and privilege on the procedure they want to schedule. Parameters job – Job number created by the sequence SYS.JOBSEQ. This is an OUT parameter. what – The PL/SQL job name; the PL/SQL job name is usually a call to a stored procedure. The job name should be enclosed in single quotes and terminated with a semicolon. next_date – The date a job will run next (after the initial SUBMIT and COMMIT). Default is SYSDATE. interval – Function to calculate the next job run time. Evaluated before next_date. Every 3 hours: SYSDATE + 3/24, every Sunday at 6am: NEXT_DAY(TRUNC(SYSDATE),”SUN”) + 6/24. Default is NULL, meaning it will not be run again. no_parse – Determines if a job will be parsed at submit time (FALSE) or at execute time (TRUE). The default is FALSE. instance – Specifies which instance can run the job (default is any instance). Refer to the Oracle9i Supplied PL/SQL Packages and Types Reference for a complete description of the parameters.

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.6

12.6

SUBMIT Example SQL> SQL> CREATE CREATE OR OR REPLACE REPLACE PROCEDURE PROCEDURE p_run_insert p_run_insert IS IS 22 BEGIN BEGIN 33 INSERT INTO run_table VALUES ('Execution INSERT INTO run_table VALUES ('Execution at at '||to_char(sysdate, '||to_char(sysdate, 'dd-mon-yy 'dd-mon-yy hh:mi:ss') hh:mi:ss') )) ;; 44 COMMIT COMMIT ;; 55 END; END; 66 // Procedure Procedure created. created. SQL> SQL> VARIABLE VARIABLE p_jobno p_jobno number number SQL> SQL> BEGIN BEGIN 22 DBMS_JOB.SUBMIT DBMS_JOB.SUBMIT (:p_jobno,'P_RUN_INSERT;', (:p_jobno,'P_RUN_INSERT;', SYSDATE, SYSDATE, 'SYSDATE 'SYSDATE ++ (10/(24*60*60))'); (10/(24*60*60))'); 33 COMMIT; COMMIT; /* /* must must commit commit after after SUBMIT SUBMIT */ */ 44 END; SQL> END; SQL> PRINT PRINT p_jobno p_jobno 55 // P_JOBNO P_JOBNO PL/SQL PL/SQL procedure procedure successfully successfully completed. completed. ------------------11 © 2006 SkillBuilders, Inc.

This example submits the procedure P_RUN_INSERT to run immediately (SYSDATE is passed to the NEXT_DATE parameter) and schedules it to run again every 10 seconds (based on the interval parameter). The P_RUN_INSERT procedure requires this table: SQL> CREATE TABLE run_table (message VARCHAR2(40)); Note that the job parameter is an OUT parameter. This value is generated from the sequence SYS.JOBSEQ. Once a job number is assigned, it never changes. In order to determine the job number assigned you can check the USER_JOBS data dictionary table or you could submit the job using an anonymous PL/SQL block from SQL*Plus as shown above. NOTE: You must issue a COMMIT after DBMS_JOB.SUBMIT, or your job will NOT be processed. Interestingly, you will see the job listed in in USER_JOBS, but it will not be processed until you COMMIT. We can see that the job is running by querying the RUN_TABLE table: SQL> select * from run_table; MESSAGE ------------------------------Execution at 30-jun-04 04:46:38 Execution at 30-jun-04 04:47:19

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.7

12.7

Running a Job ¾ RUN procedure will execute a job immediately ¾ Run job on demand ¾ Run a “broken” job ¾ ¾

Fix a broken job Debug a job

SQL> SQL> select select job, job, what, what, to_char(last_date, to_char(last_date, 'mm/dd 'mm/dd hh:mi') hh:mi') 22 from from user_jobs; user_jobs; JOB TO_CHAR(LAS JOB WHAT WHAT TO_CHAR(LAS ------------------- ----------------------------------------------------------- --------------------22 P_RUN_INSERT; 06/30 P_RUN_INSERT; 06/30 04:57 04:57 SQL> SQL> exec exec dbms_job.run(2) dbms_job.run(2) PL/SQL PL/SQL procedure procedure successfully successfully completed. completed. © 2006 SkillBuilders, Inc.

The RUN procedure is used to cause immediate execution of a job on the job queue (use the SUBMIT procedure to put a job on the queue). A call to SUBMIT must precede a call to RUN. When a job is run immediately, it is run using the current process and not by a “Jnnn” background process. In addition to running a job before its next scheduled run, the RUN procedure can be used to run “broken” jobs. Question: What is a broken job? Answer: If a job fails it is resubmitted one minute after the first failure. If it fails again, it is resubmitted two minutes later, and if it fails once again, it is resubmitted after four minutes and so on for a total of 16 attempts. After that point, a job is considered broken. You can use RUN to execute the job; if it succeeds it is marked as not broken (see the BROKEN column of USER_JOBS). Parameters ¾

job – Job number. The job number is created when the job is submitted. As shown above, you can query the USER_JOBS dictionary view to find jobs and job numbers.

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.8

12.8

Cleaning Up Broken Jobs ¾ Jobs are “broken” after 16 failures ¾

Will no longer execute

¾ BROKEN procedure can set job to not broken SQL> SQL> select select job, job, what, what, broken broken 22 from from user_jobs; user_jobs;

Job Jobisisbroken broken

JOB BB JOB WHAT WHAT ------------------- ----------------------------------------------------------- -33 GATHER_MY_STATS; YY GATHER_MY_STATS; SQL> SQL> exec exec dbms_job.broken(3,FALSE); dbms_job.broken(3,FALSE);

Fix Fixjob job

PL/SQL PL/SQL procedure procedure successfully successfully completed. completed. © 2006 SkillBuilders, Inc.

If a job fails 16 times, Oracle marks the job as “broken”. The BROKEN procedure is used to break or, more commonly, to “un-break” a broken job. Parameters ¾

job – Job number created at SUBMIT.

¾

broken

¾

next_date – The date the job will run next (default is SYSDATE)

TRUE - job is flagged as broken; FALSE - job is flagged as not broken

A broken job can also be executed using the RUN procedure.

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.9

12.9

Removing a Job ¾ The REMOVE procedure will remove a job from the queue SQL> SQL> exec exec dbms_job.remove(2) dbms_job.remove(2) PL/SQL PL/SQL procedure procedure successfully successfully completed. completed.

© 2006 SkillBuilders, Inc.

You may remove a job from the queue at any time by calling the REMOVE procedure. The REMOVE procedure takes only one parameter, the job number. If a job is currently running when a call to REMOVE is made, it will be removed from the queue after it finishes executing.

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.10

12.10

Changing Job Parameters ¾ CHANGE DBMS_JOB.CHANGE(job,what,next_date,interval,instance,force); DBMS_JOB.CHANGE(job,what,next_date,interval,instance,force);

¾ WHAT DBMS_JOB.WHAT(job,what); DBMS_JOB.WHAT(job,what);

¾ NEXT_DATE DBMS_JOB.NEXT_DATE(job,next_date); DBMS_JOB.NEXT_DATE(job,next_date);

¾ INTERVAL DBMS_JOB.INTERVAL(job,interval); DBMS_JOB.INTERVAL(job,interval);

¾ INSTANCE DBMS_JOB.INSTANCE(job,instance); DBMS_JOB.INSTANCE(job,instance); © 2006 SkillBuilders, Inc.

The parameters for a job can be changed after the job has been submitted using the procedures CHANGE, WHAT, NEXT_DATE, INSTANCE and INTERVAL. The CHANGE procedure changes more than one job parameter at once while the other procedures change only the specific characteristic. All the parameters behave the same as they do in the SUBMIT procedure. Refer to the Oracle9i Supplied PL/SQL Packages and Types Reference for a complete description of the procedures.

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.11

12.11

Viewing Job Information ¾ DBA_JOBS and USER_JOBS ¾

Information about queued jobs

¾ DBA_JOBS_RUNNING ¾

Information about currently running jobs

© 2006 SkillBuilders, Inc.

Information about currently executing jobs and the success or failure of previously submitted jobs is available in the data dictionary. ¾

USER_JOBS provide information about a job such as job number, last run date and next run date.

¾

DBA_JOBS_RUNNING provides information about jobs that are currently running. There is no ALL nor USER version of this view.

© 2006 SkillBuilders, Inc.

V2.1

Using DBMS_JOB

12.12

12.12

Using DBMS_JOB Workshop ¾ DBMS_JOB

© 2006 SkillBuilders, Inc.

Workshop – DBMS_JOB 1. Verify that the JOB_QUEUE_PROCESSES parameter is not zero: SHOW PARAMETER JOB_QUEUE_PROCESSES If it is zero, modify it from a DBA account as follows: ALTER SYSTEM SET JOB_QUEUE_PROCESSES = 5; 2. Schedule a 3 AM nightly job to gather statistics on all the objects in your schema. 1. First, execute the supplied script DBMS_JOB_WORKSHOP_SETUP.SQL to create the required test table and procedure. 2. Next, submit a job to the queue to execute immediately and then again every night at 3 AM. 3. Verify that the job ran. Note that it may take a little time before the job completes.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.1

Lesson 13 Profile and Tune Profile and tune PL/SQL with DBMS_PROFILER.

© 2006 SkillBuilders, Inc.

© 2006 SkillBuilders, Inc.

SKILLBUILDERS

V2.1

Profile and Tune

13.2

13.2

Lesson Objectives ¾What can be tuned? ¾Using DBMS_PROFILER

© 2006 SkillBuilders, Inc.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.3

13.3

Introduction to Tuning PL/SQL ¾ Biggest gains often from tuning embedded SQL Tuning Course SQL ¾ ¾

TKPROF, EXPLAIN, AUTOTRACE V$SQL_PLAN, V$SQL_PLAN_STATISTICS

¾ Use DBMS_PROFILER for PL/SQL code ¾ ¾

Find problem areas Test different techniques to find fastest

This lesson…

© 2006 SkillBuilders, Inc.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.4

13.4

DBMS_PROFILER ¾ Collect and store performance data for PL/SQL programs ¾ Data stored in tables ¾ ¾ ¾

PLSQL_PROFILER_RUNS PLSQL_PROFILER_UNITS PLSQL_PROFILER_DATA

© 2006 SkillBuilders, Inc.

DBMS_PROFILER collects and saves performance data for PL/SQL programs. The data is stored in tables.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.5

13.5

Profiler Setup ¾ If DBMS_PROFILER not available ¾

Run PROFLOAD.SQL as SYSDBA

¾ Run PROFTAB.SQL under your username ¾

Creates tables

¾ Run PROFREP.SQL under your username ¾

Creates views & packages for reporting

© 2006 SkillBuilders, Inc.

If DBMS_PROFILER is not available, the following script will need to be run: $ORACLE_HOME/rdbms/admin/profload.sql (must be logged in as SYSDBA). DESCRIBE DBMS_PROFILER to determine if it is available. Next, run the following script to create tables to hold the performance data: ORACLE_HOME/rdbms/admin/proftab.sql (logged in as your USER id). This script (9.2.0.4) is supplied with the course. The username requires the following privileges: ¾ create sequence ¾ create view ¾ create procedure Next, run the $ORACLE_HOME/plsql/demo/profrep.sql script to create some views and packages needed for reporting. This script (9.2.0.4) is also supplied with the course.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.6

13.6

Using Profiler ¾ Start profiler with DBMS_PROFILER.START_PROFILER ¾

Consider a LOGON trigger

¾ Run your code ¾ Stop profiler DBMS_PROFILER.STOP_PROFILER ¾ Run PROFSUM.SQL script to create report ¾

Use version supplied with this course

¾ Optionally run PROFRESET.SQL to clear data © 2006 SkillBuilders, Inc.

The use of this package is very simple. You start the profiler, run your code and stop the profiler. The PL/SQL engine will have populated the 3 profiler tables with the performance and code coverage information. Then run the Oracle script PROFSUM.SQL to create a report. There are 3 basic subprograms within the DBMS_PROFILER package. ¾ The START_PROFILER function starts profiling in the current session. You can provide an optional string to give a name to the profiling session if you do not want to use only the default, SYSDATE. Starting the profiler can be done in a LOGON trigger or directly in the application code. ¾ The STOP_PROFILER function ends profiling in the current session. This function also implicitly “flushes” the data into the profiler tables. The profiler data is collected in memory data structures until it is “flushed” or written to the profiler tables. STOP_PROFILER does an implicit FLUSH_DATA when it is executed. ¾ The FLUSH_DATA function allows profiler data collected in memory to be “flushed” or written to the profiler tables. You may want to call FLUSH_DATA at intermediate points within your application during the profiling session to write the collected data into the profiler tables and free the memory used to collect profile data.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.7

13.7

Testing SQL> SQL> create create or or replace replace procedure procedure modtest modtest 22 as as 33 begin begin 44 dbms_profiler.start_profiler('mod'); dbms_profiler.start_profiler('mod'); 55 for for xx in in 1..1000 1..1000 loop loop 66 if if mod(x,100) mod(x,100) == 00 then then null; null; end end if; if; 77 end end loop; loop; 88 dbms_profiler.stop_profiler; dbms_profiler.stop_profiler; 99 end; end; 10 10 // SQL> SQL> exec exec modtest modtest Procedure created. Procedure created. PL/SQL procedure successfully completed. PL/SQL procedure successfully completed. SQL> SQL> exec exec countertest countertest PL/SQL PL/SQL procedure procedure successfully successfully completed. completed. © 2006 SkillBuilders, Inc.

The profiler is good for comparing the performance of similar routines. In this example I am comparing the performance of the MOD function to a manual counter as shown in this routine: SQL> create or replace procedure countertest 2 as 3 counter number := 0; 4 begin 5 dbms_profiler.start_profiler('counter'); 6 for x in 1..1000 loop 7 counter := counter + 1; 8 if counter = 100 then counter := 0; end if; 9 end loop; 10 dbms_profiler.stop_profiler; 11 end; 12 / Procedure created. Execute the supplied script PROFILER.SQL to test this on your system.

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.8

13.8

Reporting SQL> SQL> @profsum @profsum Total Total time time spent spent on on each each run run RUNID SECS RUNID RUN_COMMENT RUN_COMMENT SECS --------- --------------------- ------------34 1.77 34 mod mod 1.77 35 .81 35 counter counter .81

Counter Counterwas was faster fasterthan than MOD MOD

MOD MOD function functiontook took most mostof ofthe the time time

Lines Lines taking taking more more than than 1% 1% of of the the total total time, time, each each run run separate separate RUNID PCT UNIT_NAME LINE# RUNID HSECS HSECS PCT OWNER OWNER UNIT_NAME LINE# TEXT TEXT --------- ------------- ----------- --------------------- ----------------------- ----------- ------------------------------34 MODTEST 66 if 34 148.35 148.35 57.5 57.5 DAVE DAVE MODTEST if mod(x,100)=0 mod(x,100)=0 then then null; null; end end if; if; 35 35

29.22 29.22

11.3 11.3 DAVE DAVE

COUNTERTEST COUNTERTEST

66 for for xx in in 1..1000 1..1000 loop loop

© 2006 SkillBuilders, Inc.

Here is an excerpt of the report created by the PROFSUM.SQL script (this script is provided by Oracle; a copy is included in your class scripts). We can see that the MOD function was the main reason that the MODTEST routine was slower than the COUNTER routine. Bug Report The timings reported on an Intel/Windows server are not always accurate. Oracle Corp claims this is an Intel bug: “This is a vendor/os problem rather than an oracle problem because the RDTSC instruction is reporting wrong time stamp counter. Found in some INTEL Pentium processor Errata that there is indeed such as problem and no plans to fix that. Also the problem only exists on Windows as this is port specific bug. Metalink Bug 2207526.”

© 2006 SkillBuilders, Inc.

V2.1

Profile and Tune

13.9

13.9

Profile & Tune PLSQL Workshop ¾ Using DBMS_PROFILER

© 2006 SkillBuilders, Inc.

Workshop – Using DBMS_PROFILER If your database is running on an Intel Windows platform, it is likely that the timings reported by the Profiler will be incorrect. As Oracle claims this is an Intel bug, there’s not much we can do about this. 1.

Profile the two different routines supplied in the script WORKSHOP_PROFILER_SETUP.SQL. One routine use row-at-a-time processing; the other routine uses bulk processing to accomplish the same task.

2.

Which routine is faster?

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.1

A. Dynamic SQL What is dynamic SQL? Execute DDL, DML and Anonymous PL/SQL Blocks dynamically Constructs needed to perform dynamic SQL Benefits of dynamic SQL Contrast NDS with DBMS_SQL © 2006 SkillBuilders, Inc.

© 2006 SkillBuilders, Inc.

SKILLBUILDERS

V2.1

Dynamic SQL

A.2

A.2

What is Dynamic SQL? ¾ Allows SQL statements that are not known at compile time to be parsed at run time ¾ Dynamic SQL can process: ¾ ¾ ¾ ¾

DML: INSERT, UPDATE, DELETE, SELECT DDL: CREATE, ALTER, DROP DCL: GRANT, REVOKE PL/SQL: Anonymous blocks, calls to other PL/SQL programs from within an anonymous block © 2006 SkillBuilders, Inc.

What is Dynamic SQL? Dynamic SQL is, as its name implies, dynamic as compared to normal in-line SQL statements. A static SQL statement knows, at compile time, exactly which table and columns within the table are used/effected as well as what the WHERE clause specifies. Dynamic SQL allows many of the things that need to be known at compile time to be postponed until runtime. Dynamic SQL also provides a work around for the PL/SQL restriction disallowing DDL in PL/SQL blocks. With Dynamic SQL, not only can DML be executed, but so can DDL and DCL statements as well as PL/SQL anonymous blocks. Dynamic SQL can be implemented using the DBMS_SQL package or through the use of Native Dynamic SQL. Prior to Oracle8i, dynamic SQL was implemented through the DBMS_SQL package. But there were some problems with DBMS_SQL: it is a very complicated package, it has a number of restrictions and it is relatively slow. So, with Oracle8i, dynamic SQL was re-implemented directly in the PL/SQL language itself and was called Native Dynamic SQL, or NDS. In general, NDS is faster and is easier to build, read and maintain. ۞ Sybase supports the EXECUTE IMMEDIATE syntax similar to Oracle’s Native Dynamic SQL (NDS) support. MS SQL Server uses the equivalent syntax EXEC sp_executesql 'sql Statement'

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.3

A.3

NDS vs. DBMS_SQL ¾ Exclusive NDS capabilities: ¾ ¾

Works with all datatypes (objects, collections, etc) Allows fetching of multiple columns directly into a PL/SQL record

¾ Exclusive DBMS_SQL capabilities: ¾ ¾ ¾ ¾

Allows you to use DESCRIBE Supports SQL statements > 32KB in length Supports the use of the RETURNING clause into an array of values Allows you to reuse your dynamic SQL cursors © 2006 SkillBuilders, Inc.

DBMS_SQL vs. NDS Given the fact that NDS executes faster and is easier to build, read and maintain, why would anyone ever use DBMS_SQL again? Well, NDS may not do everything you want it to do and DBMS_SQL is your only choice in pre-8i environments. There are some capabilities only available to you with DBMS_SQL and some capabilities only available with NDS as shown here. Exclusive NDS Capabilities NDS works with all datatypes whereas DBMS_SQL only works with Oracle7-compatible datatypes. NDS allows fetching of multiple columns directly into a PL/SQL record. With DBMS_SQL, you must fetch into individual variables. Exclusive DBMS_SQL Capabilities DBMS_SQL allows you to describe the columns of your dynamic cursor, obtaining column information in an index-by table of records. DBMS_SQL supports large SQL statements whereas NDS is constrained to a 32KB limit . . . . continued . . . .

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.4

Exclusive DBMS_SQL Capabilities (continued) DBMS_SQL supports the use of the RETURNING clause into an array of values. NDS only allows the use of RETURNING for a single statement. DBMS_SQL allows you to reuse your dynamic SQL cursors, which can improve performance. DBMS_SQL can be executed from client-side (Oracle Developer) applications whereas NDS cannot.

From these lists, we can conclude that NDS implementation should be able to handle the majority of the dynamic SQL requirements you are likely to encounter. But, in those instances when NDS just does not do it all, DBMS_SQL is still a viable alternative.

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.5

A.5

NDS Statement Summary ¾ EXECUTE IMMEDIATE ¾

Executes a specified SQL statement immediately

¾ OPEN FOR ¾

Allows you to perform multi-row dynamic queries

© 2006 SkillBuilders, Inc.

NDS Statement Summary One of the selling points for NDS is its simplicity. Unlike DBMS_SQL, which has dozens of programs and lots of rules to follow, NDS has been integrated into the PL/SQL language by adding one new statement, EXECUTE IMMEDIATE, and by enhancing the existing OPEN FOR statement.

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.6

A.6

NDS Single-Row Query Syntax EXECUTE EXECUTE IMMEDIATE IMMEDIATE statement-string statement-string [INTO {define-variable [INTO {define-variable [, [, define_variable] define_variable] ... | record}] ... | record}] [USING OUT || IN IN OUT] OUT] bind-argument bind-argument [USING [IN [IN || OUT [,[IN | OUT | IN OUT] bind-argument]...]; [,[IN | OUT | IN OUT] bind-argument]...];

© 2006 SkillBuilders, Inc.

NDS Single-Row Query Syntax (EXECUTE IMMEDIATE) statement-string = string expression that represents a SQL statement (without the terminator) or PL/SQL block (with the terminator) INTO – (used only for single-row queries) specifies the variables or record into which column values are retrieved define-variable = variable that stores a selected column value record = a user-defined or %ROWTYPE record that stores a selected row USING – specifies all bind arguments; default parameter mode is IN but can specify all modes. At run time, any bind arguments in the USING clause replace corresponding placeholders in the SQL statement or PL/SQL block. So, every placeholder must be associated with a bind argument in the USING clause. bind_argument = an expression whose value is passed to or returned by the dynamic SQL statement or PL/SQL block

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.7

A.7

NDS Single-Row INSERT Example CREATE CREATE OR OR REPLACE REPLACE PROCEDURE PROCEDURE insert_into_dept insert_into_dept (dept_no number, dept_name (dept_no number, dept_name varchar2, varchar2, loc loc varchar2) varchar2) IS IS stmt_str stmt_str varchar2(200); varchar2(200); BEGIN BEGIN stmt_str stmt_str := := 'INSERT 'INSERT INTO INTO dept dept VALUES VALUES (:1,:2,:3)'; (:1,:2,:3)'; EXECUTE IMMEDIATE stmt_str EXECUTE IMMEDIATE stmt_str USING USING IN IN dept_no, dept_no, IN IN dept_name, dept_name, IN IN loc; loc; END; END;

© 2006 SkillBuilders, Inc.

NDS Single-Row Query Example The example shows how the EXECUTE IMMEDIATE statement can perform dynamic single-row queries. You specify bind variables in the USING clause (dept_no, dept_name and loc) which “map” to the placeholders (:1, :2, :3) listed in the statement STRING (STMT_STR). Note that the placeholders are positional and the names do not have to match the bind variables in the USING clause. As a matter of fact, the substitution variables can be named anything you want and can even have duplicate names.

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.8

A.8

NDS Multi-Row Query Syntax OPEN OPEN {cursor_variable {cursor_variable || :host_cursor_variable} :host_cursor_variable} FOR stmnt-string FOR stmnt-string [USING [USING bind-argument[, bind-argument[, bind-argument]...] bind-argument]...] ;;

FETCH FETCH {cursor_variable {cursor_variable || INTO {define_variable[, INTO {define_variable[, record} record} ;;

:host_cursor_variable} :host_cursor_variable} define_variable]... define_variable]... ||

CLOSE CLOSE {cursor_variable {cursor_variable || :host_cursor_variable}; :host_cursor_variable};

© 2006 SkillBuilders, Inc.

NDS Multi-Row Query Syntax OPEN-FOR ¾ cursor_variable = a cursor variable without a return type ¾ host_cursor_variable = a cursor variable declared in a PL/SQL host environment ¾ stmnt-string = string expression that represents a multi-row query FETCH ¾ cursor_variable = a cursor variable without a return type ¾ host_cursor_variable = a cursor variable declared in a PL/SQL host environment ¾ define-variable = variable that stores a selected column value ¾ record = a user-defined or %ROWTYPE record that stores a selected row CLOSE ¾ cursor_variable = a cursor variable without a return type ¾ host_cursor_variable = a cursor variable declared in a PL/SQL host environment

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.9

A.9

NDS Multi-Row Query Example DECLARE DECLARE TYPE TYPE DeptCurTyp DeptCurTyp IS IS REF REF CURSOR CURSOR ;; dept_cv DeptCurTyp dept_cv DeptCurTyp ;; dept_rec dept%ROWTYPE dept_rec dept%ROWTYPE ;; stmt_str varchar2(200); stmt_str varchar2(200); v_dept_no v_dept_no dept.dept_no%TYPE dept.dept_no%TYPE ;; BEGIN BEGIN v_dept_no v_dept_no := := 1; 1; stmt_str stmt_str := := 'SELECT 'SELECT ** FROM FROM dept dept WHERE WHERE dept_no dept_no == :1'; :1'; OPEN OPEN dept_cv dept_cv FOR FOR stmt_str stmt_str USING USING v_dept_no v_dept_no ;; LOOP LOOP FETCH FETCH dept_cv dept_cv INTO INTO dept_rec dept_rec ;; EXIT WHEN dept_cv%NOTFOUND; EXIT WHEN dept_cv%NOTFOUND; --- further further processing processing END END LOOP; LOOP; CLOSE CLOSE dept_cv; dept_cv; END; END; © 2006 SkillBuilders, Inc.

NDS Multi-Row Query Example To perform a multi-row query, you take the following steps: ¾

Declare a REF CURSOR type

¾

Declare a cursor variable based on the REF CURSOR

¾

OPEN the cursor variable FOR your query string

¾

Use the FETCH statement to fetch one row at a time from your query

¾

Check cursor attributes (%NOTFOUND, %ROWCOUNT, etc) as necessary

¾

Close the cursor variable using the normal CLOSE statement

REF CURSOR REF (short for REFERENCE) CURSOR is used in the TYPE declaration to create a user-defined type which is simply a pointer to a memory location. This type is then used to create a cursor variable which is used in the OPEN…FOR statement. Basically, the REF allows you to create a memory location into which the dynamic SQL statement will be retrieved and manipulated at run-time.

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.10

A.10

NDS PL/SQL Example CREATE CREATE OR OR REPLACE REPLACE PROCEDURE PROCEDURE p_nds_plsql p_nds_plsql (p_database IN info.database_name%TYPE) (p_database IN info.database_name%TYPE) IS IS v_sql_stmt VARCHAR2(256); v_sql_stmt VARCHAR2(256); v_instance info.instance_name%TYPE; v_instance info.instance_name%TYPE; BEGIN BEGIN v_sql_stmt v_sql_stmt := := 'BEGIN 'BEGIN '' || || 'SELECT 'SELECT instance_name instance_name '' || || 'INTO 'INTO :sid_name :sid_name '' || || 'FROM 'FROM info info '' || || 'WHERE 'WHERE database_name database_name == :db_name; :db_name; '' || || 'END; ' ; 'END; ' ; EXECUTE EXECUTE IMMEDIATE IMMEDIATE v_sql_stmt v_sql_stmt USING USING OUT OUT v_instance, v_instance, IN IN p_database p_database ;; DBMS_OUTPUT.PUT_LINE(‘Instance: DBMS_OUTPUT.PUT_LINE(‘Instance: ‘‘ || || v_instance) v_instance) ;; END END ;; © 2006 SkillBuilders, Inc.

NDS PL/SQL Example To execute an anonymous PL/SQL block, you take the following steps: ¾

Declare OUT variables, if any

¾

Create a string containing the PL/SQL block

¾

Make sure to include a semicolon (;) within the string to terminate the block

¾

EXECUTE the string

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.11

A.11

DBMS_SQL Procedures Summary ¾ DBMS_SQL.OPEN_CURSOR ¾ DBMS_SQL. PARSE ¾ DBMS_SQL. BIND_VARIABLE ¾ DBMS_SQL. DEFINE_COLUMN ¾ DBMS_SQL. EXECUTE ¾ DBMS_SQL. FETCH_ROWS ¾ DBMS_SQL. VARIABLE_VALUE ¾ DBMS_SQL. COLUMN_VALUE ¾ DBMS_SQL. CLOSE_CURSOR © 2006 SkillBuilders, Inc.

OPEN_CURSOR - Returns the cursor ID of the new dynamic cursor PARSE - Parses the statement (i.e. checks it’s syntax and associates it with the cursor) BIND_VARIABLE - Associates the placeholders in the statement with the value of a variable DEFINE_COLUMN - Specify the variables that are to receive the SELECT values (similar to an INTO clause in a static query) EXECUTE - Executes the cursor FETCH_ROWS - Fetches, or retrieves, a row from the cursor VARIABLE_VALUE - Get the values assigned to output variables (only used when the statement is a PL/SQL block) COLUMN_VALUE - Get the actual value of a column retrieved by FETCH_ROWS CLOSE_CURSOR - Closes the cursor and releases memory To enable DBMS_SQL, the following script will need to be run (while logged in as SYS): dbmssql.sql

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.12

A.12

DBMS_SQL Example CREATE CREATE OR OR REPLACE REPLACE PROCEDURE PROCEDURE insert_into_dept insert_into_dept (( dept_no number, dept_name varchar2, dept_no number, dept_name varchar2, loc loc varchar2) varchar2) IS IS stmt_str stmt_str varchar2(200); varchar2(200); cur_hdl cur_hdl integer; integer; ** rows_processed rows_processed binary_integer; binary_integer; ** BEGIN BEGIN stmt_str stmt_str := := 'insert 'insert into into dept dept values values (:1,:2,:3);'; (:1,:2,:3);'; cur_hdl cur_hdl := := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.OPEN_CURSOR; ** DBMS_SQL.PARSE(cur_hdl, DBMS_SQL.PARSE(cur_hdl, stmt_str, stmt_str, dbms_sql.native); dbms_sql.native); ** DBMS_SQL.BIND_VARIABLE(cur_hdl, ’:1’, DBMS_SQL.BIND_VARIABLE(cur_hdl, ’:1’, dept_no); dept_no); ** DBMS_SQL.BIND_VARIABLE(cur_hdl, ’:2’, dept_name); DBMS_SQL.BIND_VARIABLE(cur_hdl, ’:2’, dept_name); ** DBMS_SQL.BIND_VARIABLE(cur_hdl, DBMS_SQL.BIND_VARIABLE(cur_hdl, ’:3’, ’:3’, loc); loc); ** rows_processed rows_processed := := DBMS_SQL.EXECUTE(cur_hdl); DBMS_SQL.EXECUTE(cur_hdl); ** DBMS_SQL.CLOSE_CURSOR(cur_hdl); DBMS_SQL.CLOSE_CURSOR(cur_hdl); ** END; END; © 2006 SkillBuilders, Inc.

DBMS_SQL Example In this example, we use DBMS_SQL to execute the same query previously shown using NDS. Notice the extra code required to accomplish the same task. Each line marked with * indicates an additional line of code required when using DBMS_SQL that is not necessary when using NDS. Using DBMS_SQL, we must open a cursor, parse the statement, explicitly bind the input variables to the placeholders in the statement, execute the statement and then close the cursor. Using NDS, we would simply have had to execute the statement. All the other tasks occur implicitly.

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.13

A.13

Privileges ¾ EXECUTE must be granted on DBMS_SQL ¾ Proper privileges must be granted for any statements being executed ¾ Privileges must be explicitly granted to the user and not granted through a role

© 2006 SkillBuilders, Inc.

Privileges Since NDS is implemented directly in the PL/SQL language itself, no specific privilege is required to use NDS. However, DBMS_SQL does require that the user be granted EXECUTE privilege on the package prior to use. For any statement (DML, DDL etc) being executed dynamically using DBMS_SQL or NDS, the user must have been granted explicit privileges to that statement. For instance, a user must have been granted the CREATE TABLE privilege before attempting to use dynamic SQL to create a table. A common mistake is to assume that if a certain privilege has been granted to a role and then that role has been granted to the user, all is well. This is not true. All privileges must be explicitly granted to a user and not through a role for dynamic SQL to associate the privileges properly.

© 2006 SkillBuilders, Inc.

V2.1

Dynamic SQL

A.14

A.14

Dynamic SQL Workshop ¾ Dynamic SQL

© 2006 SkillBuilders, Inc.

Workshop 1. Create a table called DYNAMIC_DDL with two columns (col1 number, col2 varchar2(100)). Use your preference of NDS or DBMS_SQL. 2. Write a PL/SQL code block to execute an insert statement to populate the DYNAMIC_DDL table. Run it to insert one or more rows. 3. Write a PL/SQL code block that executes an anonymous PL/SQL block via NDS to select a single row from the DYNAMIC_DDL table and display it to the environment. 4. Write a procedure to implement a dynamic WHERE clause for deletes on any table. The procedure should accept two parameters: 1) table name and 2) a condition (such as col1 = 1) and use them to create a delete statement using NDS. The delete statement will either be capable of deleting all rows in the table (if a null condition is passed) or will delete a specific row based on the condition.

© 2006 SkillBuilders, Inc.

V2.1

Appendix B – Table Descriptions

Page B.1

The following tables are used in this course. SQL> select table_name from user_tables ; TABLE_NAME -----------------------------CUSTOMER CUST_HISTORY DEPARTMENT EMPLOYEE ERRORS LOGIT ORD ORD_HISTORY ORD_ITEM ORD_ITEM_DELIVERY PAYMENT PRODUCT PRODUCT_SUPPLIER SALES_COMMISSION SALES_PER_DAY SPECIAL_OCCASION SUPPLIER CUSTOMER Name ----------------------------------------------------CUST_NO LASTNAME FIRSTNAME MIDINIT STREET CITY STATE ZIP ZIP_4 AREA_CODE PHONE COMPANY_NAME CUST_HISTORY Name ----------------------------------------------------CUST_NO LASTNAME FIRSTNAME MIDINIT STREET CITY STATE ZIP ZIP_4 AREA_CODE PHONE COMPANY_NAME

© 2006 SkillBuilders, Inc.

Null? -------NOT NULL NOT NULL NOT NULL

Type ---------------NUMBER(38) VARCHAR2(20) VARCHAR2(15) VARCHAR2(1) VARCHAR2(30) VARCHAR2(20) VARCHAR2(2) VARCHAR2(5) VARCHAR2(4) VARCHAR2(3) VARCHAR2(8) VARCHAR2(50)

Null? -------NOT NULL NOT NULL NOT NULL

Type ---------------NUMBER(38) VARCHAR2(20) VARCHAR2(15) VARCHAR2(1) VARCHAR2(30) VARCHAR2(20) VARCHAR2(2) VARCHAR2(5) VARCHAR2(4) VARCHAR2(3) VARCHAR2(8) VARCHAR2(50)

V2.1

Appendix B – Table Descriptions DEPARTMENT Name ----------------------------------------------------DEPT_NO DEPT_NAME MGR_NO EMPLOYEE Name ----------------------------------------------------EMP_NO LASTNAME FIRSTNAME MIDINIT STREET CITY STATE ZIP ZIP_4 AREA_CODE PHONE SALARY BIRTHDATE HIREDATE TITLE DEPT_NO MGR REGION DIVISION TOTAL_SALES

Page B.2

Null? -------NOT NULL NOT NULL

Type ---------------NUMBER(38) VARCHAR2(20) NUMBER(38)

Null? -------NOT NULL NOT NULL NOT NULL

Type ---------------NUMBER(38) VARCHAR2(20) VARCHAR2(15) VARCHAR2(1) VARCHAR2(30) VARCHAR2(20) VARCHAR2(2) VARCHAR2(5) VARCHAR2(4) VARCHAR2(3) VARCHAR2(8) NUMBER(5,2) DATE DATE VARCHAR2(20) NUMBER(38) NUMBER(38) NUMBER NUMBER NUMBER

ERRORS Name Null? Type ----------------------------------------------------- -------- ---------------CODE NUMBER MESSAGE VARCHAR(500) PROGRAM VARCHAR(30) ERR_DATE DATE ERR_USER VARCHAR2(30) LOGIT Name Null? Type ----------------------------------------------------- -------- ---------------EVENT VARCHAR2(400) ORD Name ----------------------------------------------------ORDER_NO CUST_NO ORDER_DATE TOTAL_ORDER_PRICE DELIVER_DATE DELIVER_TIME PAYMENT_METHOD EMP_NO

© 2006 SkillBuilders, Inc.

Null? Type -------- ---------------NOT NULL NUMBER(38) NUMBER(38) NOT NULL DATE NUMBER(7,2) DATE VARCHAR2(7) NOT NULL VARCHAR2(2) NUMBER(3)

V2.1

Appendix B – Table Descriptions

Page B.3

DELIVER_NAME GIFT_MESSAGE ORD_HISTORY Name ----------------------------------------------------ORDER_NO CUST_NO ORDER_DATE TOTAL_ORDER_PRICE DELIVER_DATE DELIVER_TIME PAYMENT_METHOD EMP_NO DELIVER_NAME GIFT_MESSAGE ORD_ITEM Name ----------------------------------------------------ORDER_NO PRODUCT_ID QUANTITY ITEM_PRICE

VARCHAR2(35) VARCHAR2(100)

Null? Type -------- ---------------NOT NULL NUMBER(38) NUMBER(38) NOT NULL DATE NUMBER(7,2) DATE VARCHAR2(7) NOT NULL VARCHAR2(2) NUMBER(38) VARCHAR2(35) VARCHAR2(100)

Null? -------NOT NULL NOT NULL

Type ---------------NUMBER(38) NUMBER(38) NUMBER(4) NUMBER(7,2)

Null? -------NOT NULL NOT NULL

Type ---------------NUMBER(38) NUMBER(38) VARCHAR2(30) VARCHAR2(30) VARCHAR2(13) VARCHAR2(50)

Null? -------NOT NULL NOT NULL

Type ---------------VARCHAR2(2) VARCHAR2(30)

PRODUCT Name Null? ----------------------------------------------------- -------PRODUCT_ID NOT NULL PRICE DESCRIPTION ONHAND REORDER SUPPLIER_NO

Type ---------------NUMBER(38) NUMBER(7,2) VARCHAR2(75) NUMBER(5) NUMBER(5) NUMBER(38)

PRODUCT_SUPPLIER Name ----------------------------------------------------PRODUCT_ID SUPPLIER_NO PRICE

Type ---------------NUMBER(38) NUMBER(38) NUMBER(7,2)

ORD_ITEM_DELIVERY Name ----------------------------------------------------ORDER_NO ITEM_NO DEL_ADDRESS DEL_NAME DEL_PHONE MESSAGE PAYMENT Name ----------------------------------------------------PAYMENT_METHOD DESCRIPTION

© 2006 SkillBuilders, Inc.

Null? -------NOT NULL NOT NULL

V2.1

Appendix B – Table Descriptions

Page B.4

SALES_COMMISSION Name ----------------------------------------------------EMP_NO COMMISSION COMM_DATE NOTE

Null? Type -------- ---------------NOT NULL NUMBER(38) NUMBER(7,2) NOT NULL DATE VARCHAR2(50)

SALES_PER_DAY Name ----------------------------------------------------SALES_DATE AMOUNT

Null? -------NOT NULL NOT NULL

Type ---------------DATE NUMBER

Null? -------NOT NULL NOT NULL

Type ---------------NUMBER(38) DATE VARCHAR2(50)

SPECIAL_OCCASION Name ----------------------------------------------------CUST_NO OCCASION_DATE OCCASION_DESCRIPTION

SUPPLIER Name Null? ----------------------------------------------------- -------SUPPLIER_NO NOT NULL SUPPLIER_NAME ADDRESS CITY STATE AREA_CODE PHONE

© 2006 SkillBuilders, Inc.

Type ---------------NUMBER(38) VARCHAR2(50) VARCHAR2(30) VARCHAR2(20) VARCHAR2(2) VARCHAR2(3) VARCHAR2(8)

V2.1