Anda di halaman 1dari 232

ORACLE PLSQL

Procedural Language Structure Query Language

Part 1 : PLSQL Course


Part 2 : PLSQL practices and problems

Prepared By : Ashraf Omar Hussein


Email : ashraf_oh@hotmail.com
Mobile No : +20101552319

Oracle Complete PLSQL Reference 0


Part 1 : PLSQL Course

1. Why do you need PLSQL?


2. PLSQL Block Structure
3. Variables Types
4. Anonymous Block
5. Stored Procedure
6. Parameter
7. Control Structure
7.1 IF Condition
7.2 Case Expression
7.3 Loop
8. Cursor
9. Handle Exception
10. DataBase Trigger
11. Function
12. Package

Oracle Complete PLSQL Reference 1


13.
Q: What is PLSQL ?
A: It is a procedural anguage Structure Query language

Q: Why do you Need PLSQL Language ?

1 Bad peformance for the heavy network traffic

SQL SQL
DATA
SQL SQL
Applicat BASE Applicat
ion1 SQL SQL
ion2

2 Cannt write more than one SQL command at the same Time

3 SQL commands are not depended to each other and Not executed in a specific order

4 SQL command s are not saved in the DB server

5 SQL Commands are not shared for all users

6 SQL Commands cannt handle user Error (Exception)

7 SQL Commands are static NOT Dynamic

8 SQL Commands are executed Manually not Automatically

9 SQL Commands dont use IF condition

10 SQL Command dont use LOOP statement

11 SQl Command dont use

12 SQL Command dont use Variable

Q: What are the benefits of PLSQL ?

1 Improve Performance and reduce network traffic between client and server by agrouping sql statements
together in one block and send it to the server in one call

2 Portability: PlSQl is available on any kind of platform

3 Modularize Programs: can contain nested Blocks

4 Integration: it can be used as developer tools (in forms and reports)or as administration tools

Oracle Complete PLSQL Reference 2


Q: How does PLSQL solve the problems of the SQL commands?

1 By creating a database Block

Q: What is a datablock Block ?

1 It is a dataase structure that contain one or more SQL commands

2 Block require that all SQL Commands to be correct for the execution . if there is one SQL command is
not Correct then the whole block with all SQL Commands will not be exeucted

3 If you write more than one SQL statement you must separate them by using semi comma (;)

Q: what are the block types?


1 Anonymus Bock 2 Subprogram Program Unit
Not stored or saved in the DB server Stored or saved in the DB server
Not shared for all users Shared for all users
Executed only once Executed many times as user requests
Created and executed during run time Created before the execution time
Cannt accept parameter Can Accept Parameter
Has only one type Has 3 types
1. Anonymus Block 1. Stored Procedure
2. Function
3. Package

Anonymous Block Structure

Declaration Part
Optional

Body
Mandatory Exception Part
Optional

Variable
Oracle Complete PLSQL Reference 3
Q: What is a Variable?
1. Is a space located in the memory can be used For Impermanent storage of One an ONLY One Value
2. Variable can store value identified by the user himself OR value retrieved form the data base table

Q: Why do you use a variable?

1- Temporary storage of data:


1.1 Data can be temporarily stored in one or more variables for use when validating data input and
for processing later in the data flow process such as Login Window we store the user name and
password For user to check for these two values if they are stored in the data base the user will be
logined successfully and if they are not stored in the data base the user will not be able to login.

2. Manipulation of stored values:


2.1 Variables can be used for calculations and other data manipulations without accessing database.
2.2 store values for calculation and the result of these calculations will be displayed in the report

3- Reusability:
3.1 After they are declared, variables can be used repeatedly in an application simply by referencing
them in other statements, including other declarative statements such as local variables and global
variables.

4- Ease of maintenance:

4.1 declare new variable has the same data type of other variable
4.2 declare new variable has the same data type of data base column and when changing the value in
the database this value will changed automatically in the variable such as create variable storing the
max value in empno column to create application trigger to increment this value for the next record

Q: How do you declare a variable?


1. You must declare a variable in the declaration part of the block
2. You can decalre more than one variable in the same block BUT you must
2.1 define each varibale in a separate line
2.2 end each varibale with a semi comma (;)
3. Each variable Must has [name, data type] mandatory, [null ability, default value] optional

Q: what are the rules of the Variable name ?


1. Variable names are unique within the same block but variable name may be duplicated in other block
2. Length between 1-30 charater length
3. Must start with character NOT with number or special character BUT it may include numbers and special
character inside the name or at the end
4. Variable name mustnt be the same as column name within the data base
5. It is preferable to start variable name with V_ColumnName if it contain changeable value and
start variable name with C_ColumnName if it contain Constant value
6. If you declare a variable contain constant value so the keyword CONSTANT must precede the data type of
the variable
7. String literals must be enclosed in single quotation marks. For example , 'Hello, world'.
If there is a single quotation mark in the string, use a single quotation mark twice, for example,
to insert a value FISHERMAN'S DRIVE, the string would be 'FISHERMAN''S DRIVE '.

Oracle Complete PLSQL Reference 4


Q: what are the rules when you Assign a value for the Variabe ?
1. It is good code to assign value for the variable because if you did not assign value then null will be inserted
2. To assign value for the variable you can use := or use DEFAULT as keyword
3. Variable value can be constant value or default value or expression
4. Assigning string value must be enclosed between single quotes But numeric value does not require single
quotes
5. If you assign value for the variable in the declaration section and assign new value for the variable in the
execution section the new value will replace the old value in the declaration part

Q: What are the data types for the variables


1. Char(n)
2. Varcahr2(n)
3. Number(n)
4. Number(m,n)
5. Date
6. Binary_integer
7. Boolean
8. Long
9. Long raw

Oracle Complete PLSQL Reference 5


Examples for decalring variables
1. Use user defined datatype

Declare
v_job varchar2(20) null ;
v_location varchar2(50) null := 'cairo';
v_deptno number(5) not null := 10
v_total_sal number(9,2) := 0;
v_mgr number(6) DEFAULT 100;
c_comm CONSTANT number(5) null DEFAULT 1400;
v_hire_date date := TO_CHAR('1998/08/16', 'yyyy/mm/dd');
v_orderdate date := SYSDATE + 3;
c_tax_rate CONSTANT numebr(5,2) := 0.15;
v_valid BOOLEAN not null := TRUE;

2. Use TabeName.ColumnName%type
Declare
v_job emp.job%type ;
v_location dept.dname%type := 'cairo' ;
v_deptno dept.deptno%type not null := 10;
v_total_sal emp.sal%type := 0;
v_mgr emp.mgr%type DEFAULT 100;
c_comm CONSTANT emp.comm%type := 1400;
v_hire_date emp.hiredate%type := TO_CHAR('1998/08/16', 'yyyy/mm/dd');

3. Use Variable%type
Declare
v_job emp.job%type ;
v_location v_job%type := 'cairo' ;
v_deptno dept.deptno%type not null := 10;
v_total_sal v_deptno%type := 0;
v_mgr v_deptno%type DEFAULT 100;
c_comm CONSTANT emp.comm%type := 1400;
v_hire_date emp.hiredate%type := TO_CHAR('1998/08/16', 'yyyy/mm/dd');

4. Use TableName%rowtype
4.1 Decalre only one variable that store the value for all row in the table
4.2 you can print the whole row value or print a specific values only
Declare
Emp_Row Emp%RowType;
begin
DBMS_OUTPUT.PUT_LINE (Emp_Row.Empno);
DBMS_OUTPUT.PUT_LINE (Emp_Row.Ename);
DBMS_OUTPUT.PUT_LINE (Emp_Row.Salary);
End;

Oracle Complete PLSQL Reference 6


5. Use recod data type
5.1 create an object of record data type
5.2 create a variable based on that object type
Declare
TYPE emp_record_type IS RECORD
(employee_id NUMBER(6) NOT NULL := 100,
last_name employees.last_name%TYPE,
job_id employees.job_id%TYPE);
emp_record emp_record_type;

6. use table data type


Declare
Type Emp_Table is Table of EMP%RowType
Index by binary integer;
V_Emp Emp_table;

DBMS_OUTPUT.PUT_LINE:
1. PRINT command. is DBMS_OUTPUT.PUT_LINE. DBMS_OUTPUT is Oracle-supplied package, and
PUT_LINE is a procedure within that package.
2. Within a PL/SQL block, reference DBMS_OUTPUT.PUT_LINE and, in parentheses, specify the string
that you want to print to the screen. The package must first be enabled in your SQL*Plus session. To do
this, execute the SQL*Plus

SQL> SET SERVEROUTPUT ON command.

Oracle Complete PLSQL Reference 7


Anonymus Block Best Practices
1. How to write Insert Statement without Variables

2. How to write Insert Statement with Variables

Oracle Complete PLSQL Reference 8


3. How to write Update Statement without Variables

4. How to write Update Statement with Variables

Oracle Complete PLSQL Reference 9


5. How to write Delete Statement without Variables
It is not possible to write the select statement without variables because varaibles are MANDATORY in this case .
Because the syntax for the SELECT statement is differe from the normal SELECT stamtent written by SQL
SELECT using SQL Syntac SELECT using PLSQL syntax
Select Select
INTO variabls ------- New
From table name From table name
Where Where
Group by Group by
Having Having
Order by Order by
Variables are decalred imlicitly by oracle Variables are decalred Explicitly by Developer
Values are printed implicitly by oralce Values are printed Explicitly by Developer

Oracle Complete PLSQL Reference 10


6. How to write Update Statement with Variables

You must declare variables with the same number of the columns that you retrieve in your select statement
1. Decalre variables for each column you retrive in select statement
2. Select column into variable
3. Print value for the variable by using DBMS_OUTPUT.PUT_LINE
4. you must enable DBMS_OUTPUT.PUT_LINE first by running command
5. SQL> set serveroutput on ;
6. DBMS_OUTPUT.PUT_LINE is used to pring value for one variable only .
7. If you print values for more that one variable then you can use Concat function or write
DBMS_OUTPUT.PUT_LINE more than one time for each varaible you want to pring

Oracle Complete PLSQL Reference 11


Oracle Complete PLSQL Reference 12
7. How to write more that DML transactions within the anonymus block

Oracle Complete PLSQL Reference 13


8. How to write more that DML transactions within the anonymus block

Oracle Complete PLSQL Reference 14


9. Using Subsutitution Variable By using wild card &

Oracle Complete PLSQL Reference 15


9.1 Using Subsutitution Variable By using wild card &

9.2 Using Subsutitution Variable By using wild card &

Oracle Complete PLSQL Reference 16


9.3 Using Subsutitution Variable By using wild card &

Oracle Complete PLSQL Reference 17


10 . Using ROW%TYPE as a datatype
1. it can be used when you retrieve all cloumns from the table
2. you can print all the values or just a specific values only

Oracle Complete PLSQL Reference 18


11 . Using RECORD%TYPE as a datatype

Oracle Complete PLSQL Reference 19


Subprogram = Program Unit
1. Stored Procedure
Parameters are optional not mandatory

Declaration Part
Optional

Body
Mandatory

Declaration Part
Optional

1. all Stored procedures created are stored in user_objects


2. source code is stored in user_source

Oracle Complete PLSQL Reference 20


1.1 procedure without parameters

Oracle Complete PLSQL Reference 21


1.1 procedure without parameters

1.1 procedure without parameters

Oracle Complete PLSQL Reference 22


1.1 procedure without parameters

Oracle Complete PLSQL Reference 23


1.1 procedure without parameters using TABLENAME%ROWTYPE as a datatype
Using ROW%TYPE as a datatype
1. it can be used when you retrieve all cloumns from the table
2. you can print all the values or just a specific values only

Oracle Complete PLSQL Reference 24


1.1 procedure without parameters using TABLENAME%ROWTYPE as a datatype
Using ROW%TYPE as a datatype

Oracle Complete PLSQL Reference 25


1.1 procedure without parameters using RECORD DATATYPE as a datatype
Using RECORD DATATYPE as a datatype

Oracle Complete PLSQL Reference 26


1.2 procedure with parameters
Parameter type are
1. IN Parameter ---- Default type
2. OUT Parameter
3. IN OUT Parameter
You can define more that one parameters in the same procedure
All parameters are defined after the procedure name

Oracle Complete PLSQL Reference 27


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 28


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 29


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 30


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 31


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 32


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 33


1.2 procedure with parameters -- IN parameter

1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 34


1.2 procedure with parameters -- IN parameter

Oracle Complete PLSQL Reference 35


1.2 procedure with parameters -- IN Parameter using TABLENAME%ROWTYPE as a datatype

Oracle Complete PLSQL Reference 36


1.2 procedure with parameters -- IN Parameter using TABLENAME%ROWTYPE as a datatype

1.2 procedure with parameters -- IN Parameter using RECORD DATATYPE as a datatype

Oracle Complete PLSQL Reference 37


Part 1 : PLSQL Course

Control Structure
There are three Type of Control Structure
1 IF Condition
2 Case Expression
3 Loop

Oracle Complete PLSQL Reference 38


IF Condition

Oracle Complete PLSQL Reference 39


IF Condition
There Are Three Types of IF Statement
1 IF Stamtement with ONLY one Conditon
Syntax IF Condition1 then Action1 ; END IF;

2 IF Stamtement with ONLY two Conditons


Syntax IF Condition1 then Action1 ;
ELSE Action2 ;
END IF;

3 IF Stamtement with MORE than two Conditons


Syntax IF Condition1 then Action1 ;
ELSIF Condition2 then Action2 ;
ELSIF Condition3 then Action3 ;
ELSIF Condition4 then Action4 ;
ELSE action 5;
END IF;

All conditions in IF statements are Boolean expressions that evaluate to true or false.
All Actions in IF Statements are PL/SQL statements
You can execute many actions as you like when the actions is TRUE

IF Stamtement with ONLY one Conditon

Oracle Complete PLSQL Reference 40


IF Stamtement with ONLY one Conditon

Oracle Complete PLSQL Reference 41


IF Stamtement with ONLY two Conditons

Oracle Complete PLSQL Reference 42


IF Stamtement with MORE than two Conditons

Oracle Complete PLSQL Reference 43


IF Stamtement with MORE than two Conditons

Oracle Complete PLSQL Reference 44


create or replace procedure rep1(p1 number)
is
vsal number(5);
v2 varchar2(20);
begin
select sal
into vsal
from emp
where empno = p1;
if LENGTH(vsal) < 6 then
v2 := to_char(vsal,'000000');
dbms_output.put_line(v2);
end if;
end;

Oracle Complete PLSQL Reference 45


CASE Expression

Oracle Complete PLSQL Reference 46


CASE Expression

Createorreplaceprocedurerep1(p1number)
Is
V_salnumber(5);
Begin
Selectsal
Intov_sal
Fromscott.Emp
Whereempno=p1;
v_sal:=CASEv_salWhennullthen50;
When<=1000thenv_sal+100;
When<=2000thenv_sal+200;
ELSEv_sal+300;
ENDCASE;
Updateemp
setsal=V_sal
whereempno=p1;
End;

Oracle Complete PLSQL Reference 47


Loop

Oracle Complete PLSQL Reference 48


Loop

What is Loop ?
It is a technique that can be used to run spefic code more that one time within the block

Why do you use Loop?


You may use a loop to run one or more statements multiple times

What are Loop types ?


1. Basic Loop Simple Loop
2. For loop
3. While Loop

In loop you must write a condition to exist the loop . If you didnt specify the condition the loop will
continue forever (infinity loop)

Basic Loop Simple Loop


A simple loop runs until you explicitly end the loop.

To end the loop, you use either an EXIT or EXIT WHEN statement.

The EXIT statement ends a loop immediately.

EXIT WHEN statement ends a loop when a specified condition occurs.

Basic Loop Syntax

Oracle Complete PLSQL Reference 49


Basic Loop

Oracle Complete PLSQL Reference 50


Basic Loop

Oracle Complete PLSQL Reference 51


Basic Loop

Basic Loop with IF condition

Oracle Complete PLSQL Reference 52


Basic Loop LABEL Loop

Basic Loop

Oracle Complete PLSQL Reference 53


Oracle Complete PLSQL Reference 54
Basic Loop

Oracle Complete PLSQL Reference 55


For Loop

A FOR loop runs a predetermined number of times.

You can use a variable directory in the body without declaring it in the declaration

Basic Loop Syntax

Where :

1. Loop_variable specifies the loop variable


2. REVERSE specifies that the loop variable value is to be decremented each time through the loop.

3. lower_bound specifies the loop's lower bound

4. upper_bound specifies the loop's upper bound

5. If REVERSE is used, the loop variable is initialized to this upper bound

6. The upper or lower bounds of the FOR loop can be defined as variables or functions.

Oracle Complete PLSQL Reference 56


For Loop

Oracle Complete PLSQL Reference 57


Oracle Complete PLSQL Reference 58
For Loop

Oracle Complete PLSQL Reference 59


Oracle Complete PLSQL Reference 60
For Loop

Oracle Complete PLSQL Reference 61


For Loop

Oracle Complete PLSQL Reference 62


For Loop

Oracle Complete PLSQL Reference 63


For Loop

Oracle Complete PLSQL Reference 64


Oracle Complete PLSQL Reference 65
Reversed For Loop with REVERSE Key Word

Oracle Complete PLSQL Reference 66


Oracle Complete PLSQL Reference 67
For Loop

Oracle Complete PLSQL Reference 68


For Loop

Oracle Complete PLSQL Reference 69


While Loop

Oracle Complete PLSQL Reference 70


While Loop

Oracle Complete PLSQL Reference 71


While Loop with Parameters

Oracle Complete PLSQL Reference 72


While Loop

Oracle Complete PLSQL Reference 73


While Loop

Oracle Complete PLSQL Reference 74


While Loop

Oracle Complete PLSQL Reference 75


Cursor

Explicit Cursor
Implicit Cursor
Reference Cursor

Cursor
Oracle Complete PLSQL Reference 76
Topics
Cursor
1. Introduction( 13 )
2. Cursor Declaration( 16 )
3. Cursor Open( 3 )
4. Fetch( 17 )
5. LOOP( 10 )
6. Close Cursor( 6 )
7. Cursor Status( 6 )
8. Implicit Cursor( 18 )
9. Explicit Cursor( 2 )
10. Cursor for Update( 5 )
11. Cursor Parameter( 4 )
12. ref cursor( 6 )
13. REFCURSOR( 9 )
14. Cursor Attributes( 9 )
15. refcursor( 3 )
16. Cursor function( 5 )

Q: What is Cursor?

1. Cursor is a space in the memory that can be used to store more than ONE record
2. cursor is basically a set of rows that you can access one at a time.
3. Cursor can accept parameters

Q: when do you use a Cursor?


You use a cursor when you have a SELECT statement that returns more than one row from the database.

Q: How do you use a Cursor?


1. Declare variables to store the column values from the SELECT statement. Declaration part
2. Declare the cursor , specifying your SELECT statement. Declaration part
3. Open the cursor. Body part
4. Fetch the rows from the cursor. Body part
5.Close the cursor. Body part

Q: what is the syntax for the cursor ?

Oracle Complete PLSQL Reference 77


Cursor
Q: How do you use a Cursor?
Open Execute the SELECT statement
Fetch 1. Read column values into the variables that you specify
2. you must use LOOP to Fetch more than one record
3. If you didnot use Loop with the cursor then the first record retreived by the
cursor will be retrieved ONLY
Close Frees up system resources

Q: what are the cursors type?


Explicit Curosr Declare Cursor then use open , fetch , close
Defined in the decalarion part as follows
Cursor <CursorNmae> is <SELECT statement> ;
Implicit Cursor Declare Cursor then use Loop
Defined in the body part with loop statement as follows
FOR I in <SELECT statement> Loop;
SQL%ROWCOUNT and SQL%BULK_ROWCOUNT
SQL%FOUND and SQl%NOTFOUND
Reference Coursor

Q: Functions with Cursor


<CursorName>%ISOPEN Return TRUE if the cursor is opend and Return FALSE if cursor is not opened
<CursorName>%FOUND 1. Return TRUE if the cursor retun row and Return FALSE if cursor didnt return row
2. MUST be used after the fetching of records
<CursorName>%NOTFOUND 1. Return TRUE if the cursor retun row and Return FALSE if cursor didnt
return row
2. MUST be used after the fetching of records
<CursorName>%ROWCOUNT 1. Retun number of record retrieved by cursor
2. MUST be used before closing the cursor

Values of %FOUND, %NOTFOUND, and %ROWCOUNT are changed after every fetch.
If you use the %FOUND, %NOTFOUND, and %ROWCOUNT cursor variables before the cursor is opened
or after the cursor is closed, they will raise an exception.

Oracle Complete PLSQL Reference 78


Cursor with NO Loop
If you didnt use Curosr with Loop then only the first record retried by cursor will be displayed

Cursor with Basic Loop

Oracle Complete PLSQL Reference 79


Cursor with Basic Loop to Fetch cursor till cursorName%NOTFOUND

Oracle Complete PLSQL Reference 80


Cursor with Basic Loop to Fetch cursor till cursorName%NOTFOUND

Oracle Complete PLSQL Reference 81


Cursor with For Loop

Cursor with While Loop

Oracle Complete PLSQL Reference 82


Cursor with While Loop to Fetch cursor till cursorName%NOTFOUND

Cursor for count

Oracle Complete PLSQL Reference 83


Cursor to reference whole table

<CursorName>%ISOPEN

<CursorName>%FOUND or <CursorName>%NOTFOUND
Oracle Complete PLSQL Reference 84
<CursorName>%ROWCOUNT

Oracle Complete PLSQL Reference 85


Cursor with Parameters

Oracle Complete PLSQL Reference 86


Cursor with Parameters

Oracle Complete PLSQL Reference 87


Cursor with Parameters

Cursor with Parameters

Oracle Complete PLSQL Reference 88


Implicit Cursor
Implicit cursor open, fetch and close
Open When you begin the body by writing BEGIN keyword
Fetch When you start the Loop statement by writing (basic loop , for loop , while Loop)
Close When you end the Loop statement by writing (end loop) key word

Explicit Cursor Declaraion

Oracle Complete PLSQL Reference 89


Implicit Cursor Declaration

Implicit Cursor

Oracle Complete PLSQL Reference 90


Implicit Cursor

Implicit cursors: SQL%ROWCOUNT returns number of rows affected by SQL statement

Oracle Complete PLSQL Reference 91


Implicit Cursor

Oracle Complete PLSQL Reference 92


Reference Cursor
The REF CURSOR datatype cannot be used outside a PL/SQL environment.
There are two kinds of REF CURSOR types:
1. weak
2. strong.
Weak Reference Cursor can point to any data set, as shown here:
Strong Reference Cursor Explicitly declares the type of data that can be referenced.

Weak Ref Cursor


1.
SQL> Declare
type weak_rcty is ref cursor;
c_weak rcty weak_rcty;

2.
declare
c_weak sys_refcursor

Strong Ref Cursor

declare
type strong_rcty is ref cursor return employee%ROWTYPE;
c_strong_rcty strong_rcty;

Oracle Complete PLSQL Reference 93


Weak Reference Cursor

Weak Reference Cursor

Oracle Complete PLSQL Reference 94


Weak Reference Cursor

Oracle Complete PLSQL Reference 95


Oracle Complete PLSQL Reference 96
Weak Reference Cursor

Oracle Complete PLSQL Reference 97


Exception Handling

Exception Handling & Handling PL/SQL Errors


Q: What is Exception?
In PL/SQL, the user can catch certain runtime errors.
Exceptions can be internally defined by Oracle or the user.
Q: What is Exception Handling?
1. Exceptions are used to handle errors that occur in your PL/SQL code.
2. you can use more than one EXCEPTION in the same Block
3. You could always code a NULL statement if no action is to be taken.
4. you can declare variables in the Exception handler
Oracle Complete PLSQL Reference 98
Q: What are the oracle Error Types?
There are three types of exceptions:
1. Predefined Oracle errors
2. Undefined Oracle errors
3. User-defined errors
Identifying Exception Types
Error Code Prefix Indicates This Exception Type of Error
ORA Core RDBMS errors
PLS PL/SQL errors
FRM Oracle Forms errors
REP Oracle Reports errors

Q: what are the Exception Types ?


1. Pre-defined Exception
2. Custom Exception

Q: what are the different parts of the exception?


The different parts of the exception.
1. Declare the exception.
2. Raise an exception.
3. Handle the exception.
An exception has four attributes:
1. Name provides a short description of the problem.
2. Type identifies the area of the error.
3. Exception Code gives a numeric representation of the exception.
4. Error message provides additional information about the exception.
The predefined divide-by-zero exception has the following values for the attributes:
1. Name = ZERO_DIVIDE
2. Type = ORA (from the Oracle engine)
3. Exception Code = C01476
4. Error message = divisor is equal to zero
How do you write EXCEPTION in the PLSQL BLOCK?

Pre-Defined Exceptions
Exception Oracle Error SQLCODE Value
NO_DATA_FOUND ORA-01403 Single SELECT statement returned no data
TOO_MANY_ROWS ORA-01422 Single SELECT statement returned more than one row of
data.
ZERO_DIVIDE ORA-01476 A program attempts to divide a number by zero.
VALUE_ERROR ORA-06502 An arithmetic, conversion, truncation, or
size-constraint error occurs.
For example, when your program selects a column value
Oracle Complete PLSQL Reference 99
into a character variable,
if the value is longer than the declared length
of the variable,
PL/SQL aborts the assignment and raises
VALUE_ERROR. In procedural statements,
VALUE_ERROR is raised if the conversion of a
character string into a number fails. (In SQL statements,
INVALID_NUMBER is raised.)
DUP_VAL_ON_INDEX ORA-00001 A program attempts to store duplicate values in a
database column that is constrained by a unique index.
INVALID_NUMBER ORA-01722 In a SQL statement, the conversion of a character string
into a number fails because the string does not
represent a valid number. (In procedural statements,
VALUE_ERROR is raised.) This exception is also raised
when the LIMIT-clause expression in a bulk FETCH
statement does not evaluate to a positive number.
ACCESS_INTO_NULL ORA-06530 A program attempts to assign values to the attributes of
an uninitialized object.
CASE_NOT_FOUND ORA-06592 None of the choices in the WHEN clauses of a CASE
statement is selected, and there is no ELSE clause.
COLLECTION_IS_NULL ORA-06531 A program attempts to apply collection methods other
than EXISTS to an uninitialized nested table or varray,
or the program attempts to assign values to the
elements of an uninitialized nested table or varray.
INVALID_CURSOR ORA-01001 A program attempts a cursor operation that is not
allowed, such as closing an unopened cursor.
LOGIN_DENIED ORA-01017 A program attempts to log on to Oracle with an invalid
username or password.
NOT_LOGGED_ON ORA-01012 A program issues a database call without being
connected to Oracle.
PROGRAM_ERROR ORA-06501 PL/SQL has an internal problem
SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 A program references a nested table or varray element
using an index number (-1 for example) that is outside
the legal range.
SYS_INVALID_ROWID ORA-01410 The conversion of a character string into a universal
rowid fails because the character string does not
represent a valid rowid.
TIMEOUT_ON_RESOURCE ORA-00051 A time-out occurs while Oracle is waiting for a resource

Pre-Defined Exceptions
Exception Oracle Error SQLCODE Value
SUBSCRIPT_BEYOND_COUNT ORA-06533 A program references a nested table or varray element
using an index number larger than the number of
elements in the collection.
ROWTYPE_MISMATCH ORA-06504 The host cursor variable and PL/SQL cursor variable
involved in an assignment have incompatible return
types. For example, when an open host cursor variable
Oracle Complete PLSQL Reference 100
is passed to a stored subprogram, the return types of
the actual and formal parameters must be compatible.
SELF_IS_NULL ORA-30625 A program attempts to call a MEMBER method, but the
Instance of the object type has not been initialized. The
built-in parameter SELF points to the object, and is
Always the first parameter passed to a MEMBER
method.
STORAGE_ERROR ORA-06500 PL/SQL runs out of memory or memory has been
Corrupted.
CURSOR_ALREADY_OPEN ORA-06511 A program attempts to open an already open cursor. A
Cursor must be closed before it can be reopened. A
cursor FOR loop automatically opens the cursor to
which it refers, so your program cannot open that
cursor inside the loop.
OTHERS 1. Any other error occurred.
2. You can use the OTHERS exception to handle all
exceptions
3. Because OTHERS handles all exceptions, you must
list it after any specific exceptions in your EXCEPTION
block.

Create the following Employee and Department tables to be used in the following exercises

when NO_DATA_FOUND then


Raised when Single SELECT statement returned no data

Oracle Complete PLSQL Reference 101


System Error

User Exception

When TOO_MANY_ROWS then


Raised when Single SELECT statement returned more than one row of data.

Oracle Complete PLSQL Reference 102

System Error
User Exception
when NO_DATA_FOUND & TOO_MANY_ROWS then

Oracle Complete PLSQL Reference 103


More than one Exception

when ZERO_DEVIDE then


Raised when an attempt is made to divide a number by zero.

System Error

User Exception

when DUP_VAL_ON_INDEX then


Raised when an attempt is made to store duplicate values in a column that is constrained by a unique index

System Error

Oracle Complete PLSQL Reference 104

System Error
User Exception
User Exception
when INVALID_NUMBER then
Raised when an attempt is made to convert an invalid character string into a number.

Oracle Complete PLSQL Reference 105

System Error
User Exception
when OTHERS then
You can use the OTHERS exception to handle all exceptions

System Error

User Exception

when OTHERS then

Oracle Complete PLSQL Reference 106 OTHERS Exception is not


the last one
when OTHERS then

User Exception

Declare Variables in the Exception Handler

Oracle Complete PLSQL Reference 107


Use more than one nested block in the main block

Use SQLCODE and SQLERRM Functions with Exceptions


SQLCODE Return Error code ot Error number for any Error
SQLERRM Return Error Message for any Error

Oracle Complete PLSQL Reference 108


User Defined Exception
1. Is a user defined exception that can be used instead of the pre-defined exception
2. user-defined exceptions must be declared and must be raised explicitly by RAISE statements.
3. Exceptions can be declared only in the declarative part of a PL/SQL block,
4. You declare an exception by introducing its name, followed by the keyword EXCEPTION

5. You cannot declare an exception twice in the same block

Oracle Complete PLSQL Reference 109


6. Exceptions declared in a block are considered local to that block and global to all its sub-blocks. Because a
block can reference only local or global exceptions, enclosingblocks cannot reference exceptions declared in a
sub-block

User Defined Exception

Oracle Complete PLSQL Reference 110


Defining Your Own Error Messages by using Procedure: RAISE_APPLICATION_ERROR
1.The procedure RAISE_APPLICATION_ERROR lets you issue user-defined ORA- error messages from stored
subprograms. That way, you can report errors to your application and avoid returning unhandled exceptions.
2. error_number is a negative integer in the range -20000 .. -20999 and message is a character string up to
2048bytes long

OUT Parameter

Oracle Complete PLSQL Reference 111


1. OUT parameter acts like a variable. You can change its value, and reference the value after assigning it:

2. can be bused when pass parameter values from one procedure to another procedure
2.1 OUT parameter returns a value to the caller of a subprogram.

3. You must pass a variable, not a constant or an expression, to an OUT parameter.

4. OUT formal parameters are initialized to NULL

OUT Parameter

Oracle Complete PLSQL Reference 112


IN OUT Parameter

Oracle Complete PLSQL Reference 113


Call procedure from another procedure

Call External Procedure named Rep1

Oracle Complete PLSQL Reference 114

Call External Proceure named Rep1


Call procedure from another procedure

Table Type

Oracle Complete PLSQL Reference 115


SQL> DECLARE
2 TYPE emp_table_struct IS TABLE OF emp.fname%TYPE INDEX BY BINARY_INTEGER;
3 emp_table emp_table_struct;
4 CURSOR emp_cursor IS SELECT fname FROM emp ORDER BY id;
5 v_row NUMBER := 1;
6 BEGIN
7 OPEN emp_cursor;
8 LOOP
9 FETCH emp_cursor INTO emp_table(v_row);
10 EXIT WHEN emp_cursor%NOTFOUND;
11 DBMS_OUTPUT.PUT_LINE(emp_table(v_row));
12 v_row := v_row + 1;
13 END LOOP;
14 CLOSE emp_cursor;
15 DBMS_OUTPUT.PUT_LINE('Total rows: '||emp_table.COUNT);
16 END;
17 /

DataBase Trigger

What is a mutating and constraining table?


"Mutating" means "changing". A mutating table is a table that is currently being modified by an update, delete, or insert
statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered "mutating" and
raises an error since Oracle should not return data that has not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign or unique key columns of the
table off which it fires. If you must have triggers on tables that have referential constraints, the workaround is to enforce the
referential integrity through triggers as well.
There are several restrictions in Oracle regarding triggers:
A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be accessed by the trigger) .
Oracle Complete PLSQL Reference 116
A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result

Is it better to put code in triggers or procedures? What is the difference?


In earlier releases of Oracle it was better to put as much code as possible in procedures rather than triggers. At that stage
procedures executed faster than triggers as triggers had to be re-compiled every time before executed (unless cached). In
more recent releases both triggers and procedures are compiled when created (stored p-code) and one can add as much
code as one likes in either procedures or triggers.

Functions

Q: What is Fincation?
A function is similar to a procedure except that a function must return a value.
Function can accept parameters or not

The simplified syntax for the CREATE FUNCTION statement is as follows:

CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN type
{IS | AS}
BEGIN
function_body
END function_name;
Oracle Complete PLSQL Reference 117
Function with no parameters

Function with parameters

Oracle Complete PLSQL Reference 118


Function with parameters
Function to calculate raise as 10% of the salary

Oracle Complete PLSQL Reference 119


Function to calculate raise as % of the salary

Oracle Complete PLSQL Reference 120


Function to calculate total as sal + comm

Oracle Complete PLSQL Reference 121


Function returns week No of the Month

Oracle Complete PLSQL Reference 122


Functions return name of a Month

Oracle Complete PLSQL Reference 123


Functions return Quartner No of the year

Oracle Complete PLSQL Reference 124


Functions return Julian Date
Julian date must be between 1 and 5373484

Functions return name of a specific date


Oracle Complete PLSQL Reference 125
Functions return username

Functions return sysdate

Functions return default nationality

Oracle Complete PLSQL Reference 126


Functions return Max salary

Position Notation calls for the parameters

Oracle Complete PLSQL Reference 127


Name Notation calls for the parameters

Mixed Name and position Notation calls for the parameters

Oracle Complete PLSQL Reference 128


Database Trigger

Oracle Complete PLSQL Reference 129


DataBase Trigger
Q: what is a Trigger ?
It is a PLSQL Block that is associated with specific table, view, schema, Database and fire implecitly when
a specific event occure

Q: what are the triggers Types?


1. DataBase Trigger Fire When specific Database event Occurs (Database)
2. Application Trigger Fire When specific Event Occurs With Particular Application (Forms, report)

Q: what are the objects that the DB trigger associate with ?


1. Table 2. View 3. schema 4. Database

Q: what is the structur of the Trigger Code?


Part 1 Trigger Timing After Before (Tables) Instead of(View)
Mandatory
Part 2 Trigger Event 1. DB Event 1. DML Trigger
Mandatory Insert , update , update of <column > , delete
2. System Event Create , alter , drop , Logon , logoff ,
shutdown,startup,servererror
Part 3 Trigger Type For each row 1. The trigger body executes once for each row affected by
Optinal the trigger event.

2. use :NEW , :OLD functions


For Each Statement 1. The trigger body executed for each bulk of rows affected
[Default] by the trigger event .

2. NOT use :NEW , :OLD functions


Part 4 Trigger When <Condition> If you want to restirct a specific condition
Optional Condition
Part 5 Trigger Action The actions that the trigger will execute when the event
Mandatory occur

Trigger Syntax

Oracle Complete PLSQL Reference 130


Oracle Complete PLSQL Reference 131
Oracle Complete PLSQL Reference 132
Oracle Complete PLSQL Reference 133
DDL Triggers Events Avaliable Functions
BEFORE / AFTER ALTER 1. ora_sysevent

Oracle Complete PLSQL Reference 134


BEFORE / AFTER CREATE 2. ora_client_ip_address
3. Ora_database_name
BEFORE / AFTER DROP
4. ora_des_encrypted_password
BEFORE / AFTER RENAME 5. ora_dict_obj_name
6. ora_dict_obj_name_list
BEFORE / AFTER ANALYZE
7. ora_dict_obj_owner
BEFORE / AFTER ASSOCIATE 8. ora_dict_obj_type
9. ora_grantee
STATISTICS
10. ora_instance_num
BEFORE / AFTER DISASSOCIATE 11. ora_is_alter_column
12. ora_is_creating_nested_table
STATISTICS
13. ora_is_drop_column
BEFORE / AFTER AUDIT 14. ora_is_servererror
15. ora_login_user
BEFORE / AFTER NOAUDIT
16. ora_partition_pos
BEFORE / AFTER COMMENT 17. ora_privilege_list
18. ora_revokee
BEFORE / AFTER DDL
19. ora_server_error
BEFORE / AFTER GRANT 20. ora_server_error_depth
21. ora_server_error_msg
BEFORE / AFTER REVOKE
22. ora_server_error_num_params
BEFORE / AFTER TRUNCATE 23. ora_server_error_param
24. ora_sql_txt
AFTER SUSPEND
25. ora_with_grant_option
26. space_error_info

Oracle Complete PLSQL Reference 135


What is a mutating and constraining table?
"Mutating" means "changing". A mutating table is a table that

is currently being modified by an update, delete, or insert


statement. When a trigger tries to reference a table that is
in state of flux (being changed), it is considered "mutating"
and raises an error since Oracle should not return data that
has not yet reached its final state.
Another way this error can occur is if the trigger has
statements to change the primary, foreign or unique key
columns of the table off which it fires. If you must have
triggers on tables that have referential constraints, the
workaround is to enforce the referential integrity through
triggers as well.
There are several restrictions in Oracle regarding triggers:
A row-level trigger cannot query or modify a mutating table.
(Of course, NEW and OLD still can be accessed by the trigger)
.
A statement-level trigger cannot query or modify a mutating
table if the trigger is fired as the result

Is it better to put code in triggers or procedures? What is the difference?


In earlier releases of Oracle it was better to put as much
code as possible in procedures rather than triggers. At that
stage procedures executed faster than triggers as triggers
had to be re-compiled every time before executed (unless
cached). In more recent releases both triggers and procedures
are compiled when created (stored p-code) and one

Oracle Complete PLSQL Reference 136


create table company
(product_id number(4) not null,
company_id NUMBER(8) not null,
company_short_name varchar2(30) not null,
company_long_name varchar2(60) );

insert into company values(1,1001,'A Inc.','Long Name A Inc.');


insert into company values(1,1002,'B Inc.','Long Name B Inc.');
insert into company values(1,1003,'C Inc.','Long Name C Inc.');
insert into company values(2,1004,'D Inc.','Long Name D Inc.');
insert into company values(2,1005,'E Inc.','Long Name E Inc.');
insert into company values(2,1006,'F Inc.','Long Name F Inc.');

create table product_audit


(product_id number(4) not null,
num_rows number(8) not null );

CREATE OR REPLACE TRIGGER myTrigger


AFTER INSERT ON company
FOR EACH ROW
DECLARE
BEGIN
UPDATE product_audit
SET num_rows =num_rows+1
WHERE product_id =:NEW.product_id;
IF (SQL%NOTFOUND) THEN
INSERT INTO product_audit VALUES (:NEW.product_id,1);
END IF;
END;
/

insert into company values(3,1007,'E Inc.','Long Name E Inc.');

Oracle Complete PLSQL Reference 137


Examples
SQL>createtableemplpyee
(empnonumber(5),namechar(10),salnumber(5),commnumber(5),totalnumber(5))

SQL>CreateorreplacetriggerTri1
Afterupdateofsal,commonemp
Foreachrow
Begin
Updateemp
Settotal=sal+comm
Wheresal=:new.salorcomm=:new.comm;
End;

SQL>insertintoevalues(1,'ali',100,200,null);
SQL>insertintoevalues(2,'mona',200,300,null);
SQL>commit;

SQL>updateesetsal=300whereid=1;

ERRORatline1:
ORA04091:tableSCOTT.Eismutating,trigger/functionmaynotseeit
ORA06512:at"SCOTT.TRI1",line2
ORA04088:errorduringexecutionoftrigger'SCOTT.TRI1'
ErrorCalrification
INOracleyoucanntinsrtintotableXandruntriggertoupdatethesametable
Butyoucanrunthetriggertoupdateanothertablebbecauseitisrelatedtointernal
constraintthatviolatethisissue

Oracle Complete PLSQL Reference 138


Instead OF Trigger
Use instead of trigger when you want to insert or update or
delete on unupdatable View (Read Only View) because the instead
of trigger works invisibly on the underlying table
Name Null? Type
----------------------------------------- -------- -------------------------
DEPTNO NOT NULL NUMBER(5) Primary Key
DNAME CHAR(20)
LOC CHAR(20)

Name Null? Type


----------------------------------------- -------- -------------------------
EMPNO NOT NULL NUMBER(5)
ENAME CHAR(20)
SAL NUMBER(5)
DEPTNO NUMBER(5) References d:deptno

Oracle Complete PLSQL Reference 139


Create or replace view v
As select e.empno , e.ename , e.sal , e.deptno , d.deptno as
deptatmentID , d.dname , d.loc
From e e , d d
Where e.deptno = d.deptno

Create or replace trigger Tri1


Instead of insert on v
For each row
Begin
Insert into d Values(:new.deptno , :new.dname ,:new.loc);
Insert into E Values(:new.empno , :new.ename ,:new.sal ,:new.deptno);
End;

Insert into v
Values(1,ahmed,100,1,1,sales,cairo);

You must insert data into view in the same sequence for that view columns

Q: How do I Enable and Disable the Trigger


SQL> Alter trigger <Trigger_name> Disable|Enable

Q: How do I Enable and Disable all trigger for a table


SQL> Alter table <Table_name> Disable|Enable

Q: How do I Compile the trigger


SQL> Alter Trigger <Trigger_name> compile

Q: How do I drop the trigger


SQL> drop Trigger <Trigger_name>

Oracle Complete PLSQL Reference 140


System Triggers
1. DDL Trigers
http://www.psoug.org/reference/ddl_trigger.html

DDL Triggers Events Avaliable Functions


BEFORE / AFTER ALTER 27. ora_sysevent
28. ora_client_ip_address
BEFORE / AFTER CREATE
29. Ora_database_name
BEFORE / AFTER DROP 30. ora_des_encrypted_password
31. ora_dict_obj_name
BEFORE / AFTER RENAME
32. ora_dict_obj_name_list
BEFORE / AFTER ANALYZE 33. ora_dict_obj_owner
34. ora_dict_obj_type
BEFORE / AFTER ASSOCIATE
35. ora_grantee
STATISTICS 36. ora_instance_num
37. ora_is_alter_column
BEFORE / AFTER DISASSOCIATE
38. ora_is_creating_nested_table
STATISTICS 39. ora_is_drop_column
40. ora_is_servererror
BEFORE / AFTER AUDIT
41. ora_login_user
BEFORE / AFTER NOAUDIT 42. ora_partition_pos
43. ora_privilege_list
BEFORE / AFTER COMMENT
44. ora_revokee
BEFORE / AFTER DDL 45. ora_server_error
46. ora_server_error_depth
BEFORE / AFTER GRANT
47. ora_server_error_msg
BEFORE / AFTER REVOKE 48. ora_server_error_num_params
49. ora_server_error_param
BEFORE / AFTER TRUNCATE
50. ora_sql_txt
AFTER SUSPEND 51. ora_with_grant_option
52. space_error_info

Oracle Complete PLSQL Reference 141


Example No:10
Create Table tets_DDL
(server_Event varchar2(50),
object_owner varchar2(50),
object_name varchar2(50),
user_name varchar2(50),
system_date date)
CREATE OR REPLACE TRIGGER test_DDL
BEFORE CREATE or ALTER or DROP ON SCHEMA
BEGIN
INSERT INTO tets_ddl
SELECT ora_sysevent, ora_dict_obj_owner, ora_dict_obj_name, USER, SYSDATE
FROM dual;
END;

Example No:11
Conn sys/password@<service_name> as sysdba;
Create table ddl_log
(server_event char(40),
owner char(20),
objectname char(20),
text varchar(200),
username char(20),
transaction_date date);

CREATE OR REPLACE TRIGGER ddl_trigger


BEFORE CREATE OR ALTER OR DROP ON SCHEMA
DECLARE
oper varchar2(50);
BEGIN
SELECT ora_sysevent
INTO oper
FROM dual;
IF oper IN ('CREATE', 'DROP') THEN
INSERT INTO ddl_log
SELECT ora_sysevent, ora_dict_obj_owner, ora_dict_obj_name, NULL, USER, SYSDATE
FROM dual;
ELSIF oper = 'ALTER' THEN
INSERT INTO ddl_log
SELECT ora_sysevent, ora_dict_obj_owner,ora_dict_obj_name, sql_text, USER, SYSDATE
FROM sys.gv$open_cursor
WHERE UPPER(sql_text) LIKE 'ALTER%';
END IF;
END;

Oracle Complete PLSQL Reference 142


CREATE OR REPLACE TRIGGER save_our_db
BEFORE DROP OR TRUNCATE ON SCHEMA
DECLARE
oper varcha2(20);
BEGIN
SELECT ora_sysevent
INTO oper
FROM dual;
IF oper = 'DROP' THEN
RAISE_APPLICATION_ERROR(-20998, 'Attempt To Drop In Production Has Been Logged');
ELSIF oper = 'TRUNCATE' THEN
RAISE_APPLICATION_ERROR(-20999, 'Attempt To Truncate A Production Table Has Been Logged');
END IF;
END;

DDL Trigger To Prevent Creating Objects That Whose Names


Begin With The Letter 'X'
CREATE OR REPLACE TRIGGER no_xtabs
BEFORE CREATE ON SCHEMA
DECLARE
x user_tables.table_name%TYPE;
BEGIN
SELECT ora_dict_obj_name
INTO x
FROM dual;
IF SUBSTR(x, 1, 1) = 'X' THEN
RAISE_APPLICATION_ERROR(-20099, 'Table Names Can Not Start With The Letter X');
END IF;
END;
/

Oracle Complete PLSQL Reference 143


2. System Triggers
http://www.psoug.org/reference/system_trigger.html
AFTER LOGON
AFTER STARTUP
System Event Trigger Types BEFORE LOGOFF
BEFORE SHUTDOWN
AFTER SERVERERROR (does not trap

CREATE TABLE connection_audit


(login_date DATE,
username VARCHAR2(30));
CREATE OR REPLACE TRIGGER logon_audit
AFTER LOGON on database
BEGIN
INSERT INTO connection_audit(login_date, username)
VALUES (SYSDATE, USER);
END;

CREATE TABLE log_logons (sqltext VARCHAR2(25) NOT NULL);

CREATE OR REPLACE PROCEDURE logproc


Is
Begin
INSERT INTO log_logons(sqltext)
VALUES(user || ' - ' || TO_CHAR(SYSDATE)|| ' - '||'Logged On' );
End;

CREATE OR REPLACE TRIGGER logintrig


AFTER LOGON ON DATABASE
CALL logproc

Oracle Complete PLSQL Reference 144


Create table ip
(ip_add char(20),
user_name char(20),
logon_user char(20),
I want to display all object names that has been altered
db_name char(20),
instance_no number(5),

create table w
logon_date date);

(username char(20),
CREATE OR REPLACE TRIGGER ip_trace
AFTER LOGON ON DATABASE

object_name varchar2(255));
BEGIN
IF (ora_sysevent=LOGON) THEN
CREATE
INSERT INTO IP OR REPLACE TRIGGER sysevent_trig
VALUES(ora_client_ip_address,user,ora_login_user,Ora_database_name,ora_instance_num,sysdate);

AFTER
END IF; ALTER ON SCHEMA
END;

BEGIN
INSERT INTO w VALUES(user,ora_dict_obj_name);
END ;

Oracle Complete PLSQL Reference 145


alter table dept
add constraint a check (dname is not null);
alter user scott identified by scott;

I want to display descripted password for the altered user

create table encpassword


(username char(20),
enc_user char(255),
encpassword varchar2(255));

CREATE OR REPLACE TRIGGER sysevent_trig


AFTER ALTER ON DATABASE
BEGIN
INSERT INTO encpassword
VALUES(user,ora_dict_obj_name,ora_des_encrypted_password);
END;

Alter user scott identifiec by abc;


Select * from encpassword

Oracle Complete PLSQL Reference 146


Server Error Trigger

SQL > create table caught_errors


(dt date,
username varchar2( 30),
msg varchar2(512),
stmt varchar2(512));

create or replace trigger catch_errors


After servererror on database
Declare
sql_text ora_name_list_t;
msg_ varchar2(2000) := null;
stmt_ varchar2(2000) := null;
begin
for depth in 1 .. ora_server_error_depth loop
msg_ := msg_ || ora_server_error_msg(depth);
End loop;
For i in 1 .. ora_sql_txt(sql_text) loop
stmt_ := stmt_ || sql_text(i);
End loop;
Insert into caught_errors (dt,username,msg ,stmt )values (sysdate,ora_login_user,msg_,stmt_);
end;

Trigger Privelages

create trigger
create any trigger
administer database trigger -- required
System Privileges
for ON DATABASE
alter any trigger
drop any trigger

Oracle Complete PLSQL Reference 147


Triggers Data Dictionary

dba_triggers all_triggers user_triggers

You Can Enable And Disable Any Trigger According To the following Codes

Oracle Complete PLSQL Reference 148


Function

Oracle Complete PLSQL Reference 149


1.
create or replace function emp_count
return number
is
cnt number(2) := 0;
begin
select count(*) into cnt
from emp ;
return (cnt);
end;
/

2.
create or replace function emp_count (p_deptno in number)
return number
is
cnt number(2) := 0;
begin
select count(*) into cnt
from emp
where deptno = p_deptno ;
return (cnt);
end;
/

3.

update emp set comm = sal where deptno = 10 ;


commit;

create or replace function fun1 (p1 number , p2 number)


return number
is
begin
if p1 = p2 then
return (0);
else
return (1);
end if;
end;
/

4.
select ename , sal , sal*0.10 as raise
from emp;

Create or replace function raise10(p_sal number)


Return number
Is
Begin
Return (p_sal * 0.10);
Oracle Complete PLSQL Reference 150
End;

Create or replace function raise(p_sal number ,p_percentage number )


Return number
Is
Begin
Return (p_sal * p_percentage);
End;

5.
select ename , sal , comm, nvl(sal,0)+nvl(comm,0) as total
from emp;

Create or replace function total (p_sal number , p_comm number)


return number
is
Begin
return (nvl(p_sal,0)+nvl(p_comm,0));
End;

6.
select ename , hiredate , TO_CHAR(hiredate,'W')
from emp;

Create or replace function week_month(p_date IN date)


RETURN NUMBER
IS
BEGIN
RETURN ( TO_NUMBER( TO_CHAR( p_date, 'W' ) ) );
END;

7.
select ename, hiredate , TO_CHAR(hiredate, 'fmMonth') as Month_name
from emp;

Create or replace function Month_Name ( p_date IN DATE )


RETURN VARCHAR2
IS
BEGIN
RETURN ( TO_CHAR( p_date, 'fmMonth' ) );
END Month_Name;

8.
select ename , hiredate , TO_CHAR( hiredate, 'Q' )
from emp
where deptno = 10 ;

Oracle Complete PLSQL Reference 151


Create or replace function quarter( p_date IN DATE )
RETURN NUMBER
IS
BEGIN
RETURN ( TO_NUMBER( TO_CHAR( p_date, 'Q' ) ) );
END;

9- Function that return julian date from date

select hiredate , TO_CHAR(hiredate, 'J' )


from emp
where deptno = 10 ;

Create or replace function julianfromdate(p_date IN date)


RETURN NUMBER
IS
BEGIN
RETURN (TO_NUMBER(TO_CHAR( p_date, 'J' ) ) );
END;

10- function that return date form julian

Create or replace function datefromjulian(p_num IN NUMBER )


RETURN DATE
IS
BEGIN
IF p_num BETWEEN 1 and 5373484 THEN
RETURN (TO_DATE(TRUNC(p_num ),'J'));
ELSE
RAISE_APPLICATION_ERROR (-01854, 'Julian date must be between 1 and 5373484');
END IF;
END;

11- Function that return dayname

select ename ,hiredate , TO_CHAR( hiredate, 'fmDay')


from emp
where deptno = 10 ;

Create or replace function dayname ( p_date IN DATE )


RETURN VARCHAR2
IS
BEGIN
RETURN ( TO_CHAR( p_date, 'fmDay' ) );
END;

12.
Create Or Replace Function username
RETURN VARCHAR2
IS
BEGIN
Oracle Complete PLSQL Reference 152
RETURN user;
END;

13. Function that return current date = sysdate


select sysdate from dual;

Create Or Replace Function current_date


RETURN date
IS
BEGIN
RETURN sysdate;
END;

14- Function that default value for nationality column


create table employee (name char(4),nationality varchar2(20));

Create Or Replace Function default_nationality


RETURN varchar2
IS
BEGIN
RETURN egyptian;
END;

Insert into employee


Values('ali', default_nationality);

15- Function that return max_sal_emp


select max(sal) from emp;

Create Or Replace Function max_sal_emp


RETURN number
IS
v_max_sal number(5);
BEGIN
Select max(sal)
Into v_max_sal
From emp;
RETURN v_max_sal;
END;

16- Function that return statistic

select max(sal) , min(sal) , avg(sal) , sum(sal)


from emp;

Create Or Replace Function Max_Min_Avg_Sum


RETURN varchar2
IS
v_max_sal number(5);
v_min_sal number(5);
Oracle Complete PLSQL Reference 153
v_avg_sal number(5);
v_sum_sal number(5);
BEGIN
Select max(sal) , min(sal), avg(sal) , sum(sal)
Into v_max_sal , v_min_sal , v_avg_sal , v_sum_sal
From emp;
RETURN (to_char(v_max_sal) || '-' || to_char(v_min_sal) || '-' || to_char(v_avg_sal) || '-' || to_char(v_sum_sal));
END;

17.
CREATE OR REPLACE FUNCTION add_three_numbers( a NUMBER := 0, b NUMBER := 0, c NUMBER := 0
)
RETURN NUMBER
IS
BEGIN
RETURN a + b + c;
END;
/
BEGIN
dbms_output.put_line(add_three_numbers(3,4,5));
END;
/

18.
CREATE OR REPLACE FUNCTION add_three_numbers( a NUMBER := 0, b NUMBER := 0, c NUMBER := 0
)
RETURN NUMBER
IS
BEGIN
RETURN a + b + c;
END;
/

BEGIN
dbms_output.put_line(add_three_numbers(a => 4,b => 5,c => 3));
END;

19.
CREATE OR REPLACE FUNCTION add_three_numbers( a NUMBER := 0, b NUMBER := 0, c NUMBER := 0
)
RETURN NUMBER
IS
BEGIN
RETURN a + b + c;
END;
/

BEGIN
dbms_output.put_line(add_three_numbers(a => 4,b => 5,c => 3));
END;

Oracle Complete PLSQL Reference 154


Package

Oracle Complete PLSQL Reference 155


createtabledd
(deptnonumber(5),deptnamevarchar2(30),deptlocvarchar2(5));

createsequencesqdept
startwith1
incrementby1;

CREATEorreplacepackageover_pack
IS/AS

Procedureadd_dept(dnonumber,dnamevarchar2,dlocvarchar2);

Procedureadd_dept(dnamevarchar2,dlocvarchar2);

End;
/
CREATEorreplacepackageBODYover_pack
Is

Procedureadd_dept(dnonumber,dnamevarchar2,dlocvarchar2)
Is
Begin
Insertintoddvalues(dno,dname,dloc);
End;

Procedureadd_dept(dnamevarchar2,dlocvarchar2)
Is
Begin
Insertintoddvalues(sqdept.nextval,dname,dloc);
End;

End;
/

execover_pack.add_dept(design,cairo);

execover_pack.add_dept(1,sales,alex);

Oracle Complete PLSQL Reference 156


CREATEorreplacepackageover_pack
Is
functiontotal(v_salnumber,v_commnumber)returnnumber;
functionmax_sal_empreturnnumber;
End;

CREATEorreplacepackagebodyover_pack
Is
functiontotal(v_salnumber,v_commnumber)
returnnumber
is
Begin
return(nvl(v_sal,0)+nvl(v_comm,0));
End;
Functionmax_sal_emp
RETURNnumber
IS
v_max_salnumber(5);
BEGIN
Selectmax(sal)
Intov_max_sal
Fromemp;
RETURN(v_max_sal);
END;
End;
/

selectsal,comm,over_pack.total(sal,comm)
fromemp;

selectover_pack.max_sal_emp
fromdual;

Oracle Complete PLSQL Reference 157


Oracle Complete PLSQL Reference 158
Oracle Complete PLSQL Reference 159
System Package

Oracle Complete PLSQL Reference 160


Oracle Complete PLSQL Reference 161
DBMS_ALERT( 6 ) dbms_application_info( 4 ) DBMS_AQADM( 3 ) dbms_crypto( 8 ) DBMS_DB( 1 ) dbms_ddl( 1 )
DBMS_DEBUG( 1 ) DBMS_FGA( 1 ) DBMS_FILE_TRANSFER( 1 ) dbms_flashback( 3 ) dbms_job( 8 ) dbms_lob( 17 )
dbms_lock( 1 ) DBMS_METADATA( 2 ) DBMS_OBFUSCATION_TOOLKIT( 6 ) dbms_output( 16 ) DBMS_PIPE( 13 ) DBMS_RANDOM( 12 )
DBMS_REDEFINITION( 1 ) DBMS_REPAIR( 4 ) dbms_rowid( 7 ) dbms_scheduler( 1 ) DBMS_SESSION( 1 ) dbms_space( 1 )
dbms_sql( 27 ) dbms_stats( 12 ) DBMS_TRACE( 2 ) dbms_utility( 15 ) DBMS_WARNING( 2 ) dbms_xmlquery( 1 )
dbms_xmlschema( 2 ) htp( 1 ) ORA Error( 13 ) ORA( 18 ) outln_pkg( 1 ) TEXT_IO( 1 )
UTL_COMPRESS( 1 ) UTL_FILE( 9 ) UTL_HTTP( 1 ) utl_i18n( 1 ) UTL_INADDR( 1 ) UTL_MAIL( 1 )
utl_raw( 27 ) UTL_SMTP( 1 ) UTL_TCP( 1 )

Oracle Complete PLSQL Reference 162


Implicit Cursor
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/sqlnotfound.htm

http://www.java2s.com/Tutorial/Oracle/0500__Cursor/UsingSELECTinaCursor.htm
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Cursorforobjecttable.htm
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Cursorwithorderby.htm
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Cursorforaggregatefunction.htm
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/FetchingAcrossCommitsExample2.htm
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/CursorFORLoop.htm
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Closecursorinexcpetionhandler.htm
SQL>Createorreplaceprocedurea
Is
CursorEmp_Rec_Curisselectename,deptnofromemp;
Begin
foriinemp_rec_curloopimplicitopenandimplicitFetch
ifi.deptno=20then
dbms_output.put_line(i.ename||''||i.deptno);
endif;
endloop;implicitcloseandimplicitloopExit
end;

theprviousexampleisequaltonextexample

SQL>Createorreplaceprocedurea
Is
Begin
foriin(selectename,deptnofromemp)loopimplicitopenandimplicitFetch
ifi.deptno=20then
dbms_output.put_line(i.ename||''||i.deptno);
endif;
endloop;
implicitcloseandimplicitloopExit
end;

SQL%ROWCOUNT and SQL%BULK_ROWCOUNT


http://www.java2s.com/Tutorial/Oracle/0500__Cursor/usingSQLBULKROWCOUNTandSQLROWCOUNT.htm

Use cursor subquery


http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Usethecursorsubquery.htm

Nested Cursor
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Nestedcursor.htm

VARRAY of Cursor
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/VARRAYofCursor.htm

Assigning different queries to the same cursor variable Ref Cursor


http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Assigningdifferentqueriestothesamecursorvariable.htm
Oracle Complete PLSQL Reference 163
Execute immediate statement
BEGIN
FOR i IN (SELECT table_name
FROM user_tables
WHERE table_name = 'DEPT2' ) LOOP
;'EXECUTE IMMEDIATE 'DROP TABLE dummy 6
7
;END LOOP 8
9
10 END;
http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Returninformationusingcursorstatusvariables.htm
Can one use dynamic SQL statements from PL/SQL?
Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL
statements (statements created at run-time). Look at these examples. Note that statements are NOT terminated by
semicolons:
EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)';
-- Using bind variables...
sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';
EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;
-- Returning a cursor...
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these
examples:
CREATE OR REPLACE PROCEDURE DYNSQL
AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
More complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x',
DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
Oracle Complete PLSQL Reference 164
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||
sqlerrm);
END;
/
Back to top of file

Execute procedure
1. exec rep1;
2. exec rep1()p1,p2,p3,;
3. call rep1();
4. call rep1(p1,p2,p3,.);

Triggers

Oracle Complete PLSQL Reference 165


Table data type

http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Createandusereferencecursor.htm

http://www.java2s.com/Tutorial/Oracle/0500__Cursor/Referencevalueinacursorbycursorvariable.htm

Function

http://www.java2s.com/Tutorial/Oracle/0480__PL-SQL-
Programming/CodewithConditionalControltoAvoidanException.htm

http://www.java2s.com/Tutorial/Oracle/0480__PL-SQL-
Programming/CodewithExplicitHandlerforPredefinedException.htm

http://www.java2s.com/Tutorial/Oracle/0480__PL-SQL-
Programming/Handlingexceptionswithouthaltingtheprogram.htm

IN OUT PARAMETER

http://www.java2s.com/Tutorial/Oracle/0500__Cursor/TheuseofREFCURSOR.htm

http://www.java2s.com/Tutorial/Oracle/0500__Cursor/OpenSYSREFCURSORforselectfrom.htm

http://www.java2s.com/Tutorial/Oracle/0500__Cursor/SYSREFCURSORtypeparameter.htm

Oracle Complete PLSQL Reference 166


While Loop

http://www.java2s.com/Tutorial/Oracle/0440__PL-SQL-Statements/ReversedFORLOOP.htm
http://www.adp-gmbh.ch/ora/plsql/loops.html

https://support.us.oracle.com/oip/faces/secure/srm/sr/SRQueue.jspx?mc=true

https://login.oracle.com/mysso/signon.jsp?
site2pstoretoken=v1.2~97B77393~56D799A0127BA50DC728218D093398C3E7DC7FBF437396E2
DF8C88659E2568533223ED388A5A74C7CE50A6B563DA6224E2FE03819119B6DD1568AE6C9280
AB2EDCDECBBDD876929B5A9F5D0C72951FDCE134763C3783B3DFACB6CED8B35EA6CC1CF29A9
2BAA0E40C94B0B59C78A8AA97086082846113AC3E082477225EF2359275DE1F014672AC086F85
A66620BFBDAB778B2E5A6D04E0641CF70781A264F3C9EE35CFEC74333D63B3570160E466D4390
A005E5988628900&p_error_code=&p_submit_url=https%3A%2F%2Flogin.oracle.com%2Fsso
%2Fauth&p_cancel_url=http%3A%2F%2Fgcca.oraclecorp.com
=%2Fcca&ssousername=&subscribername

https://login.oracle.com/mysso/signon.jsp?
site2pstoretoken=v1.2~B483CC4E~8A17DE85F48237269E6D418A2D3B532BF6B825EBC625C51F
D063482AE69E7EB1B7E38AEF36FA299222FB6EB1EE7E34B0DC424060688F88C2241F59A23D04F
3E37FE9AD514E1C692B8BD63EA50EB5A6510493DD38C1E272779A451A13D05CB235AD10FE3A1
1658C15E94EE612F4B74D190699D28ACAE02CA2213BB826001290456A80A25F7EE2D6C99261B0
5A83CD01EAB5FEE046D837278283E8C3F7E28198BAA653F3C73A6FFC6B39B19ACD78D5EDAC9C
E0C22B7B5F17349A1312F92CB33D4C25CE5C83F0768185C830F3F292E87C413AC60A0775EF16C
324913DCBF1A7F1A9D25E779E5B91F1350602B1F083E5812CDA7B4A2BD87D6317&p_error_code
=&p_submit_url=https%3A%2F%2Flogin.oracle.com%2Fsso%2Fauth&p_cancel_url=https%3A%2F
=%2Fsupport.us.oracle.com%2Foip&ssousername=&subscribername

https://login.oracle.com/mysso/signon.jsp?
site2pstoretoken=v1.2~B483CC4E~23E6FB45EB4FE6929831F3A33F813893C1D08307A3F8A92A
A3484C34FF3229B41916D02D6C8610D11A20FCE7DF40F64B70506A05058A71C3E56EE66E25DBC
CD6B8834A62BB8CD4371A40D66106E03A166297BAD9E86E8A419F45FCD1CDB2278BB4E534703
9AED42D290AD988AC97C5977896884568F4C86E545344B0079CAB3DA03435F70B45D1D2DD73C
B25930116BFC56B8EDDC9863698C3465FE67D524D229537AAFBF483E0CC33D838D654E6D4748
356753D3EF371FECA7F8B482995D61F8430328F872CE9E6DAC0580B0A73C727699C7F402C9526
09B21A3263A306C1E4DE7CE0A56893155771D173674350EE77&p_error_code=&p_submit_url=htt
ps%3A%2F%2Flogin.oracle.com%2Fsso%2Fauth&p_cancel_url=https%3A%2F
=%2Fsupport.us.oracle.com%2Foip&ssousername=&subscribername

Oracle Complete PLSQL Reference 167


part 2

REATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS


BEGIN
-- do something with TabX from database B
null;
END;

Oracle Complete PLSQL Reference 168


Oracle Supplied Packages

Thes packages are got from the following URL

http://www.ss64.com/orap/

Packagesmarked*arenewin9.2

PackageDescription

DBMS_ALERTNotifyadatabaseevent(asynchronous)

DBMS_APPLICATION_INFO
Registeranapplicationnamewiththedatabase
forauditingorperformancetracking.
Applicationinfocanbepushedinto
V$SESSION/V$SESSION_LONGOPS

DBMS_AQAddamessage(ofapredefinedobjecttype)ontoaqueue
ordequeueamessage.

DBMS_AQADMAdministeraqueueorqueuetable
formessagesofapredefinedobjecttype.

DBMS_AQELMConfigureAdvancedQueuing
asynchronousnotificationbyemailandHTTP.*

DBMS_BACKUP_RESTORE
NormalizefilenamesonWindowsNTplatforms.

DBMS_DDLAccessSQLDDLstatementsfromastoredprocedure,
providesspecialadministrationoperations
notavailableasDDLs.

DBMS_DEBUGImplementserversidedebuggersandprovideawayto
debugserversidePL/SQLprogramunits.

DBMS_DEFERUserinterfacetoareplicatedtransactionaldeferred
RPCfacility.RequirestheDistributedOption.

Oracle Complete PLSQL Reference 169


DBMS_DEFER_QUERY
Permitqueryingthedeferredremoteprocedurecalls(RPC)
queuedatathatisnotexposedthroughviews.
RequirestheDistributedOption.

DMBS_DEFER_SYS
Thesystemadministratorinterfacetoareplicated
transactionaldeferredRPCfacility.
RequirestheDistributedOption.

DBMS_DESCRIBE
Describetheargumentsofastoredprocedure
withfullnametranslationandsecuritychecking.

DBMS_DISTRIBUTED_TRUST_ADMIN
MaintaintheTrustedDatabaseList,whichisusedto
determineifaprivilegeddatabaselinkfromaparticular
servercanbeaccepted.

DBMS_ENCODEEncode???

DBMS_FGAFinegrainedsecurityfunctions.*

DMBS_FLASHBACK
Flashbacktoaversionofthedatabaseataspecified
wallclocktimeoraspecifiedsystemchange
number(SCN).*

DBMS_HS_PASSTHROUGH
SendpassthroughSQLstatementstononOraclesystems.
(viaHeterogeneousServices)

DBMS_IOTCreateatableintowhichreferencestothechainedrows
foranIndexOrganizedTablecanbeplacedusingthe
ANALYZEcommand.

DBMS_JOBSchedulePL/SQLproceduresthatyouwantperformedat
periodicintervals;alsothejobqueueinterface.

DBMS_LDAPFunctionsandprocedurestoaccessdatafrom
LDAPservers.*

DBMS_LIBCACHE
PreparesthelibrarycacheonanOracleinstanceby
extractingSQLandPL/SQLfromaremoteinstanceand
compilingthisSQLlocallywithoutexecution.*

DBMS_LOBGeneralpurposeroutinesforoperationsonOracleLarge
Object(LOBs)datatypesBLOB,CLOB(readwrite),

Oracle Complete PLSQL Reference 170


andBFILEs(readonly).

DBMS_LOCKRequest,convertandreleaselocksthroughOracleLock
Managementservices.

DBMS_LOGMNRFunctionstoinitializeandrunthelogreader.

DBMS_LOGMNR_CDC_PUBLISH
Identifynewdatathathasbeenaddedto,modified,or
removedfrom,relationaltablesandpublishthechanged
datainaformthatisusablebyanapplication.*

DBMS_LOGMNR_CDC_SUBSCRIBE
Viewandquerythechangedatathatwascaptured
andpublishedwiththeDBMS_LOGMNR_CDC_PUBLISHpackage.*

DBMS_LOGMNR_D
Querythedictionarytablesofthecurrentdatabase,and
createatextbasedfilecontainingtheircontents.

DBMS_METADATA
Retrievecompletedatabaseobjectdefinitions(metadata)
fromthedictionary.*

DBMS_MVIEWRefreshsnapshotsthatarenotpartofthesame
refreshgroupandpurgelogs.DBMS_SNAPSHOTisasynonym.

DBMS_OBFUSCATION_TOOLKIT
ProceduresforDataEncryptionStandards.

DBMS_ODCIGettheCPUcostofauserfunctionbasedonthe
elapsedtimeofthefunction.*

DBMS_OFFLINE_OG
PublicAPIsforofflineinstantiationofmastergroups.

DBMS_OFFLINE_SNAPSHOT
PublicAPIsforofflineinstantiationofsnapshots.

DBMS_OLAPProceduresforsummaries,dimensions,andqueryrewrites.

DBMS_ORACLE_TRACE_AGENT
ClientcallableinterfacestotheOracleTRACE
instrumentationwithintheOracle7Server.

DBMS_ORACLE_TRACE_USER
PublicaccesstotheOraclerelease7Server
OracleTRACEinstrumentationforthecallinguser.

Oracle Complete PLSQL Reference 171


DBMS_OUTLNInterfaceforproceduresandfunctionsassociatedwith
managementofstoredoutlines.SynonymouswithOUTLN_PKG

DBMS_OUTLN_EDIT
Editaninvoker'srightspackage.*

DBMS_OUTPUTAccumulateinformationinabuffersothatitcanbe
retrievedoutlater.

DBMS_PCLXUTILIntrapartitionparallelismforcreatingpartitionwise
localindexes.

DBMS_PIPEADBMSpipeservicewhichenablesmessagestobesent
betweensessions.

DBMS_PROFILERAProbeProfilerAPItoprofilePL/SQLapplications
andidentifyperformancebottlenecks.
Toinstallthisrunprofload.sql(asSYS)andproftab.sql(as
user)

DBMS_RANDOMAbuiltinrandomnumbergenerator.
Optionstogeneraterandomnumberswithinarangeor
distribution.

DBMS_RECTIFIER_DIFF
APIsusedtodetectandresolvedatainconsistencies
betweentworeplicatedsites.

DBMS_REDEFINITION
Reorganiseatable(changeit'sstructure)whileit's
stillonlineandinuse.*

DBMS_REFRESHCreategroupsofsnapshotsthatcanberefreshedtogether
toatransactionallyconsistentpointintime.
RequirestheDistributedOption.

DBMS_REPAIRRepairdatacorruption.

DBMS_REPCATAdministerandupdatethereplicationcatalogandenvironment.
RequirestheReplicationOption.

DBMS_REPCAT_ADMIN
Createuserswiththeprivilegesneededbythesymmetric
replicationfacility.RequirestheReplicationOption.

DBMS_REPCAT_INSTATIATE
Instantiatesdeploymenttemplates.
RequirestheReplicationOption.

Oracle Complete PLSQL Reference 172


DBMS_REPCAT_RGT
Defineandmaintainrefreshgrouptemplates.
RequirestheReplicationOption.

DBMS_REPUTIL
Generateshadowtables,triggers,andpackages
fortablereplication.

DBMS_RESOURCE_MANAGER
Maintainplans,consumergroups,andplandirectives;
alsoprovidessemanticssothatyoumaygrouptogether
changestotheplanschema.

DBMS_RESOURCE_MANAGER_PRIVS
Maintainprivilegesassociatedwithresourceconsumergroups.

DBMS_RESUMABLE
Suspendlargeoperationsthatrunoutofspaceorreachspace
limitsafterexecutingforalongtime,fixtheproblem,and
makethestatementresumeexecution.

DBMS_RLSRowlevelsecurityadministrativeinterface.

DBMS_ROWIDProcedurestocreaterowidsandtointerprettheircontents.

DBMS_SESSIONAccesstoSQLALTERSESSIONstatements,andothersession
information,fromstoredprocedures.

DBMS_SHARED_POOL
Keepobjectsinsharedmemory,sothattheywillnotbeaged
outwiththenormalLRUmechanism.

DBMS_SNAPSHOT
SynonymforDBMS_MVIEW

DBMS_SPACESegmentspaceinformationnotavailablethroughstandardSQL.
Howmuchspaceisleftbeforeanewextentgetsallocated?
HowmanyblocksareabovethesegmentsHighWaterMark?
Howmanyblocksareinthefreelist(s)

DBMS_SPACE_ADMIN
Tablespaceandsegmentspaceadministrationnotavailable
throughthestandardSQL.

DBMS_SQLUsedynamicSQLtoaccessthedatabase.

DBMS_STANDARD
Languagefacilitiesthathelpyourapplicationinteract
withOracle.

Oracle Complete PLSQL Reference 173


Oracle Complete PLSQL Reference 174


DBMS_STATSViewandmodifyoptimizerstatisticsgatheredfordatabase
objects.Inasmalltestenvironmentthisallowsfakingthestatstosimulate
runningalargeproductiondatabase.

DBMS_TRACERoutinestostartandstopPL/SQLtracing.

DBMS_TRANSACTION
AccesstoSQLtransactionstatementsfromstored
proceduresandmonitorstransactionactivities.

DBMS_TRANSFORM
Aninterfacetothemessageformattransformationfeatures
ofOracleAdvancedQueuing.*

DBMS_TTSCheckifatransportablesetisselfcontained.

DBMS_TYPESConstants,whichrepresentthebuiltinanduserdefined
types.

DBMS_URLOracleSpatialconnection_type??

DBMS_UTILITYUtilityroutines,Analyze,Time,Conversionetc.

DBMS_WMDatabaseWorkspaceManager(longtransactions)*

DBMS_XMLGENConverttheresultsofaSQLquerytoacanonicalXMLformat.
*

DMBS_XMLQUERY
DatabasetoXMLTypefunctionality.*

DBMS_XMLSAVE
XMLtodatabasetypefunctionality.*

DEBUG_EXTPROC
Debugexternalproceduresonplatformswithdebuggers
thatcanattachtoarunningprocess.

OUTLN_PKGSynonymofDBMS_OUTLN.

PLITBLMHandleindextableoperations.(Don'tcalldirectly)

SDO_CS,SDO_GEOM,SDO_LRS,SDO_MIGRATE,SDO_TUNE
seeOracleSpatialUser'sGuideandReference
SpatialpackagesareinstalledinuserMDSYSwithpublic
synonyms.

STANDARDTypes,exceptions,andsubprogramswhichare

Oracle Complete PLSQL Reference 175


availableautomaticallytoeveryPL/SQLprogram.

UTL_COLLCollectionlocatorsqueryandupdatefromaPL/SQLprogram.

UTL_ENCODEEncodeRAWdataintoastandardencodedformat
sothatthedatacanbetransportedbetweenhosts.*

UTL_FILEReadandwriteOStextfilesviaPL/SQL.
ArestrictedversionofstandardOSstreamfileI/O.

UTL_HTTPEnableHTTPcalloutsfromPL/SQLandSQLtoaccessdata
ontheInternetortocallOracleWebServerCartridges.

UTL_INADDRAproceduretosupportinternetaddressing.

UTL_PGConvertCOBOLnumericdataintoOraclenumbers
andconvertOraclenumbersintoCOBOLnumericdata.

UTL_RAWSQLfunctionsforRAWdatatypesthatconcat,
substr,etc.toandfromRAWS.

UTL_REFEnableaPL/SQLprogramtoaccessanobjectbyprovidinga
referencetotheobject.

UTL_SMTPSendSMTPemail.Themailerprogramneedstorunonthe
server,
butcanbeinvokedfromaclient.

UTL_TCPSimpleTCP/IPbasedcommunicationbetweenserversandthe
outsideworld.

UTL_URLEscapeandunescapemechanismforURLcharacters.

ANYDATATYPEAselfdescribingdatainstanceTYPE.

ANYDATASETTYPE
DescribeagivenTYPEplusasetofdatainstancesofthat
type.

ANYTYPETYPEContainsatypedescriptionofanypersistentSQLtype,
namedorunnamed,includingobjecttypesandcollectiontypes.

Seealso

EXECExecuteaPL/SQLpackage
DESCDescribeapackage

RelatedViews
ALL_ARGUMENTSUSER_ARGUMENTS

Oracle Complete PLSQL Reference 176


DBA_OBJECTSALL_OBJECTSUSER_OBJECTSSYS_OBJECTS
ALL_PROCEDURESUSER_PROCEDURES
DBA_SOURCEALL_SOURCEUSER_SOURCE

Oracle Complete PLSQL Reference 177


2.MorganLibraryvipvip

Topic Version LastModified Comment


ActiveSessionHistory 11gR1 25Dec2007
AddBindingClause 11gR1 19Sep2007
ADDMDemo 11gR1 01Feb2008
ADRCommandInterpreter 11gR1 09Aug2008
AdvancedCompression 11gR1 09Nov2008
AdvancedQueuingDemo 11gR1 05Mar2008
AnalyticFunctions 11gR1 16Oct2007
Analyze 11gR1 09Jul2007
AnonymousBlock 11gR1 21Jul2007
AnydataDataType 11gR1 28Jul2007
ApplicationServer 10.1.2.0.2 07Feb2007
ApplicationServer 10.1.3.0.0 07Feb2007
ArchiveLogs 11gR1 06Oct2007
ArrayProcessing 11gR1 18Aug2008
Arrays:IndexbyBINARY_INTEGER 11gR1 07Jul2007
Arrays:IndexbyVARCHAR2 11gR1 07Jul2007
ASOFQueries 11gR1 14Sep2007
ASH 11gR1 25Dec2007
AssociateStatistics 11gR1 03Jan2008
AssociativeArrays 11gR1 07Jul2007
AuditVault 10.2.3 14Jun2008
Auditing 11gR1 06Aug2007
AUTHID(DEFINER)andCURRENT_USER) 11gR1 01Sep2008
AutomaticDiagnosticRepository 11gR1 28Sep2007
AutomaticWorkloadRepository 11gR1 17Aug2007
AutomaticWorkloadRepositoryReport 11gR1 17Aug2007
AutonomousTransactions 11gR1 30Jan2008
Autotrace 11gR1 08Jul2007
AWR 11gR1 17Aug2007
AWRReport 11gR1 17Aug2007
Backup&Recovery 10gR2 07Mar2006
B*TreeIndexes 11gR1 03Nov2008
BidirectionalCursor 11gR1 06Aug2007
BindVariables 11gR1 20Jul2007
BitmapIndexes 11gR1 03Nov2008
BitmapJoinIndexes 11gR1 03Nov2008
BLAST_CUR 11gR1 14Dec2007
BlockChangeTracking 11gR1 20Jul2007
BlockDump 11gR1 16Oct2007
BreakingOracle(demosfromUKOUG
11gR1 03Dec2008
presentation)
BSQFiles 11gR1 19Oct2007
BuiltinPackages 11gR1 06Oct2007
BufferPool 11gR1 15Jul2007
BulkBinding/BulkCollection 11gR1 17Aug2008
CASEFunction 11gR1 15Aug2007
CastFunction 11gR1 21Jul2007
ChainedRows 11gR1 30Jul2007
ChangeDataCaptureSync 11gR1 01Jun2008
ChangeDataCaptureHotLog 11gR1 01Jun2008
ChangeDataCaptureAutoLog 10gR2

Oracle Complete PLSQL Reference 178


CharacterSets 11gR1 30Jul2007
CharacterSetFunctions 11gR1 21Jul2007
CheckConstraint 11gR1 25Nov2007
ClusteringFactor 11gR1 12Aug2007
Clusters 11gR1 20Jul2007
Codd'sRules 07Jul2007
Collections 11gR1 30Nov2008
CollectionFunctions 11gR1 08Oct2007
ColoredSQL 11gR1 17Aug2007
COLUMN_VALUE 11gR1 25Aug2007
Commit 11gR1 07Jul2007
CommonTableExpressions 11gR1 10Feb2008
Compilation:InterpretedandNative 11gR1 09Aug2007
CompoundTriggers 11gR1 12Aug2007
CompositePartitioning 11gR1 25Nov2007
CompressedIndexes 11gR1 09Nov2008
CompressedTables 11gR1 09Nov2008
ConditionalCompilation 11gR1 25Nov2007
Conditions 11gR1 24Nov2007
ConnectBy 11gR1 26Nov2008
Constants 11gR1 21Aug2007
Constraints 11gR1 29Feb2008
ConsumerGroups 11gR1 25Dec2007
Contexts 11gR1 06Oct2007
ContinueStatement 11gR1 09Aug2007
ControlFiles 11gR1 16Nov2008
ControlStructures 11gR1 19Dec2007
ConversionFunctions 11gR1 04Apr2008
CreateDatabase 11gR1 01May2008
CreateSchema 11gR1 08Jul2007
CrossTabulationandPivotOperator 11gR1 02Oct2007
CRS_STAT 11gR1 07Feb2006
CTX_DDL 11gR1 24Dec2007
Cube 11gR1 06Oct2007
CursorSharing 11gR1 26Oct2007
Cursors&CursorLoops 11gR1 19Dec2007
DANGLING 11gR1 23Nov2007
DataControlLanguage(DCL) 11gR1 07Jul2007
DataDictionary 11gR1 02Sep2008
DataFiles 11gR1 07Oct2007
DataGuard 10gR2 30May2007 PhysicalOnly
DataIntegrity 11gR1 26Oct2007
DataMiningFunctions 11gR1 05Oct2007
DataPump(API) 11gR1 27Dec2007
DataPump(Executable) 11gR1 07Sep2008
DataTypes&SubTypes 11gR1 09Oct2007
Database 11gR1 01May2008
DatabaseLinks 11gR1 23Nov2007
DateFunctions 11gR1 08Nov2008
DBMSOBJG 11gR1 08Jul2007
DBMS_ADDM 11gR1 16Nov2007
DBMS_ADVANCED_REWRITE 11gR1 11Aug2007
DBMS_ADVISOR 11gR1 01Feb2008
DBMS_ALERT 11gR1 08Jul2007
DBMS_AMD 11gR1 08Jul2007
DBMS_APPLICATION_INFO 11gR1 06Jan2008

Oracle Complete PLSQL Reference 179


DBMS_APPLY_ADM 11gR1 12Dec2007 incomplete
DBMS_AQ 11gR1 05Nov2007
DBMS_AQADM 11gR1 06Apr2008
DBMS_AQELM 11gR1 08Oct2007
DBMS_ASSERT 11gR1 12Aug2007
DBMS_ASYNCRPC_PUSH 11gR1 08Jul2007
DBMS_AUTO_TASK 11gR1 24Aug2007
DBMS_AUTO_TASK_ADMIN 11gR1 10Oct2007
DBMS_AUTO_TASK_EXPORT 11gR1 10Oct2007
DBMS_AUTO_TASK_IMMEDIATE 11gR1 10Oct2007
DBMS_AW 11gR1 15Feb2008
DBMS_AW_STATS 11gR1 15Feb2008
DBMS_BACKUP_RESTORE 11gR1 28May2008
DBMS_CAPTURE_ADM 11gR1 17Oct2007
DBMS_CDC_PUBLISH 11gR1 20Sep2008
DBMS_CDC_SUBSCRIBE 11gR1 18Oct2007
DBMS_CDC_UTILITY 11gR1 20Sep2008
DBMS_CHANGE_NOTIFICATION 11gR1 07Apr2008
DBMS_CLUSTDB 11gR1 08Jul2007
DBMS_COMPARISON 11gR1 30Oct2008
DBMS_CONNECTION_POOL 11gR1 12Aug2007
DBMS_CQ_NOTIFICATIONS 11gR1 25Dec2007
DBMS_CRYPTO 11gR1 11Aug2007
DBMS_CRYPTO_TOOLKIT_TYPES 11gR1 29Jul2007
DBMS_CSX_ADMIN 11gR1 13Sep2007
DBMS_CUBE 11gR1 15Feb2008
DBMS_DATAPUMP 11gR1 27Dec2007
DBMS_DBLINK 11gR1 29Jul2007
DBMS_DB_VERSION 11gR1 25Nov2007
DBMS_DBVERIFY 11gR1 23Aug2007
DBMS_DDL 11gR1 18Mar2008
DBMS_DDL_INTERNAL 11gR1 18Aug2007
DBMS_DESCRIBE 11gR1 18Dec2007
DBMS_DG 11gR1 24Aug2007
DBMS_DIMENSION 11gR1 04Dec2007
DBMS_DISTRIBUTED_TRUST_ADMIN 11gR1 16Mar2008
DBMS_DRS 11gR1 14Dec2007
DBMS_EDITIONS_UTILITIES 11gR1 13Sep2007
DBMS_EPG 11gR1 18Mar2008
DBMS_ERRLOG 11gR1 24Aug2007
DBMS_EXPFIL 11gR1 25Dec2007
DBMS_EXTENDED_TTS_CHECKS 11gR1 07Dec2007
DBMS_FBT 11gR1 26Sep2008
DBMS_FEATURE_USAGE 11gR1 17Aug2007
DBMS_FEATURE_USAGE_REPORT 11gR1 17Aug2007
DBMS_FGA 11gR1 24Dec2007
DBMS_FILE_TRANSFER 11gR1 09Aug2007
DBMS_FLASHBACK 11gR1 14Sep2007
DBMS_FREQUENT_ITEMSET 11gR1 18Mar2008
DBMS_HA_ALERTS 11gR1 14Aug2007
DBMS_HA_ALERTS_PRVT 11gR1 14Aug2007
DBMS_HM 11gR1 24Sep2007
DBMS_HPROF 11gR1 23Aug2007
DBMS_I_INDEX_UTL 11gR1 14Mar2008
DBMS_INDEX_UTL 11gR1 09Aug2007
DBMS_INDEXING 11gR1 09Aug2007

Oracle Complete PLSQL Reference 180


DBMS_IOT 11gR1 17Aug2007
DBMS_IR 11gR1 13Sep2007
DBMS_JOB 11gR1 24Aug2007 SeeDBMS_SCHEDULERtoo
DBMS_LCR 11gR1 29Jul2007
DBMS_LDAP 11gR1 13Dec2007
DBMS_LOB 11gR1 25Sep2007
DBMS_LOBUTIL 11gR1 26Sep2007
DBMS_LOCK 11gR1 18Aug2007
DBMS_LOGMNR 11gR1 25Dec2007
DBMS_LOGMNR_D 11gR1 24Apr2008
DBMS_LOGSTDBY 11gR1 17Sep2007
DBMS_MANAGEMENT_PACKS 11gR1 26Sep2007
DBMS_METADATA 11gR1 29Jul2008
DBMS_METADATA_UTIL 11gR1 11Apr2008
DBMS_MONITOR 11gR1 01Feb2008
DBMS_MVIEW 11gR1 04Dec2007
DBMS_NETWORK_ACL_ADMIN 11gR1 26Dec2007
DBMS_NETWORK_ACL_UTILITY 11gR1 09Aug2007
DBMS_OBFUSCATION_TOOLKIT DeprecatedSeeDBMS_CRYPTO
DBMS_OBJECT_UTILS 11gR1 17Dec2007
DBMS_ODCI 11gR1 09Aug2007
DBMS_OUTLN 11gR1 30Mar2008
DBMS_OUTLN_EDIT 11gR1 30Mar2008
DBMS_OUTPUT 11gR1 10Jul2007
DBMS_PCLXUTIL 11gR1 10Jul2007
DBMS_PREDICTIVE_ANALYTICS 11gR1 13Aug2007
DBMS_PREPROCESSOR 11gR1 13Aug2007
DBMS_PROFILER 11gR1 20Aug2007
DBMS_PROPAGATION_ADM 11gR1 30Mar2008
DBMS_RANDOM 11gR1 10Jul2007 SeeDBMS_CRYPTOtoo
DBMS_RECTIFIER_DIFF 11gR1 30Oct2008
DBMS_RECTIFIER_FRIENDS 11gR1 10Jul2007
DBMS_REDEFINITION 11gR1 29Mar2008
DBMS_REFRESH 11gR1 20Aug2007
DBMS_REGISTRY 11gR1 17Aug2008
DBMS_REGISTRY_SERVER 11gR1 24Dec2007
DBMS_REGXDB 11gR1 20Aug2007
DBMS_REPAIR 11gR1 24Dec2007
DBMS_REPUTIL 11gR1 20Sep2007
DBMS_RESOURCE_MANAGER 11gR1 25Dec2007
DBMS_RESOURCE_MANAGER_PRIVS 11gR1 24Nov2007
DBMS_RESULT_CACHE 11gR1 02Dec2007
DBMS_RESUMABLE 11gR1 24Nov2007
DBMS_RLS 11gR1 17May2008
DBMS_ROWID 11gR1 26Nov2007
DBMS_SCHEDULER 11gR1 19May2008
DBMS_SCHEMA_COPY 10gR2 06May2006 Droppedfrom11.1.0.6
DBMS_SERVER_ALERT 11gR1 07Apr2008
DBMS_SERVER_TRACE 11gR1 30Mar2008
DBMS_SERVICE 11gR1 22Dec2007
DBMS_SESSION 11gR1 14Sep2007
DBMS_SESSION_STATE 11gR1 14Dec2007
DBMS_SHARED_POOL 11gR1 20Nov2007
DBMS_SNAPSHOT 11gR1 07Sep2007
DBMS_SPACE 11gR1 23Aug2007
DBMS_SPACE_ADMIN 11gR1 23Aug2007

Oracle Complete PLSQL Reference 181


DBMS_SPM 11gR1 13Sep2007
DBMS_SQL 11gR1 14Apr2008
DBMS_SQLDIAG 11gR1 28Sep2007
DBMS_SQLHASH 11gR1 29Aug2007
DBMS_SQLJTYPE 11gR1 19Aug2007
DBMS_SQLPA 11gR1 13Sep2007
DBMS_SQLPLUS_SCRIPT 11gR1 06Dec2007
DBMS_SQLTUNE 11gR1 02Dec2008
DBMS_STAT_FUNCS 11gR1 01Apr2008
DBMS_STATS 11gR1 27Nov2008
DBMS_STORAGE_MAP 11gR1 19Aug2007
DBMS_STREAMS 11gR1 01Apr2008
DBMS_STREAMS_ADM 11gR1 01Apr2008
DBMS_STREAMS_AUTH 11gR1 18Dec2007
DBMS_SUPPORT 11gR1 29Jan2008
DBMS_SYSTEM 11gR1 28Mar2008
DBMS_TDB 11gR1 24Dec2007
DBMS_TRACE 11gR1 29Jan2008
DBMS_TRANSACTION 11gR1 03Nov2007
DBMS_TRANSFORM 11gR1 04Apr2008
DBMS_TTS 11gR1 07Apr2008
DBMS_TYPES 11gR1 29Jul2007
DBMS_UNDO_ADV 11gR1 19Aug2007
DBMS_UTILITY 11gR1 04Nov2008
DBMS_WARNING 11gR1 06Jan2008
DBMS_WARNING_INTERNAL 11gR1 15Jul2007
DBMS_WLM 11gR1 19Sep2007
DBMS_WMSynonym 10gR2 17Dec2005
DBMS_WORKLOAD_CAPTURE 11gR1 07Sep2007
DBMS_WORKLOAD_REPLAY 11gR1 07Sep2007
DBMS_WORKLOAD_REPOSITORY 11gR1 17Aug2007
DBMS_XA 11gR1 13Aug2007
DBMS_XDBUTIL_INT 11gR1 26Dec2007
DBMS_XMLGEN 11gR1 29Mar2008
DBMS_XPLAN 11gR1 28Apr2008
DBMS_ZHELP 11gR1 13Jul2007
DBMS_ZHELP_IR 11gR1 13Jul2007
DBV(databaseverify) 11gR1 05Oct2007
DCLStatements 11gR1 29Jul2007
DDLEventTriggers 11gR1 18Mar2008
Deadlocks 11gR1 08Dec2007
DECODEFunction 11gR1 15Aug2007
DeferrableConstraints 11gR1 21Jun2008
DeleteStatement 11gR1 12Aug2007
DescendingIndexes 11gR1 03Nov2008
DICOM 11gR1 24Sep2008
Dimensions 11gR1 02Dec2008
Directories 11gR1 29Jul2007
DisassociateStatistics 11gR1 03Jan2008
DIUTIL 11gR1 11Jul2007
DMLStatements 11gR1 07Jul2007
DumpingOracle 11gR1 10Apr2008
DynamicPerformanceViews 11gR1 28Aug2008
EBusinessSuite 11.5.10 29Sep2007
Editions 11gR1 11Aug2007
EncryptedTablespaces 11gR1 30Sep2007

Oracle Complete PLSQL Reference 182


EnvironmentVariables 11gR1 30Mar2008
Errors 11gR1 30Jul2007
Events 11gR1 04Sep2008
ExceptionHandling 11gR1 01Dec2008
ExcludedNodes 11gR1 27Sep2008
Exists 11gR1 08Jul2007
ExplainPlan 11gR1 16Aug2007
Export 11gR1 27Oct2007
ExpressionFiltering 10g 28Apr2005
ExternalTables 11gR1 10Feb2008
FilesOfInterest 11gR1 25Sep2008
FineGrainedAccessControl(FGAC) 11gR1 17May2008
FineGrainedAccessControlDemo 11gR1 17Nov2008
FineGrainedAuditing(FGA) 11gR1 24Dec2007
Flashback 11gR1 14Aug2007
FlashbackArchive 11gR1 15Oct2007
FlashbackDatabase 11gR1 14Aug2007
FlashbackDrop 11gR1 14Aug2007
FlashbackQuery 11gR1 14Aug2007
FlashbackTable 11gR1 14Aug2007
FlashbackTransaction 11gR1 14Aug2007
FlashbackVersion 11gR1 14Aug2007
FOLLOWSClause(Triggers) 11gR1 12Aug2007
FORUPDATE 11gR1 07Jul2007
FORALL 11gR1 17Aug2008
ForeignKeyConstraint 11gR1 29Feb2008
FORMs 10g 24Jan2005
FunctionBasedIndexes 11gR1 03Nov2008
Functions:Deterministic 11gR1 27Sep2008
Functions:Miscellaneous 11gR1 19Aug2007
Functions:UserDefined 11gR1 10Jan2008
FusionMiddleWareApplicationServer 10.1.2.0.2 02Jan2007
FusionMiddleWareApplicationServer 10.1.3.0.0 02Jan2007
GlobalHints 10gR2 22Aug2006
GlobalPartitionedIndexes 11gR1 25Nov2007
GlobalTemporaryTables 11gR1 01Nov2007
GlobalizationToolkit 11gR1 10Oct2007
GridControl 10.2.0.4 01Jan2008
GROUPBYClauses 11gR1 22Oct2007
GROUPID 11gR1 22Oct2007
GROUPINGSETS 11gR1 22Oct2007
GuaranteedRestorePoint 11gR1 29Jul2007
GV$Views 11gR1 01Nov2007
HashPartitioning 11gR1 25Nov2007
HAVINGClauses 11gR1 22Oct2007
HeapTables 11gR1 26Nov2008
Hints 10gR2 08Apr2008
Histograms 11gR1 02Mar2008
HostEnvironment 11gR1 02Mar2008
HTP 11gR1 30Mar2008
IFStatements 11gR1 06Aug2007
Import 11gR1 27Oct2007
Indexes 11gR1 03Nov2008
IndexOrganizedTables(IOT) 11gR1 09Nov2007
InitSIDDotOra 11gR1 13Nov2008
InlineViews 11gR1 02Mar2008

Oracle Complete PLSQL Reference 183


InsertStatements 11gR1 29Oct2007
InsteadOfTriggers 11gR1 08Nov2008
InstringFunction 11gR1 27Jul2007
IntermediaAudio 11gR1 25Aug2008
IntermediaVideo 11gR1 25Aug2008
Interval 11gR1 20Dec2007
IntervalPartitioning 11gR1 25Nov2007
InvisibleIndexes 11gR1 03Nov2008
InvitedNodes 11gR1 27Sep2008
ISNOTOFTYPE 11gR1 17Aug2008
ISOFONLY 11gR1 17Aug2008
ISOFTYPE 11gR1 17Aug2008
JavaFunctions 11gR1 20Mar2008
Joins 11gR1 16Aug2008
KeepPool 11gR1 15Jul2007
KillingSessions 11gR1 08Feb2008
LargeObjects 11gR1 18Oct2008
LCR$_XML_SCHEMA 11gR1 18Oct2008
Licensing 10gR2 30Sep2006
Licensing 11gR1 08Feb2008
LinuxInstallationforOracleRDBMS 10gR2 16Jan2008
LinuxInstallationforOracleRDBMS 11gR1 16Jan2008
ListPartitioning 11gR1 25Nov2007
Listener 11gR1 03Mar2008
LOBCompression 11gR1 29Jul2007
LOBs 11gR1 18Oct2008
LocalPartitionedIndexes 11gR1 25Nov2007
Locks 11gR1 09Feb2008
LogFiles 11gR1 27Nov2007
LONGToCLOB 11gR1 09Feb2008
Loops 11gR1 19Dec2007
LTBuiltinPackage 10gR2 17Dec2005
MaterializedViews 11gR1 06Jun2008
MergeStatement 11gR1 12Aug2007
MicrosoftSQLServer2005Comparison 24Apr2007
MicrosoftVistaEnterpriseandOracle 21Apr2007
ModelClause 10g 09Dec2006
MultimediaAudio 11gR1 25Aug2008
MultimediaVideo 11gR1 25Aug2008
Multiset 11gR1 21Jul2007
MultiversionConcurrencyControl(MVCC) 11gR1 11Nov2007
NativeCompilation 11gR1 09Aug2007
NativeDynamicSQL(NDS) 11gR1 20Feb2008
NestedLoops 11gR1 24Dec2007
NestedTables 11gR1 02Dec2008
NestedTableConstraints 11gR1 23Nov2007
NetAppFilerHead 11gR1 10Oct2008
NetServices 11gR1 13Nov2008
NetworkApplianceFilerManagement 16Jan2007
NID(changeinternaldatabaseidentifier) 11gR1 05Oct2007
NoSegmentIndexes 11gR1 03Nov2008
NOCOPY 11gR1 14Sep2007
Normalization 28May2007
NOWAIT 11gR1 07Jul2007
NumericFunctions 11gR1 16Oct2008
NULL 11gR1 14Sep2007

Oracle Complete PLSQL Reference 184


NULLPruning 11gR1 04Dec2007
ObjectPrivileges 11gR1 24Dec2007
ObjectRelationalViews 10g 17Nov2004
ObjectTables:SeeNestedTablesandVarrays 11gR1 20Sep2008
OBJECT_ID 11gR1 25Aug2007
Operators:Builtin 11gR1 16Aug2008
Operators:UserDefined 11gR1 19Sep2007
ORA_HASH 11gR1 13Jul2007
ORA_NAME_LIST_T 11gR1 22Dec2007
ORA_ROWSCN 11gR1 25Aug2007
ORADEBUG 11gR1 25Sep2008
ORADIM 10gR2 23Nov2005
ORAPWD 11gR1 13Dec2007
ORDERBYClause 11gR1 22Oct2007
Outlines 11gR1 30Mar2008
OUTLN_EDIT_PKG 11gR1 30Mar2008
OUTLN_PKG 11gR1 30Mar2008
OWA 11gR1 18Dec2007
OWA_CUSTOM 11gR1 15Sep2007
OWA_CX 11gR1 15Sep2007
OWA_OPT_LOCK 11gR1 15Sep2007
OWA_SEC 11gR1 15Sep2007
OWA_TEXT 11gR1 15Sep2007
OWA_UTIL 11gR1 09Apr2008
Packages:UserDefined 11gR1 17Oct2008
ParentCorrelationName 11gR1 06Aug2007
Partitioning(tablesandindexes) 11gR1 25Nov2007
PartitioningbyReference 11gR1 25Nov2007
PartitionbySystem 11gR1 29Dec2007
PartitioningEliminationDemo 11gR1 25Nov2007
PartitioningPruningDemo 11gR1 25Nov2007
PasswordFile 11gR1 19Nov2008
PipelinedTableFunctions 11gR1 17Dec2007
Pivot 11gR1 02Oct2007
PLSHPROF 11gR1 23Aug2007
PLSQL_CCFLAGS 11gR1 25Nov2007
PL/Scope 11gR1 02Feb2008
PL/SQLObjectSettings 11gR1 09Aug2007
PL/SQLWarnings 11gR1 16Jan2008
PRAGMAS 11gR1 27Jan2008
PRAGMAAutonomous_Transaction 11gR1 30Jan2008
PRAGMAException_Init 11gR1 02Oct2007
PRAGMAInline 11gR1 02Oct2007
PRAGMASeriallyReusable 11gR1 02Oct2007

Primary
KeyConstraint 11gR1 25Nov2007
Procedures 11gR1 17Dec2007
ProductUserProfiles 11gR1 17Oct2007
Profiles 11gR1 20Dec2007
Protocol.ora 11gR1 27Sep2008 DeprecatedSee:SQLNET.ORA
PseudoColumns 11gR1 25Aug2007
PublicSynonyms 11gR1 21Jul2007
PurgeRecyclebin 11gR1 14Aug2007
PurgeTable 11gR1 14Sep2007
QuoteDelimiters 11gR1 14Sep2007
RAC 11gR1 15Oct2008
RAID 11gR1 09Feb2008

Oracle Complete PLSQL Reference 185


RangePartitioning 11gR1 25Nov2007
Rank 11gR1 02Mar2008
RDA 10gR2 05Oct2006
RealApplicationClusters 11gR1 15Oct2008
RecycleBin 11gR1 30Dec2007
RecyclePool 11gR1 15Jul2007
Redo 11gR1 01Oct2007
RefCursors 11gR1 05Dec2007
ReferentialConstraint 11gR1 29Feb2008
ReferentialPartition 11gR1 25Nov2007
RegularExpressions 11gR1 09Feb2008
RemoteDiagnosticAgent 10gR2 05Oct2006
ReplaceBuiltinFunction 11gR1 07Aug2007
RestorePoint 11gR1 29Jul2007
ResultCache(SQL) 11gR1 02Dec2007
ResultCache(PL/SQL) 11gR1 02Dec2007
ResumableTransactions_ 11gR1 03Nov2007
ReverseKeyIndexes 11gR1 03Nov2008
RewriteEquivalence 11gR1 11Aug2007
RMAN 10gR2 26Apr2006 incomplete
RMANDemo 11gR1 20Oct2008
Roles 11gR1 03Oct2007
Rollback 11gR1 07Jul2007
Rollup 11gR1 06Oct2007
ROWDEPENDENCIES 11gR1 25Aug2007
ROWID 11gR1 25Aug2007
RowLevelSecurity 11gR1 17May2008
ROWNUM 11gR1 25Aug2007
RuleBasedOptimizer(RBO) 16Apr2004 Deprecated
SampleClause 11gR1 29Oct2008
Savepoint 11gR1 07Jul2007
Schema 11gR1 08Jul2007
SecureFiles 11gR1 19Jul2008
Security 11gR1 27May2008
Segments 11gR1 18Oct2008
SelectStatement 11gR1 29Oct2008
SelectIntoStatement 11gR1 29Oct2008
Sequences 11gR1 11Aug2007
Services 11gR1 22Dec2007
Sessions 11gR1 11Sep2008
SetOperators 11gR1 19Sep2007
SETTRANSACTION 11gR1 15Dec2007
SHOW 11gR1 24Dec2007
SKIPLOCKED 11gR1 07Jul2007
SLEEP 11gR1 25Aug2007
Snapshots 11gR1 21Nov2007
SortedHashClusters 11gR1 20Jul2007
Soundex 11gR1 14Sep2007
SPFile 11gR1 13Nov2008
SQLInjection 10gR2 05Mar2007
SQL*Loader 10gR2 17Dec2007
SQL*Plus 11gR1 16Dec2007
SQLNET.ORA 11gR1 27Sep2008
Standard 11gR1 01Dec2008
Starting&StoppingTheDatabase 11gR1 05Apr2008
StartupParameters 11gR1 13Nov2008

Oracle Complete PLSQL Reference 186


StoredOutlines 11gR1 30Mar2008
StoredProcedures 11gR1 17Dec2007
Storage 19Oct2006
StreamsDemo1 10gR2 07Jun2007
StreamsDemo2 10gR2 07Jun2007
StreamsDemo3 10gR2 07Jun2007
StringFunctions 11gR1 16Oct2008
Subqueries 11gR1 08Jul2007
SubstringFunction 11gR1 27Jul2007
SybaseASE15.0.1Comparison 26Jan2007
Synonyms 11gR1 21Jul2007
SYS_CONTEXTBuiltinFunction 11gR1 19Aug2007
SYS_GUID 11gR1 09Dec2006
SYS_OP_COMBINED_HASH 11gR1 18Aug2008
SYS_OP_DESCEND 11gR1 25Aug2007
SYS_OP_DISTINCT 11gR1 25Aug2007
SYS_OP_GUID 11gR1 25Aug2007
SYS_OP_LBID 11gR1 25Aug2007
SYS_OP_MAP_NONNULL 11gR1 25Aug2007
SYS_OP_RAWTONUM 11gR1 25Aug2007
SYS_OP_RPB 11gR1 25Aug2007
SYS_OP_TOSETID 11gR1 25Aug2007
SYS_TYPEID 11gR1 25Aug2007

System
11gR1 20Sep2008

SystemEvents
11gR1 18Mar2008
SystemEventTriggers 11gR1 06Jan2008

SystemPrivileges
11gR1 08Jan2008

SystemStatistics
11gR1 08Apr2008
TableCollectionExpression 11gR1 30Nov2008
Tables 11gR1 26Nov2008
TableTriggers 11gR1 13Feb2008
Tablespaces 11gR1 23Oct2008
TablespaceGroups 11gR1 22Nov2007
Timestamp 11gR1 20Dec2007
TimeZones 11gR1 20Dec2007
TKPROF 11gR1 04Sep2008
TotalRecall 11gR1 09Aug2007
TraceFileIdentifier 11gR1 19Feb2008
Tracing 11gR1 04Sep2008
TransactionBackout 11gR1 16Oct2007
Transactions 11gR1 15Dec2007
TranslateBuiltinFunction 11gR1 07Aug2007
TransparentDataEncryption 11gR1 29Oct2007
TransportableTablespaces 11gR1 21Jun2008
Truncate(Tables&Partitions) 11gR1 30Jul2007
Tuning 11gR1 15Aug2008
Types 11gR1 02Dec2008
UndoTablespace 11gR1 20Nov2008
UndocumentedOracle 11gR1 17Aug2008
UNIX/vi 09Apr2008
UniqueConstraint 11gR1 25Nov2007
Unpivot 11gR1 02Oct2007
UpdateStatement 11gR1 02Nov2007
USERENV 11gR1 25Aug2007 SeeSYS_CONTEXT
Users 11gR1 22Apr2008
USER_LOCK 11gR1 27Jul2007

Oracle Complete PLSQL Reference 187


Utilities 11gR1 19Nov2008
UTL_COLL 11gR1 29Jul2007
UTL_COMPRESS 11gR1 29Jul2007
UTL_ENCODE 11gR1 10Oct2007
UTL_FILE 11gR1 18Mar2008
UTL_GDK 11gR1 10Oct2007
UTL_HTTP 11gR1 23Jan2008
UTL_I18N 11gR1 27Jul2007
UTL_INADDR 11gR1 07Jul2007
UTL_LMS 11gR1 07Jul2007
UTL_MAIL 11gR1 11Aug2007
UTL_MATCH 11gR1 10Oct2007
UTL_RAW 11gR1 10Oct2007
UTL_RECOMP 11gR1 30Jul2007
UTL_REF 11gR1 31Mar2008
UTL_SMTP 11gR1 18Dec2007 Deprecated:SeeUTL_MAIL
UTL_SPADV 11gR1 18Mar2008
UTL_TCP 11gR1 12Aug2007
UTL_URL 11gR1 11Aug2007
UTL_XML 11gR1 01Apr2008
Variables 11gR1 21Aug2007
VARRAYS 11gR1 01Apr2008
VERSIONSBETWEEN 11gR1 25Aug2007
Views 11gR1 26Oct2007
VirtualColumns 11gR1 18Oct2007
VirtualColumnPartitioning 11gR1 25Nov2007
VirtualIndexes 11gR1 03Nov2008
VirtualPrivateDatabase 11gR1 17May2008
V$Views 11gR1 01Nov2007
WAIT 11gR1 07Jul2007
WhereClause 11gR1 29Jul2007
Wildcards 11gR1 14Sep2007
WITHClause 11gR1 10Feb2008
WM_CONCAT 11gR1 03Dec2007
WorkspaceManager 10gR2 17Dec2005
WPG_DOCLOAD 11gR1 17Dec2007
Wrap 11gR1 05Oct2007
WriteCLOBtofile 11gR1 01Feb2008
XMLFunctions 11gR1 14Sep2007
XMLQuery 11gR1 27Jan2008
XMLTable 11gR1 26Jan2008
XMLTYPE 11gR1 14Jul2007
XMLTables 11gR1 26Jan2008
XMLSCHEMA_NAME_PRESENT 11gR1 17Jun2008

Oracle Complete PLSQL Reference 188


3.builtinPKG

OracleBuiltinPackages
Version11.1

Oracle Complete PLSQL Reference 189


Last
CommonName Owner PackageName
Modified
Undocumented SYS BLAST_CUR 14Dec2007
BSLN
BaselineStatistics DBSNMP
BSLN_INTERNAL

Undocumented ORDSYS CARTRIDGE -


ContextAdministration CTX_ADM *
Context CTX_CATSEARCH
Context CTX_CLS *
Context CTX_CONTAINS
Context CTX_DDL 24Dec2007
Context CTX_DOC *
Context CTXSYS CTX_MATCHES
Context CTX_OUTPUT *
Context CTX_QUERY *
Context CTX_REPORT *
ContextThesaurus CTX_THES *
Context CTX_ULEXER *
Context CTX_XPCONTAINS

ValidatesOLAPInstallation SYS CWM2_OLAP_INSTALLER -


ExportSupportforSQLTuningBase DBMSHSXP Internal
ReplicationObjectGenerator DBMSOBJG 08Jul2007
GeneratePartitionedObjectStorage DBMSOBJG2 Internal
SYS
GenerateandrollbackDDL DBMSOBJGWRAPPER Internal
GenerateDDL DBMSOBJG_DP Internal
Undocumented DBMSZEXP_SYSPKGGRNT Internal

ADDM SYS DBMS_ADDM 16Nov2007


QueryEquivalence SYS DBMS_ADVANCED_REWRITE 11Aug2007
ADDM SYS DBMS_ADVISOR 01Feb2008
AsynchronousMessaging SYS DBMS_ALERT 08Jul2007
MoveOLAPCatalog SYS DBMS_AMD 08Jul2007
Contexts/Security SYS DBMS_APPCTX Internal

RegisterCodeForTracking SYS DBMS_APPLICATION_INFO


06-Jan-
2008
StreamsApplyProcess DBMS_APPLY_ADM 12Dec2007
StreamsApplyProcessInternalProcesses DBMS_APPLY_ADM_INTERNAL Internal
StreamsApplyProcessErrorHandling SYS DBMS_APPLY_ERROR Internal
StreamsInternalNewin11g DBMS_APPLY_POSITION Internal
StreamsInternal DBMS_APPLY_PROCESS Internal

AdvancedQueuingInterface SYS DBMS_AQ 05Nov2007


AdvancedQueuingAdministrator DBMS_AQADM 06Apr2008
UsedbyDBMS_AQADMtomanageStreamsAQ DBMS_AQADM_SYS Internal
AdvancedQueuing DBMS_AQADM_SYSCALLS
Email&HTTPAsynchronousNotification DBMS_AQELM 08Oct2007
SecureAccessToJMSInterfaces DBMS_AQIN *
JMSInterface DBMS_AQJMS
JMSInterfaceInternal DBMS_AQJMS_INTERNAL Internal
AdvancedQueuing DBMS_AQ_BQVIEW
AdvancedQueuing DBMS_AQ_EXP_CMT_TIME_TABLES
AdvancedQueuing DBMS_AQ_EXP_HISTORY_TABLES
AdvancedQueuing DBMS_AQ_EXP_INDEX_TABLES
Oracle Complete PLSQL Reference
AdvancedQueuing 190
Oracle Complete PLSQL Reference 191
Loop Examples Mohamed gamal course
SQL>
SQL>
SQL> -- basic loop
SQL>
SQL>
SQL> select * from dept;

DEPTNO DNAME LOC


---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL>
SQL>
SQL> set serveroutput on;
SQL>
SQL>
SQL>
SQL> create or replace procedure rep1
2
3 is
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7
8 begin
9 select deptno , dnaem , loc
10 into v1 , v2 , v3
11 from dept;
12
13 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3)
14
15 end
16 ;
17 /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
15/1 PLS-00103: Encountered the symbol "END" when expecting one of the
following:
:= . ( % ;
The symbol ";" was substituted for "END" to continue.

Oracle Complete PLSQL Reference 192


SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 select deptno , dnaem , loc
8 into v1 , v2 , v3
9 from dept;
10 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
11 end
12* ;
13 /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
7/1 PL/SQL: SQL Statement ignored
7/17 PL/SQL: ORA-00904: "DNAEM": invalid identifier
SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 select deptno , dname , loc
8 into v1 , v2 , v3
9 from dept;
10 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
11 end
12* ;
SQL> /

Procedure created.

SQL> exex rep1;


SP2-0042: unknown command "exex rep1" - rest of line ignored.
SQL> exec rep1;
BEGIN rep1; END;

*
ERROR at line 1:
Oracle Complete PLSQL Reference 193
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at "SCOTT.REP1", line 7
ORA-06512: at line 1

SQL>
SQL>
SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 begin
8 select deptno , dname , loc
9 into v1 , v2 , v3
10 from dept
11 where deptno = v_counter;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
13 end
14* ;
15 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 begin
8 LOOP
9 select deptno , dname , loc
10 into v1 , v2 , v3
11 from dept
12 where deptno = v_counter;
13 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
14 v_counter := v_counter + 10 ;
15 exit when v_counter = 50;
16 end loop;
Oracle Complete PLSQL Reference 194
17 end
18* ;
19 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 vmax number(5);
8 begin
9 select max(deptno) into vmax from dept;
10 LOOP
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17 exit when v_counter = vmax+1;
18 end loop;
19 end
20* ;
21 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
BEGIN rep1; END;

*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "SCOTT.REP1", line 11
Oracle Complete PLSQL Reference 195
ORA-06512: at line 1

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 vmax number(5);
8 begin
9 select max(deptno) into vmax from dept;
10 LOOP
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17 exit when v_counter > vmax;
18 end loop;
19 end
20* ;
SQL> /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

PL/SQL procedure successfully completed.

SQL> select * from dept;

DEPTNO DNAME LOC


---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL> insert into dept values(50,'a','a');

1 row created.

SQL> ed;
Oracle Complete PLSQL Reference 196
Wrote file afiedt.buf

1* insert into dept values(60,'a','a')


SQL> /

1 row created.

SQL> ed;
Wrote file afiedt.buf

1* insert into dept values(70,'a','a')


SQL> /

1 row created.

SQL> commit;

Commit complete.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a a
60 a a
70 a a

PL/SQL procedure successfully completed.

SQL> update emp set dname = null where deptno = 50;


update emp set dname = null where deptno = 50
*
ERROR at line 1:
ORA-00904: "DNAME": invalid identifier

SQL> ed;
Wrote file afiedt.buf

1* update dept set dname = null where deptno = 50


SQL> /

1 row updated.

SQL> commit;

Commit complete.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
Oracle Complete PLSQL Reference 197
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 a a
70 a a

PL/SQL procedure successfully completed.

SQL> create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 vmax number(5);
8 begin
9 select max(deptno) into vmax from dept;
10 for i in 1..7 loop
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17
18 end loop;
19 end
20 ;
21 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 a a
70 a a

PL/SQL procedure successfully completed.

SQL> select * from dept;

DEPTNO DNAME LOC


---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
Oracle Complete PLSQL Reference 198
60 a a
70 a a

7 rows selected.

SQL> create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 x number(5);
8 begin
9
10 select count(*) into x from dept;
11 for i in 1..x loop
12 select deptno , dname , loc
13 into v1 , v2 , v3
14 from dept
15 where deptno = v_counter;
16 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
17 v_counter := v_counter + 10 ;
18
19 end loop;
20 end
21 ;
22 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 a a
70 a a

PL/SQL procedure successfully completed.

SQL> delete from dept where deptno > 50;

2 rows deleted.

SQL> commit;

Commit complete.

SQL> select * from dept;

DEPTNO DNAME LOC


Oracle Complete PLSQL Reference 199
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a

PL/SQL procedure successfully completed.

SQL> select count(*) from emp;

COUNT(*)
----------
14

SQL> select count(*) from dept;

COUNT(*)
----------
5

SQL> create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 begin
8 while v_counter > 50 loop
9 select deptno , dname , loc
10 into v1 , v2 , v3
11 from dept
12 where deptno = v_counter;
13 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
14 v_counter := v_counter + 10 ;
15
16 end loop;
17 end
18 ;
19 /

Procedure created.

SQL> exec rep1;

Oracle Complete PLSQL Reference 200


PL/SQL procedure successfully completed.

SQL> set serveroutput on;


SQL>
SQL> exec rep1;

PL/SQL procedure successfully completed.

SQL> exec rep1;

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 begin
8 while v_counter < 50 loop
9 select deptno , dname , loc
10 into v1 , v2 , v3
11 from dept
12 where deptno = v_counter;
13 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
14 v_counter := v_counter + 10 ;
15 end loop;
16 end
17* ;
18 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
Oracle Complete PLSQL Reference 201
6 v_counter number(5) := 10;
7 x number(5);
8 begin
9 select max(deptno) into x from dept
10 while v_counter < x loop
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17 end loop;
18 end
19* ;
SQL> /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
9/1 PL/SQL: SQL Statement ignored
10/7 PL/SQL: ORA-00933: SQL command not properly ended
17/5 PLS-00113: END identifier 'LOOP' must match 'REP1' at line 1,
column 11

18/1 PLS-00103: Encountered the symbol "END"


SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 x number(5);
8 begin
9 select max(deptno) into x from dept;
10 while v_counter < x loop
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17 end loop;
18* end;
SQL> /

Oracle Complete PLSQL Reference 202


Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

PL/SQL procedure successfully completed.

SQL> select * from dept;

DEPTNO DNAME LOC


---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a

SQL> create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 x number(5);
8 begin
9 select max(deptno) into x from dept;
10 while v_counter < x loop
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17 end loop;
18 end;
19 /

Procedure created.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 v_counter number(5) := 10;
7 x number(5);
Oracle Complete PLSQL Reference 203
8 begin
9 select max(deptno) into x from dept;
10 while v_counter <= x loop
11 select deptno , dname , loc
12 into v1 , v2 , v3
13 from dept
14 where deptno = v_counter;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
16 v_counter := v_counter + 10 ;
17 end loop;
18* end;
SQL> /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a

PL/SQL procedure successfully completed.

SQL> insert into dept values (60,'b','b');

1 row created.

SQL> commit;

Commit complete.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 b b

PL/SQL procedure successfully completed.

SQL> select * from emp;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- --------- ---------- -------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17/12/80 800 20
7499 ALLEN SALESMAN 7698 20/02/81 1600 300 30
7521 WARD SALESMAN 7698 22/02/81 1250 500 30
7566 JONES MANAGER 7839 02/04/81 2975 20
7654 MARTIN SALESMAN 7698 28/09/81 1250 1400 30
7698 BLAKE MANAGER 7839 01/05/81 2850 30
Oracle Complete PLSQL Reference 204
7782 CLARK MANAGER 7839 09/06/81 2450 10
7788 SCOTT ANALYST 7566 19/04/87 3000 20
7839 KING PRESIDENT 17/11/81 5000 10
7844 TURNER SALESMAN 7698 08/09/81 1500 0 30
7876 ADAMS CLERK 7788 23/05/87 1100 20
7900 JAMES CLERK 7698 03/12/81 950 30
7902 FORD ANALYST 7566 03/12/81 3000 20
7934 MILLER CLERK 7782 23/01/82 1300 10

14 rows selected.

SQL> create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6
7 begin
8
9 for i in 1..14 loop
10
11 select empno , ename , job
12 into v1 , v2 , v3
13 from emp;
14 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
15
16 end loop;
17 end;
18 /

Procedure created.

SQL> exec rep1;


BEGIN rep1; END;

*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at "SCOTT.REP1", line 11
ORA-06512: at line 1

SQL> select empno , ename , job from emp;

EMPNO ENAME JOB


---------- ---------- ---------
7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
Oracle Complete PLSQL Reference 205
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

14 rows selected.

SQL> create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6
7 begin
8
9 for i in (select empno , ename , job from emp) loop
10 select empno , ename , job
11 into v1 , v2 , v3
12 from emp;
13 dbms_output.put_line(I.v1 || ' ' || I.v2 || ' ' || I.v3);
14
15 end loop;
16 end
17 ;
18 /

Warning: Procedure created with compilation errors.

SQL> SHOW ERR;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
13/1 PL/SQL: Statement ignored
13/24 PLS-00302: component 'V1' must be declared
SQL> ED;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 for i in (select empno , ename , job from emp) loop
8 select empno , ename , job
9 into v1 , v2 , v3
10 from emp;
Oracle Complete PLSQL Reference 206
11 dbms_output.put_line(i.v1 || ' ' || i.v2 || ' ' || i.v3);
12 end loop;
13 end
14* ;
15 /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
11/1 PL/SQL: Statement ignored
11/24 PLS-00302: component 'V1' must be declared
SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 for i in (select empno , ename , job from emp) loop
8 select empno , ename , job
9 into i.v1 , i.v2 , i.v3
10 from emp;
11 dbms_output.put_line(i.v1 || ' ' || i.v2 || ' ' || i.v3);
12 end loop;
13 end
14* ;
SQL> /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
8/1 PL/SQL: SQL Statement ignored
9/8 PLS-00302: component 'V1' must be declared
9/25 PL/SQL: ORA-00904: : invalid identifier
11/1 PL/SQL: Statement ignored
11/24 PLS-00302: component 'V1' must be declared
SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
Oracle Complete PLSQL Reference 207
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 for i in (select empno , ename , job from emp) loop
8 select empno , ename , job
9 into v1,v2,v3
10 from emp;
11 dbms_output.put_line(i.v1 || ' ' || i.v2 || ' ' || i.v3);
12 end loop;
13 end
14* ;
SQL> /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
11/1 PL/SQL: Statement ignored
11/24 PLS-00302: component 'V1' must be declared
SQL>
SQL>
SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 for i in (select empno , ename , job from emp) loop
8 dbms_output.put_line(i.v1 || ' ' || i.v2 || ' ' || i.v3);
9 end loop;
10 end
11* ;
SQL> /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
8/1 PL/SQL: Statement ignored
8/24 PLS-00302: component 'V1' must be declared
SQL>
SQL> ed;
Wrote file afiedt.buf
Oracle Complete PLSQL Reference 208
1 create or replace procedure rep1
2 is
3 begin
4 for i in (select empno , ename , job from emp) loop
5 dbms_output.put_line(i.empno || ' ' || i.ename || ' ' || i.job);
6 end loop;
7 end
8* ;
SQL> /

Procedure created.

SQL> exec rep1;


7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

PL/SQL procedure successfully completed.

SQL>
SQL>
SQL> create or replace procedure rep1
2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 for i in (select empno , ename , job from emp) loop
8 dbms_output.put_line(i.v1 || ' ' || i.v2 || ' ' || i.v3)
9 end loop;
10 end
11 ;
12 /

Warning: Procedure created with compilation errors.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


Oracle Complete PLSQL Reference 209
2 is
3 v1 number(5);
4 v2 varchar2(20);
5 v3 varchar2(20);
6 begin
7 for i in (select empno , ename , job from emp) loop
8 v1 := i.empno;
9 v2 := i.ename;
10 v3 := i.job;
11 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3);
12 end loop;
13 end
14* ;
SQL> /

Procedure created.

SQL> exec rep1;


7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

PL/SQL procedure successfully completed.

SQL>
SQL>
SQL> spool off;

Oracle Complete PLSQL Reference 210


Cursor Example Mohamed gamal course
============

SQL>
SQL>
SQL>
SQL> select * FROM DEPT;

DEPTNO DNAME LOC


---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 b b

6 rows selected.

SQL>
SQL>
SQL> create or replace procedure rep1
2 is
3
4 cursor zozo is select deptno , dname , loc from dept;
5
6 v1 number(5);
7 v2 varchar2(20);
8 v3 varchar2(20);
9
10
11 begin
12 open zozo;
13
14 fetch zozo into v1,v2,v3;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 );
16
17 close zozo;
18
19 end ;
20 /

Procedure created.

SQL> exec rep1;


10 ACCOUNTING NEW YORK

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

Oracle Complete PLSQL Reference 211


1 create or replace procedure rep1
2 is
3 cursor zozo is select deptno , dname , loc from dept;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 begin
8 open zozo;
9 for i in 1..6 loop
10 fetch zozo into v1,v2,v3;
11 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 );
12 end loop;
13 close zozo;
14* end ;
15 /

Procedure created.

SQL> exe crep1;


SP2-0042: unknown command "exe crep1" - rest of line ignored.
SQL> exec rep1;
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 b b

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor zozo is select deptno , dname , loc from dept;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 x number(5);
8 begin
9 select count(*) into x from dept;
10 open zozo;
11 for i in 1..x loop
12 fetch zozo into v1,v2,v3;
13 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 );
14 end loop;
15 close zozo;
16* end ;
17 /

Procedure created.
Oracle Complete PLSQL Reference 212
SQL> exec rep1;
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 a
60 b b

PL/SQL procedure successfully completed.

SQL> delete from dept where deptno >=50;

2 rows deleted.

SQL> commit;

Commit complete.

SQL> exec rep1;


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

PL/SQL procedure successfully completed.

SQL> select * from emp;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- --------- ---------- -------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17/12/80 800 20
7499 ALLEN SALESMAN 7698 20/02/81 1600 300 30
7521 WARD SALESMAN 7698 22/02/81 1250 500 30
7566 JONES MANAGER 7839 02/04/81 2975 20
7654 MARTIN SALESMAN 7698 28/09/81 1250 1400 30
7698 BLAKE MANAGER 7839 01/05/81 2850 30
7782 CLARK MANAGER 7839 09/06/81 2450 10
7788 SCOTT ANALYST 7566 19/04/87 3000 20
7839 KING PRESIDENT 17/11/81 5000 10
7844 TURNER SALESMAN 7698 08/09/81 1500 0 30
7876 ADAMS CLERK 7788 23/05/87 1100 20
7900 JAMES CLERK 7698 03/12/81 950 30
7902 FORD ANALYST 7566 03/12/81 3000 20
7934 MILLER CLERK 7782 23/01/82 1300 10

14 rows selected.

SQL> create or replace procedure rep1


2 is
3
4 cursor omar is select empno , ename , job from dept;
Oracle Complete PLSQL Reference 213
5
6 v1 number(5);
7 v2 varchar2(20);
8 v3 varchar2(20);
9
10
11 begin
12 open omar;
13
14 fetch omar into v1,v2,v3;
15 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 );
16
17 close omar;
18
19 end ;
20 /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
4/16 PL/SQL: SQL Statement ignored
4/39 PL/SQL: ORA-00904: "JOB": invalid identifier
SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job from emp;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 begin
8 open omar;
9 fetch omar into v1,v2,v3;
10 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 );
11 close omar;
12* end ;
13 /

Procedure created.

SQL> exec rep1;


7369 SMITH CLERK

PL/SQL procedure successfully completed.

Oracle Complete PLSQL Reference 214


SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job from emp;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 begin
8 open omar;
9 for i in 1..14 loop
10 fetch omar into v1,v2,v3;
11 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 );
12 end loop;
13 close omar;
14* end ;
15 /

Procedure created.

SQL> exec rep1;


7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job, sal from emp;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..14 loop
Oracle Complete PLSQL Reference 215
11 fetch omar into v1,v2,v3, v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 '' || v4 );
13 end loop;
14 close omar;
15* end ;
SQL> /

Warning: Procedure created with compilation errors.

SQL> show err;


Errors for PROCEDURE REP1:

LINE/COL ERROR
-------- -----------------------------------------------------------------
12/52 PLS-00103: Encountered the symbol "" when expecting one of the
following:
. ( ) , * @ % & | = - + < / > at in is mod remainder not rem
=> .. <an exponent (**)> <> or != or ~= >= <= <> and or like
LIKE2_ LIKE4_ LIKEC_ as between from using || member
SUBMULTISET_
The symbol "(" was substituted for "" to continue.

12/62 PLS-00103: Encountered the symbol ";" when expecting one of the
following:
. ( ) , * % & | = - + < / > at in is mod remainder not rem =>
.. <an exponent (**)> <> or != or ~= >= <= <> and or like
LIKE2_ LIKE4_ LIKEC_ as between from using || member
SUBMULTISET_
The symbol ")" was substituted for ";" to continue.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..14 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
13 end loop;
14 close omar;
15* end ;
SQL> /

Procedure created.

Oracle Complete PLSQL Reference 216


SQL> exec rep1;
7369 SMITH CLERK 800
7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7844 TURNER SALESMAN 1500
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp order by sal desc;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..14 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
13 end loop;
14 close omar;
15* end ;
SQL> /

Procedure created.

SQL> exec rep1;


7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7788 SCOTT ANALYST 3000
7566 JONES MANAGER 2975
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7499 ALLEN SALESMAN 1600
7844 TURNER SALESMAN 1500
7934 MILLER CLERK 1300
7521 WARD SALESMAN 1250
7654 MARTIN SALESMAN 1250
Oracle Complete PLSQL Reference 217
7876 ADAMS CLERK 1100
7900 JAMES CLERK 950
7369 SMITH CLERK 800

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp order by sal desc;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..5 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
13 end loop;
14 close omar;
15* end ;
SQL> /

Procedure created.

SQL> exec rep1;


7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7788 SCOTT ANALYST 3000
7566 JONES MANAGER 2975
7698 BLAKE MANAGER 2850

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp order by sal asc;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..5 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
Oracle Complete PLSQL Reference 218
13 end loop;
14 close omar;
15* end ;
SQL> /

Procedure created.

SQL> exec rep1;


7369 SMITH CLERK 800
7900 JAMES CLERK 950
7876 ADAMS CLERK 1100
7521 WARD SALESMAN 1250
7654 MARTIN SALESMAN 1250

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = 10;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..14 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
13 end loop;
14 close omar;
15* end ;
SQL> /

Procedure created.

SQL> exec rep1;


7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
7934 MILLER CLERK 1300
Oracle Complete PLSQL Reference 219
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> select * from emp where deptno = 10;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- --------- ---------- -------- ---------- ---------- ----------
7782 CLARK MANAGER 7839 09/06/81 2450 10
7839 KING PRESIDENT 17/11/81 5000 10
7934 MILLER CLERK 7782 23/01/82 1300 10

SQL> ed;
Wrote file afiedt.buf

1* select * from emp where deptno = 10


SQL>
SQL>
SQL> create or replace procedure rep1
2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = 10;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..14 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
13 end loop;
14 close omar;
15 end ;
16 /

Procedure created.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = 10;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 begin
9 open omar;
10 for i in 1..3 loop
11 fetch omar into v1,v2,v3,v4;
12 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
Oracle Complete PLSQL Reference 220
13 end loop;
14 close omar;
15* end ;
SQL> /

Procedure created.

SQL> exec rep1;


7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = 10;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = 10;
11 open omar;
12 for i in 1..x loop
13 fetch omar into v1,v2,v3,v4;
14 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
15 end loop;
16 close omar;
17* end ;
SQL> /

Procedure created.

SQL> exec rep1;


7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> update emp set deptno = 10 where ename = 'FORD';

1 row updated.

SQL> commit;

Commit complete.
Oracle Complete PLSQL Reference 221
SQL> exec rep1;
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1* commit
SQL> /

Commit complete.

SQL> create or replace procedure rep1


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = 10;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = 10;
11 open omar;
12 for i in 1..x loop
13 fetch omar into v1,v2,v3,v4;
14 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
15 end loop;
16 close omar;
17 end ;
18 /

Procedure created.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
Oracle Complete PLSQL Reference 222
12 for i in 1..x loop
13 fetch omar into v1,v2,v3,v4;
14 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
15 end loop;
16 close omar;
17* end ;
SQL> /

Procedure created.

SQL> exec rep1(10);


7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> exec rep1(20);


7369 SMITH CLERK 800
7566 JONES MANAGER 2975
7788 SCOTT ANALYST 3000
7876 ADAMS CLERK 1100

PL/SQL procedure successfully completed.

SQL> exec rep1(30);


7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7654 MARTIN SALESMAN 1250
7698 BLAKE MANAGER 2850
7844 TURNER SALESMAN 1500
7900 JAMES CLERK 950

PL/SQL procedure successfully completed.

SQL>
SQL>
SQL>
SQL>
SQL>
SQL> --%ISOPEN
SQL>
SQL> --%FOUND
SQL>
SQL> --%NOT FOUND
SQL>
SQL> --%rowcount
SQL>
SQL>
SQL>
SQL> ed;
Oracle Complete PLSQL Reference 223
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 if NOT omar%isopen then
12 dbms_output.put_line('Cursor Omar is not opened yet . please wait ');
13 end if;
14 open omar;
15 if omar%isopen then
16 dbms_output.put_line('Cursor Omar is opened successfully .please wait to fetch ');
17 end if;
18 for i in 1..x loop
19 fetch omar into v1,v2,v3,v4;
20 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
21 end loop;
22 close omar;
23* end ;
24 /

Procedure created.

SQL> exec rep1(10);


Cursor Omar is not opened yet . please wait
Cursor Omar is opened successfully .please wait to fetch
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
Oracle Complete PLSQL Reference 224
11 if NOT omar%isopen then
12 dbms_output.put_line('Cursor Omar is not opened yet . please wait ');
13 end if;
14 open omar;
15 if omar%isopen then
16 dbms_output.put_line('Cursor Omar is opened successfully .please wait to fetch ');
17 end if;
18 for i in 1..x loop
19 fetch omar into v1,v2,v3,v4;
20 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
21 end loop;
22 close omar;
23 dbms_output.put_line('Cursor Omar is closed . bye bye ');
24* end ;
25 /

Procedure created.

SQL> exec rep1(20);


Cursor Omar is not opened yet . please wait
Cursor Omar is opened successfully .please wait to fetch
7369 SMITH CLERK 800
7566 JONES MANAGER 2975
7788 SCOTT ANALYST 3000
7876 ADAMS CLERK 1100
Cursor Omar is closed . bye bye

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
12 for i in 1..x loop
13 fetch omar into v1,v2,v3,v4;
14 if omar%found then
15 dbms_output.put_line('fe bayanat estana 7ageb7alak');
16 end if;
17 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
18 end loop;
19 close omar;
20* end ;
Oracle Complete PLSQL Reference 225
21 /

Procedure created.

SQL> exec rep1(10);


fe bayanat estana 7ageb7alak
7782 CLARK MANAGER 2450
fe bayanat estana 7ageb7alak
7839 KING PRESIDENT 5000
fe bayanat estana 7ageb7alak
7902 FORD ANALYST 3000
fe bayanat estana 7ageb7alak
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
12 for i in 1..x loop
13 fetch omar into v1,v2,v3,v4;
14 if omar%NOTfound then
15 dbms_output.put_line('mafesh bayanat mesh 7ageb7alak');
16 end if;
17 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
18 end loop;
19 close omar;
20* end ;
SQL> /

Procedure created.

SQL> exec rep1(70);

PL/SQL procedure successfully completed.

SQL> exec rep1(40);

PL/SQL procedure successfully completed.

SQL> ed;
Oracle Complete PLSQL Reference 226
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
12 for i in 1..x+1 loop
13 fetch omar into v1,v2,v3,v4;
14 if omar%NOTfound then
15 dbms_output.put_line('mafesh bayanat mesh 7ageb7alak');
16 end if;
17 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
18 end loop;
19 close omar;
20* end ;
SQL> /

Procedure created.

SQL> exec rep1(10);


7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300
mafesh bayanat mesh 7ageb7alak
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> select * from emp order by deptno ;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- --------- ---------- -------- ---------- ---------- ----------
7782 CLARK MANAGER 7839 09/06/81 2450 10
7902 FORD ANALYST 7566 03/12/81 3000 10
7839 KING PRESIDENT 17/11/81 5000 10
7934 MILLER CLERK 7782 23/01/82 1300 10
7369 SMITH CLERK 7902 17/12/80 800 20
7788 SCOTT ANALYST 7566 19/04/87 3000 20
7566 JONES MANAGER 7839 02/04/81 2975 20
7876 ADAMS CLERK 7788 23/05/87 1100 20
7499 ALLEN SALESMAN 7698 20/02/81 1600 300 30
7521 WARD SALESMAN 7698 22/02/81 1250 500 30
7844 TURNER SALESMAN 7698 08/09/81 1500 0 30
7698 BLAKE MANAGER 7839 01/05/81 2850 30
Oracle Complete PLSQL Reference 227
7654 MARTIN SALESMAN 7698 28/09/81 1250 1400 30
7900 JAMES CLERK 7698 03/12/81 950 30

14 rows selected.

SQL> create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
12 for i in 1..x+1 loop
13 fetch omar into v1,v2,v3,v4;
14 if omar%NOTfound then
15 dbms_output.put_line('mafesh bayanat mesh 7ageb7alak');
16 end if;
17 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
18 end loop;
19 close omar;
20 end ;
21 /

Procedure created.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
12 for i in 1..x+5 loop
13 fetch omar into v1,v2,v3,v4;
14 if omar%NOTfound then
15 dbms_output.put_line('mafesh bayanat mesh 7ageb7alak');
16 end if;
17 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
18 end loop;
19 close omar;
20* end ;
Oracle Complete PLSQL Reference 228
SQL> /

Procedure created.

SQL> exec rep1(10);


7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300
mafesh bayanat mesh 7ageb7alak
7934 MILLER CLERK 1300
mafesh bayanat mesh 7ageb7alak
7934 MILLER CLERK 1300
mafesh bayanat mesh 7ageb7alak
7934 MILLER CLERK 1300
mafesh bayanat mesh 7ageb7alak
7934 MILLER CLERK 1300
mafesh bayanat mesh 7ageb7alak
7934 MILLER CLERK 1300

PL/SQL procedure successfully completed.

SQL> ed;
Wrote file afiedt.buf

1 create or replace procedure rep1(m number)


2 is
3 cursor omar is select empno , ename , job , sal from emp where deptno = m;
4 v1 number(5);
5 v2 varchar2(20);
6 v3 varchar2(20);
7 v4 number(5);
8 x number(5);
9 begin
10 select count(*) into x from emp where deptno = m;
11 open omar;
12 for i in 1..x loop
13 fetch omar into v1,v2,v3,v4;
14 dbms_output.put_line(v1 || ' ' || v2 || ' ' || v3 ||' ' || v4 );
15 end loop;
16 dbms_output.put_line(omar%rowcount || '' || 'records');
17 close omar;
18* end ;
SQL> /

Procedure created.

Oracle Complete PLSQL Reference 229


SQL> exec rep1(10);
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7934 MILLER CLERK 1300
4records

PL/SQL procedure successfully completed.

SQL> exec rep1(20);


7369 SMITH CLERK 800
7566 JONES MANAGER 2975
7788 SCOTT ANALYST 3000
7876 ADAMS CLERK 1100
4records

PL/SQL procedure successfully completed.

SQL> exec rep1(30);


7499 ALLEN SALESMAN 1600
7521 WARD SALESMAN 1250
7654 MARTIN SALESMAN 1250
7698 BLAKE MANAGER 2850
7844 TURNER SALESMAN 1500
7900 JAMES CLERK 950
6records

PL/SQL procedure successfully completed.

SQL> spool off;

Oracle Complete PLSQL Reference 230


Oracle Complete PLSQL Reference 231

Anda mungkin juga menyukai