Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
41 views28 pages

Unit Iv

Uploaded by

kapama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views28 pages

Unit Iv

Uploaded by

kapama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT - IV

PL/SQL : Approach and Advantages - PL/SQL Blocks - variables -


Manipulating Data - Procedural Constructs - Exception handling - Program
Units in Oracle Forms - PL/SQL Editor.

PL/SQL:
PL/SQL is Oracle’s Procedural Block structured language that enables
developers to code procedures functions and blocks.

What Is PL/SQL?
PL/SQL stands for "Procedural Language extensions to SQL. PL/SQL
is closely integrated into the SQL language. PL/SQL allows you to combine SQL
statements with "standard" procedural constructs.

PL/SQL can be embedded in application program using two methods


1. Anonymous PL/SQL blocks of SQL statements, which are processed
together in one call to the database.
2. Procedures and functions can be created in PL/SQL that combines
multiple SQL statements with procedural processing. A call to a
procedure is treated as a single call to the database.
Blocks are used to group logically related declarations and statements.
Parameters can be passed to these blocks, enabling procedures and
functions to accept and return values.

Advantages of PL/SQL
 Support for SQL
SQL is very flexible, powerful and non-procedural. it is easy
to learn. Thus making it easy to manipulate data stored in relational
database.PL/SQL uses all SQL data manipulation, cursor control and
transaction control commands.
 Improved Performance
In PL/SQL, an entire block of statements can be sent to the
RDBMS at one time, whereas SQL statements are processed one at a
time.thus, PL/SQL block statements drastically reduce communication
between the application and Oracle.
PL/SQL improves server performance by reducing the
number of calls from application to oracle. The applications pass numerous
SQL statements or block of statements, to Oracle server at one time instead
of passing each statement individually. This reduces network traffic between
application and Oracle server.
PL/SQL packages-containing procedures and functions can
be created and stored in the Oracle database, so that they can be used by
multiple application programs. Using PL/SQL minimizes Recompilation
work and reduces Disk I/O because related functions and procedures are
stored together.

Individual SQL statements PL/SQL block

Block

User User/Application

Oracle Server
Oracle Server
 Portability
PL/SQL code can be ported to any operating system and
platform on which Oracle runs.
 Integration with Oracle
PL/SQL has been designed to integrate closely with Oracle
database system and enhance SQL’s features. Therefore it supports all the
internal data types of Oracle database ANSI SQL.

PL/SQL Blocks:
A standard PL/SQL code segment is called a block.
Conceptually; a block can consist of three parts, or sections:
 A declarative section for declaring variables, constants. it is optional.
 An Executable section which consists of executable statements. The
executable statements consist of either SQL statements,PL/SQL
procedural statements or both. This section is mandatory.
 An exception handling section for handling errors. It is optional.

Declaration section

Executable Section

Exception handling Section


Sections of a block
The order of the blocks in the code segment is
logical. Blocks begin with the declarative part in which objects can be declared.
Once declared, objects can be manipulated in the executable part. Errors
raised during execution can be dealt within the exception handling part.

The structure of a PL/SQL block is as shown below:


DECLARE
Declarative Section
BEGIN
EXCEPTION
Error handling Section
END;

DECLARE signals the start of a blocks declarative part. Variables and other
objects are declared in this region.
BEGIN signals the start of a block’s executable part. A block must contain at
least one executable statement.
END signals the end of block.

Example:

The PL/SQL Character Set

A PL/SQL program consists of a sequence of statements, each of which is made


up of one or more lines of text. Text is made up of combinations of the
characters shown in
Table 2.1: PL/SQL Character Set
Type Characters
Letters A-Z, a-z
Digits 0-9
Symbols ~!@#$%&*()_-+=|[]{}:;"'<>,.?/
Whitespace Tab, space, carriage return

Note that PL/SQL is a case-insensitive language. Uppercase letters are treated


the same way as lowercase letters except when the characters are surrounded
by single quotes (when they are literal strings) or represent the value of a
character variable.

Every valid statement in PL/SQL, from declaration to executable statement to


keyword, is made up of various combinations of the above characters. Now you
just have to figure out how to put them all together!

A number of these characters -- both singly and in combination with other


characters -- have a special significance in PL/SQL. Table 2.2 lists these
special symbols.

Table 2.2: Simple and Compound Symbols in PL/SQL


Symbol Description
; Semicolon: statement terminator
% Percent sign: attribute indicator (cursor attributes like %ISOPEN and
indirect declaration attributes like %ROWTYPE). Also used as
multibyte wildcard symbol, as in SQL.
_ Single underscore: single-byte wildcard symbol, as in SQL
: Colon: host variable indicator, such as :block.item in Oracle Forms
** Double asterisk: exponentiation operator
< > and ! "Not equals"
=
|| Double vertical bar: concatenation operator
<< and Label delimiters
>>
<= and Relational operators
>=
Table 2.2: Simple and Compound Symbols in PL/SQL
Symbol Description
:= Assignment operator
=> Association operator for positional notation
-- Double dash: single-line comment indicator
/* and Beginning and ending multiline comment block delimiters
*/

LOB Datatypes

PL/SQL supports a number of large object (LOB) datatypes, which can store
objects of up to four gigabytes of data. Unlike the scalar datatypes, variables
declared for LOBs use locators, or pointers to the actual data. LOBs are
manipulated in PL/SQL using the built-in package DBMS_LOB. The LOB
datatypes are:

BFILE : File locators pointing to read-only large binary objects in operating


system files. With BFILEs, the large objects are outside the database.
BLOB : LOB locators that point to large binary objects inside the database.
CLOB : LOB locators that point to large character (alphanumeric) objects
inside the database.
NCLOB :LOB locators that point to large national character set objects inside
the database.

Variables:
 Variables are used to store the result of a query or calculation.
 Variables must be declared before use.
 DEFAULT reserve word is used to initialize variables and constants.

Declaring variables
 Declaration allocates storage space for a value, specify its datatype.
 Variables are declared in the DECLARE section of the PL/SQL block.
 Declaration involves the name of the variable followed by its
datatype.All statements must end with a semicolon.
 Initial values can also be assigned to a variable at the time of
declaration.
 To assign a value to a variable, the assignment operator ‘:=’ is used.

The general syntax is :< var-name> <type> [:=< value>];


Example:
Name char (20);
Age number (3);
Deptno number (4):=30;

Using DEFAULT
The reserved word DEFAULT can be used instead of the
assignment operator to initialize variables. For eg., the declarations
Deptno number (4):=30;
Can be rewritten as follows:
Deptno number (4) DEFAULT 30;

Using %Type
To avoid type and size conflict between a variable and the
column of a table, the attribute %TYPE is used.
Example:
empname emp.ename%type;

Here, the variable tempname will be of the same size and type as that of the
ename column of EMP table.

Using %Rowtype
The %Rowtype attribute provides a record type that represents
a row in a table. The record can store an entire row of data selected from the
table. Variables for the entire row of a table need to be declared, then instead of
declaring them individually, the attribute %ROWTYPE is used:

Emprowvar EMP%Rowtype;

Here, the variable emprowvar will be a composite variable, consisting of the


column names of the table as its members. To refer to a specific variable, say
sal, the following syntax will be used:

Emprowvar.sal:=5000;

A %ROWTYPE declaration cannot include an initialization clause.

MANIPULATING DATA USING PL/SQL


Data in PL/SQL blocks can be selected and manipulated using the
following SQL language statements:
 SELECT ,INSERT, UPDATE, DELETE, COMMIT, and ROLLBACK.
These are also the only SQL commands that can be used in a PL/SQL
block.
 DDL (Data Definition Language) statements such as CREATE and
DROP.
 DCL (Data Control Language) statements such as ROLLBACK and
COMMIT cannot be used directly.

SELECT statements in PL/SQL are similar to the SQL language. They may
contain clauses like SELECT,FROM WHERE,GROUP BY, and ORDER BY.

SQL Statements
The ability to use SQL within a PL/SQL program is one of PL/SQL’s major
strengths. By adding the ability to use variables in SQL code, PL/SQL becomes
a powerful and robust language that can take full advantage of complex Oracle
databases.

SQL used in a PL/SQL program differs from “standard” SQL in the following
important ways:
• The INTO keyword permits data to be read from a database table and placed
into a PL/SQL variable or record.
• PL/SQL variables may be used anywhere a constant or expression would be
permitted, including in the WHERE clause. Thus, although the names of tables
and columns must be known when the code is written, the values for columns
and other expressions need not be.
• SQL statements executed in PL/SQL do not return data to the screen or other
output device.
The specific syntax for each permitted SQL statement is presented below, with
two exceptions. COMMIT and ROLLBACK are the same as in standard SQL, so
their syntax is not repeated.

SELECT
Selects data from an Oracle table (or view), and places the result in a PL/SQL
record or into one or more PL/SQL variables.

Syntax:
SELECT select_list
INTO {pl/sql_record | variable [, variable…]}
FROM table_list
[WHERE where_clause]; Associates, Inc. All rights erved.

Keywords
select_list :Specifies the list of columns to be retrieved by the statement.

pl/sql_record : Specifies the name of a PL/SQL record to receive the data


returned by the SELECT statement. The record must contain exactly the same
number of variables as are listed in the select list, and their types must be
compatible. If the datatype of a field in the record differs from the
corresponding column in the select list, the two types must be compatible
enough for Oracle to implicitly convert from one to the other.
table_list : Specifies the name of one or more tables from which data will be
selected.
Variable : Specifies the name of a previously declared PL/SQL variable. There
must be exactly the same number of variables as columns in the select list,
and each must be of the same (or compatible) type.
where_clause : Specifies the WHERE conditions for this SELECT. Expressions
in the WHERE clause may include previously declared PL/SQL variables.

Example
This example retrieves KING’s row from the emp table and places the values for
hiredate, sal, and comm into the corresponding PL/SQL variables:

DECLARE
t_hiredate DATE;
t_salary NUMBER;
t_commission NUMBER;
BEGIN
SELECT hiredate, sal, commghINTO t_hiredate, t_salary, t_commission
FROM scott.emp
WHERE ename = 'KING';
END;

INSERT
Inserts a new data row into the specified table, providing values for each
specified column. Alternatively takes the results from a query, and inserts
them into the specified table.

SYNTAX
INSERT INTO [schema.]table (column[,column…])
VALUES ({expression[,expression…] | select_statement});

Keywords
Schema : The name of the schema that contains table. If omitted, the current
schema is used.
Table : Specifies the name of a table into which new rows will be inserted.
Column : Specifies the name of a column in table that will receive data specified
in the VALUES clause.
Expression : Specifies a valid PL/SQL expression, which may contain a
previously declared PL/SQL variable or record type.
select_statement : Specifies that the data to be inserted is the result of this
SELECT statement. The SELECT statement must return one column for each
column listed in the INSERT INTO clause, and the types must be compatible.
Example
The code in the following PL/SQL block inserts a new row into the emp table:
BEGIN
INSERT INTO emp (empno, ename, sal)
VALUES (1111, 'Gennick', 2500);
END;

UPDATE
UPDATE [schema.]table
SET {column = expression[,column = expression…] |
column[,column…] = (select_statement)
} © 200All rights reserved.
WHERE {where_clause | cursor_name};

Keywords
Schema : The name of the schema that contains table. If omitted, the current
schema is used Specifies the name of a table for which rows will be updated.
Column : Specifies the name of a column in the table being updated.
Expression : Any valid SQL expression.
select_statement : Any valid SELECT statement, which must return the
appropriate number and type of data elements. SELECT statements used in
the SET clause must be enclosed within parentheses.
where_clause : Specifies the WHERE conditions for this update. Expressions in
the WHERE clause may include previously declared PL/SQL variables.
cursor_name : Specifies the name of a PL/SQL cursor used to fetch data from
the table being updated.

Example
The following example updates the records of all employees who work for
employee number 7788 and doubles their salaries:
BEGIN
UPDATE emp
SET sal = sal * 2
WHERE mgr = 7788;
END;

The following, more complex UPDATE statement, sets the salary of each
employee to 90 percent of their manager’s salary. Employees without managers
do not receive a salary adjustment:

BEGIN
UPDATE emp e2000 O’Reilly & Associates, Inc. All rights reserved.
SET sal = (SELECT sal * 0.90
FROM emp m
WHERE e.mgr = m.empno)
WHERE mgr IS NOT NULL;
END;

DELETE : Deletes one or more rows of a table.

SYNTAX:
DELETE FROM [schema.]table
WHERE {where_clause | cursor_name};

Keywords
Schema : The name of the schema that contains table. If omitted, the current
schema is used.
Table : Specifies the name of a table from which rows will be deleted.
where_clause : Specifies the WHERE conditions for this delete. Expressions in
the WHERE clause may include previously declared PL/SQL variables.
cursor_name : Specifies the name of a PL/SQL cursor used to fetch data from
the specified table.

Example
The following example deletes managers who make too much money:

BEGIN
DELETE FROM emp m
WHERE empno IN (SELECT mgr FROM emp)
AND sal * 0.90 > (SELECT MAX(sal)
FROM emp e
WHERE e.mgr = m.empno);
END;

PROCEDURAL CONSTRUCTS

Control Statements
PL/SQL control statements are used to control the execution behavior of a
PL/SQL block. The existence of control statements provides PL/SQL with its
procedural, or third-generation, capabilities. These capabilities distinguish it
from SQL.

IF-THEN-ELSE : Executes one or more statements based on the logical


evaluation of Boolean expressions.

SYNTAX:
IF expression THEN
statement;[statement; ...]
[ELSIF expression THEN
statement;[statement; ...]
[ELSIF expression THEN
statement;[statement; ...] ...]
]
[ELSE
statement;[statement; ...]]
END IF;

Keywords
IF : Required keyword that indicates the beginning of conditional processing.
Expression Any valid PL/SQL expression returning a Boolean result.
THEN : A required keyword indicating that the statement(s) to follow will be
executed if expression evaluates to TRUE.
Statement : Any valid PL/SQL assignment statement, SQL statement,
procedure call, or function call.
ELSIF : Optional keyword indicating an alternative expression to be evaluated if
the primary expression is FALSE. If the ELSIF expression is evaluated and is
TRUE, the statements following the ELSIF will be executed. As many alternate
conditions (ELSIF) may be specified as are required.
ELSE : Optional keyword preceding statements to be executed in the event that
none of the IF or ELSIF expressions evaluate to TRUE.
END IF : Required keyword that indicates the end of the IF statement. Each IF
must be ended by only one END IF keyword.

Example
In the following example, salaries are adjusted and bonuses are awarded
according to the initial value of an employee’s salary per pay period. If the
salary is less then $1000, a 10 percent raise is given (salary * 1.10), but no
bonus is awarded. Salaries between $1001 and $1500 get an 8 percent raise
and a $500 bonus. Salaries between $1501 and $2000 get a 5 percent raise
and a $750 bonus. Everyone else—those with salaries over $2000—gets a 2
percent raise and a $1000 bonus:

IF salary < 1000 THEN


salary := salary * 1.10;
bonus := 0;
ELSIF salary BETWEEN 1001 AND 1500 THENCopyright © 2000 O’Reilly &
salary := salary * 1.08;
bonus := 500;
ELSIF salary BETWEEN 1501 AND 2000 THEN
salary := salary * 1.05;
bonus := 750;
ELSE
salary := salary * 1.02;
bonus := 1000;
END IF;

IF-ELSIF Examples
Here are some examples of the possible variations in the format of the IF-ELSIF
structure:

We have three different caller types to check. If the caller type is not one of VIP,
BILL_COLLECTOR, or INTERNATIONAL, then send the response with normal
delivery:

IF caller_type = 'VIP'
THEN
generate_response ('EXPRESS');

ELSIF caller_type = 'BILL_COLLECTOR'


THEN
generate_response ('THROUGH_CHICAGO');
ELSIF caller_type = 'INTERNATIONAL'
THEN
generate_response ('AIR');
ELSE
generate_response ('NORMAL');
END IF;

LOOP: Performs one or more statements repetitively, optionally terminating


execution when a condition is met or when an explicit EXIT command is
issued. Each statement between LOOP and END LOOP is executed
sequentially. If an EXIT command has not been encountered, control is passed
back to the first statement in the loop.

SYNTAX:
[<<label>>]
LOOP
[EXIT;]
[EXIT WHEN condition;]
statement;[statement;...]
END LOOP [<<label>>];

Keywords
<<label>> : Specifies an optional label for the loop. The loop is labeled by a
<<label>> preceding the LOOP statement and the corresponding END LOOP
statement may then optionally reference the same label.

LOOP : Required keyword indicating that subsequent statements, until the


END LOOP keyword is reached, be performed repetitively.

EXIT : Optional keyword that causes control to be passed to the next statement
after the END LOOP keyword. EXIT is actually an executable statement that
usually appears after an IF statement embedded in the loop. This keyword may
appear in any statement between the LOOP and END LOOP keywords, and may
appear multiple times. Note that EXIT is not strictly a component of the LOOP
syntax, but is included here for clarity, since it is often used in LOOP
programming.

EXIT WHEN : Optionally specifies a condition which, when it evaluates to


TRUE, causes control to be transferred to the next statement after the END
LOOP keyword. This keyword may appear in any statement between the LOOP
and END & LOOP keywords, and may appear multiple times. The specified exit
condition is evaluated when the EXIT WHEN statement is encountered. Note
that EXIT WHEN is not strictly a component of the LOOP syntax, but is
included here for clarity, since it is often used in LOOP programming.

Statement : Any valid PL/SQL assignment statement, SQL statement,


procedure call, or function call.

END LOOP : Required keyword indicating the end of the LOOP structure. It is
perfectly legal to have a loop structure without an EXIT or EXIT WHEN
keyword. However, such a loop will run forever, which is probably not what you
intended!

Example
In this example, which uses a PL/SQL table, the loop continues until one of
two conditions occur: if a row of the table is NULL, the loop immediately exits.
The loop is also ended when the value of loop_counter reaches 100.

loop_counter := 0;
LOOP
EXIT WHEN loop_counter = 100;
loop_counter := loop_counter+1;
IF salary_table(loop_counter) IS NULL THEN EXIT;
salary_table(loop_counter) := salary_table(loop_counter) * 1.1;
END LOOP;
WHILE Loop : Performs one or more statements repetitively until a condition is
not met. When the last statement is executed, control is passed back to the
first statement for execution.

SYNTAX:
[<<label>>]
WHILE condition LOOP
statement;[statement;…]
END LOOP [<<label>>];

This iterative execution continues until condition evaluates to FALSE.

Keywords
<<label>> : Specifies an optional label for the loop. The loop is labeled by a
<<label>> preceding the WHILE statement, and the corresponding END LOOP
statement may then optionally reference the same label.
.
WHILE …LOOP : Specifies that this is a WHILE loop that will execute as long as
condition evaluates to TRUE. When condition evaluates to FALSE, the keyword
will cause control to be transferred to the next statement following the END
LOOP keyword. The condition is tested before each execution of the loop body.

Statement : Any valid PL/SQL assignment statement, SQL statement,


procedure call, or function call.

END LOOP : Required keyword indicating the end of the LOOP structure. The
condition is evaluated prior to each iteration of the loop. If the condition is
TRUE, all statements in the loop are executed; if it evaluates to FALSE, control
is passed to the next statement after the END LOOP keyword.

Example
This example is similar to that shown earlier with the LOOP command, and
demonstrates how the same result can be accomplished using different
methods. Here, two statements are repeatedly executed (one to increment the
variable loop_ counter and one to update the corresponding element of the
salary table) until the value of loop_counter reaches 100. At that point, it is no
longer less than 100, and the loop terminates:

loop_counter := 0;
WHILE loop_counter < 100 LOOP
loop_counter := loop_counter+1;
salary(loop_counter) := salary(loop_counter) * 1.1;
END LOOP;
FOR Loop : Performs a sequence of statements a defined number of times.

SYNTAX:
[<<label>>]
FOR counter IN [REVERSE] start .. end LOOP
statement; [statement;…]
END LOOP [<<label>>];

Keywords
<<label>> : Specifies an optional label for the loop. The loop is labeled by a
<<label>> preceding the FOR statement, and the corresponding END LOOP
statement may then optionally reference the same label.
.
Counter : Specifies the name of a variable used to hold the count of iterations
through the loop. After each iteration of the loop, counter is incremented by 1,
unless REVERSE is specified, in which case counter is decremented by 1. This
variable is automatically defined as a BINARY_INTEGER and does not need to
be declared in the block. If a variable of the same name is declared and
available in the block, its declaration is temporarily overridden while the FOR
loop is active, unless it is explicitly referenced using blockname.variable
notation.

REVERSE : Specifies that counter will be decremented from end to start when
the FOR loop is executed. Start Specifies the beginning value for counter,
unless REVERSE is specified. If REVERSE is specified, start represents the
ending value for the counter. End Specifies the last value for counter; that is,
when counter reaches this value, the FOR loop is terminated and control is
passed to the executable statement immediately following the END LOOP
statement. If REVERSE is specified, end specifies the initial value of counter,
which is then decremented by 1 until start is reached.

Statement : Any valid PL/SQL assignment statement, SQL statement,


procedure call, or function call.

END LOOP : Required keyword indicating the end of the LOOP structure.

Example
This example performs the same operation as the example shown for the
WHILE loop, but is written using a FOR loop. Here the first 99 elements of the
salary table are updated:

FOR loop_counter IN 1..99 LOOP


salary(loop_counter) := salary(loop_counter) * 1.1;
END LOOP;
GOTO : Transfers program control to the executable statement immediately
following label.

SYNTAX:
GOTO label;

The following rules must be observed when using the GOTO statement:
• You can’t jump into a block from outside a block.
• You can’t jump into the middle of a loop.
• You can’t jump into the middle of an IF statement.
• You can’t jump out of an exception handler and back into the code.

Example
In this example, when salary is greater than 1000, control is passed to the
label no_raise, and the next statement to be executed assigns the current date
to the variable up_date:

IF salary > 1000 THEN


GOTO no_raise;
END IF;
Salary := salary * 1.1;
<<no_raise>>
up_date := SYSDATE;

NULL : The NULL statement does absolutely nothing. It can be used as a


placeholder when developing new code or to replace the contents of a deeply
nested portion of an IF statement that you no longer want to execute.

SYNTAX: NULL;

Example
In the following example, NULL has been used as a placeholder for code that
needs to be written later:

IF emp_sal < 0 THEN


--Write this later when the specs are finished
NULL;
ELSE
print_paycheck(emp_no, emp_sal);
END IF;

PROGRAM UNITS IN ORACLE FORMS


Function
A named PL/SQL block that performs some action and returns a single value.
A function can accept one or more parameters.

Procedure
A named PL/SQL block that performs one or more actions. A parameter list
may be used to pass values into and/or out of the procedure.

SYNTAX:
Except for anonymous blocks, all PL/SQL blocks begin with a block header.
The general syntax of the PL/SQL block header is:

{{PROCEDURE | FUNCTION} name IS | <<name>> }

Keywords
PROCEDURE : Indicates that the block is a PL/SQL procedure.

FUNCTION : Indicates that the block is a PL/SQL function. name `Specifies the
name to be assigned to the block. If used to create a named block, then the
name appears within pairs of angle brackets (<< >>) and the IS
keyword is omitted.
Example for Function
create function phon(phone number)return char is
ADDRESS CHAR(30);
BEGIN
IF phone=0001234 THEN
ADDRESS:='mosses Lusaka';
ELSIF phone=0004567 THEN
ADDRESS:='brown woodlands';
ELSIF phone=0008976 THEN
ADDRESS:='Jones Zambia';
ELSIF phone=00098765THEN
ADDRESS:='bhadhur woodlands';
END IF;
RETURN ADDRESS;
END;

Execute function :
 After write the function call a function.
 Write the coding
 declare
 begin
 dbms_output.put_line(phon(00098765));
 end;

Example for Procedure :

CREATE or REPLACE PROCEDURE incr (eid number,amt number) IS


vsalary number;
salarymissing exception;
NODATAFOUND exception;
BEGIN
SELECT sal INTO vsalary FROM empii WHERE empno=eid;
if vsalary IS NULL THEN
RAISE SALARYMISSING;
ELSE
UPDATE empii set sal=sal+amt
where empno=eid;
end if;
EXCEPTION
WHEN salarymissing THEN
dbms_output.put_line(eid || 'has salary as null');
WHEN NODATAFOUND THEN
dbms_output.put_line(eid || 'no such number');
end incr;

Execute Procedure :
 After write the procedure call a procedure.
 Execute procedure name(parameters);
 Execute incr(empno,amount)

PL/SQL Packages

A package is an encapsulated collection of related program objects (for


example, procedures, functions, variables, constants, cursors, and exceptions)
stored together in the database.

Using packages is an alternative to creating procedures and functions as


standalone schema objects. Packages have many advantages over standalone
procedures and functions. For example, they:

 Let you organize your application development more efficiently.


 Let you grant privileges more efficiently.
 Let you modify package objects without recompiling dependent schema
objects.
 Enable Oracle Database to read multiple package objects into memory at
once.
 Can contain global variables and cursors that are available to all
procedures and functions in the package.
 Let you overload procedures or functions. Overloading a procedure
means creating multiple procedures with the same name in the same
package, each taking arguments of different number or datatype.

packages are important for the following reasons:

 Packages are loaded into memory as a whole, increasing the likelihood


that a procedure or function will be resident in memory when called.
 Packages can include private elements, allowing logic to be hidden from
view.
 Placing functions and procedures inside packages eliminates the need to
recompile all functions and procedures that reference a newly recompiled
function/procedure.
 Function and procedure names may be overloaded within packages,
whereas standalone functions and procedures cannot be overloaded.
 Functions and procedures inside packages can be checked for side
effects at compile time rather than at execution time.

Parameters:
Create
Or replace
Schema
package

Example :

 CREATE OR REPLACE PACKAGE new_package AS


 PROCEDURE incr (eid number,amt number);
 Fuction phon(phone number);
 END new_package;

Parameters

Named PL/SQL programs (procedures and functions) can take parameters.


Parameters are named variables that are available to a program and that
modify program behavior and/or data. Parameters are optional on both
procedures and functions.

Parameters are declared when a procedure or function are declared and are
declared between an open and a close parenthesis (()).
Parameters may be named anything that follows Oracle naming standards.
Keep them under 30 characters, they must start with a letter and contain no
spaces. There additional rules but those are the ones that are most commonly
violated.

There are three types of parameter: IN, OUT and IN OUT.

An IN parameter is used an input only. An IN parameter cannot be changed by


the called program.

An OUT parameter is initially NULL. The program assigns the parameter a


value and that value is returned to the calling program.

An IN OUT parameter may or may not have an initial value. That initial value
may or may not be modified by the called program. Any changes made to the
parameter are returned to the calling program.

Parameter Modes

When you define the parameter you also specify the way in which the
parameter can be used. There are three different modes of parameters:

The mode determines how the program can use and manipulate the value
assigned to the formal parameter. You specify the mode of the parameter
immediately after the parameter name and before the parameter's datatype and
optional default value. The following procedure header uses all three modes of
parameters:

PROCEDURE predict_activity (last_date_in IN DATE, task_desc_inout IN


OUT VARCHAR2, next_date_out OUT DATE)

The predict_activity procedure takes in two pieces of information: the date of


the last activity and a description of the activity. It then returns or sends out
two pieces of information: a possibly modified task description and the date of
the next activity. Because the task_desc_inout parameter is IN OUT, the
program can both read the value of the argument and change the value of that
argument.

Example :
PROCEDURE combine_and_format_names (first_name_inout IN OUT VARCHAR2,
last_name_inout IN OUT VARCHAR2, full_name_out OUT VARCHAR2,
name_format_in IN VARCHAR2 := 'LAST, FIRST') IS BEGIN
/* Upper-case the first and last names. */
first_name_inout := UPPER (first_name_inout);
last_name_inout := UPPER (last_name_inout);
/* Combine the names as directed by the name format string. */
IF name_format_in = 'LAST, FIRST' THEN
full_name_out := last_name_inout || ', ' || first_name_inout;
ELSIF name_format_in = 'FIRST LAST' THEN
full_name_out := first_name_inout || ' ' || last_name_inout;
END IF;
END;

PL/SQL Editor:
The PL/SQL editor is where the application will take on its
specialized functionality. You can control exactly what the program can and
cannot do based on the work you do in the editor. This is where all of the
form’s triggers and procedures are edited and compiled. it is also where
database procedures can be accessed,modified,and compiled. The PL/SQL
editor is accessed by double-clicking on the PL/SQL editor button on the
Object Navigator.

EXCEPTION HANDLING:
Runtime errors arise from design faults, coding mistakes,
hardware failures and many other sources. Certain kinds of errors can be
handled via a PL/SQL block.In PL/SQL; an error condition is called an
Exception. Exceptions can be either internally defined or user-defined.
An exception is a specific kind of runtime error. When that
particular error occurs, the exception is said to be raised. An exception
handler is a group of commands written to handle a particular exception.

When an error occurs, an exception is raised whereby normal program


execution stops and the control are transferred to the exception handling
routine of the PL/SQL block. Internal exceptions are implicitly, where as user-
defined exceptions are explicitly raised by RAISE statements.
Overview of PL/SQL Runtime Error Handling

In PL/SQL, an error condition is called an exception. Exceptions can be


internally defined (by the runtime system) or user defined. Examples of
internally defined exceptions include division by zero and out of memory. Some
common internal exceptions have predefined names, such as ZERO_DIVIDE
and STORAGE_ERROR. The other internal exceptions can be given names.

You can define exceptions of your own in the declarative part of any PL/SQL
block, subprogram, or package. For example, you might define an exception
named insufficient_funds to flag overdrawn bank accounts. Unlike internal
exceptions, user-defined exceptions must be given names.

When an error occurs, an exception is raised. That is, normal execution stops
and control transfers to the exception-handling part of your PL/SQL block or
subprogram. Internal exceptions are raised implicitly (automatically) by the
run-time system. User-defined exceptions must be raised explicitly by RAISE
statements, which can also raise predefined exceptions.

To handle raised exceptions, you write separate routines called exception


handlers. After an exception handler runs, the current block stops executing
and the enclosing block resumes with the next statement. If there is no
enclosing block, control returns to the host environment.

The following example calculates a price-to-earnings ratio for a company. If the


company has zero earnings, the division operation raises the predefined
exception ZERO_DIVIDE, the execution of the block is interrupted, and control
is transferred to the exception handlers. The optional OTHERS handler catches
all exceptions that the block does not name specifically.

DECLARE
stock_price NUMBER := 9.73;
net_earnings NUMBER := 0;
pe_ratio NUMBER;
BEGIN
-- Calculation might cause division-by-zero error.
pe_ratio := stock_price / net_earnings;
dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);

EXCEPTION -- exception handlers begin


-- Only one of the WHEN blocks is executed.
WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error
dbms_output.put_line('Company must have had zero earnings.');
pe_ratio := null;
WHEN OTHERS THEN -- handles all other errors
dbms_output.put_line('Some other kind of error occurred.');
pe_ratio := null;
END; -- exception handlers and block end here

The last example illustrates exception handling. With some better error
checking, we could have avoided the exception entirely, by substituting a null
for the answer if the denominator was zero:
DECLARE
stock_price NUMBER := 9.73;
net_earnings NUMBER := 0;
pe_ratio NUMBER;
BEGIN
pe_ratio :=
case net_earnings
when 0 then null
else stock_price / net_earnings
end;
END;

Guidelines for Avoiding and Handling PL/SQL Errors and Exceptions

Because reliability is crucial for database programs, use both error checking
and exception handling to ensure your program can handle all possibilities:

1. Add exception handlers whenever there is any possibility of an error


occurring. Errors are especially likely during arithmetic calculations,
string manipulation, and database operations.
2. Add error-checking code whenever you can predict that an error might
occur if your code gets bad input data. Expect that at some time, your
code will be passed incorrect or null parameters, that your queries will
return no rows or more rows than you expect.
3. Make your programs robust enough to work even if the database is not
in the state you expect.
4. Handle named exceptions whenever possible, instead of using WHEN
OTHERS in exception handlers.
5. Test your code with different combinations of bad data to see what
potential errors arise.
6. Carefully consider whether each exception handler should commit the
transaction, roll it back, or let it continue. Remember, no matter how
severe the error is, you want to leave the database in a consistent state
and avoid storing any bad data.

Advantages of PL/SQL Exceptions


Using exceptions for error handling has several advantages.

With exceptions, you can reliably handle potential errors from many
statements with a single exception handler:

BEGIN
SELECT ...
SELECT ...
procedure_that_performs_select();
...
EXCEPTION
WHEN NO_DATA_FOUND THEN -- catches all 'no data found' errors

Instead of checking for an error at every point it might occur, just add an
exception handler to your PL/SQL block. If the exception is ever raised in that
block (or any sub-block), you can be sure it will be handled.

Sometimes the error is not immediately obvious, and could not be detected
until later when you perform calculations using bad data. Again, a single
exception handler can trap all division-by-zero errors, bad array subscripts,
and so on.

If you need to check for errors at a specific spot, you can enclose a single
statement or a group of statements inside its own BEGIN-END block with its
own exception handler. You can make the checking as general or as precise as
you like.

Internal Exceptions (Predefined Exceptions)


An internal exception is raised implicitly whenever the
PL/SQL block violates an oracle rule or exceeds a system-dependent limit.
Every Oracle has a number, but exceptions must be handled by
name.So,PL/SQL predefines some common Oracle errors as exceptions. Such
predefined exceptions are declared globally by PL/SQL.

Predefined or Internal Raised if


Exceptions
No_Data_Found Select statement returns no rows.
(records)
Too_many_rows Select into statement returns more
than one row.
Cursor_already_open Try to open a cursor already
opened
Zero_divide Try to divide a number by zero.
Storage_Error PL/SQL runs out of memory or if
the memory is corrupted.
Program error PL/SQL has an internal problem.
Invalid_cursor Violate cursor operation.

Example:
Declare
vStock itemmaster.stock%type;
Vreorder itemmaster reorder_level %type;
Begin
Select stock, reorder_level into vstock, vreorder from itemmaster where
stock< reorder_level;
Exception
When no_data_found then
Dbms_output.Put_line (‘No item’);
When too_many_rows then
Dbms_output.Put_line (‘more than one item found’);
End;

User-defined exceptions:
Unlike predefined exceptions, user defined exceptions should be
declared in the declarative part and raised explicitly by a ‘raise’statement.
The general syntax is
RAISE exception name;

Example:
Write a PL/SQL block for the trader wants to check whether a client in the
client-master has balance amount or not.
Declare
Vbal cmaster.balance%type;
Exbalance exception;
Begin
Select balance into vbal from cmaster where clientid=’10’;
If vbal>0 then
Raise exbalance;
End if;
Exception
When no_data_found then dbms_output.Put_line(‘nil balancs’);
When exbalance
Dbms_output.put_line ((‘The client has balance amount rupees’||vbal);
End;
Declaring Exceptions:
Exceptions are declared only in the declarative part of a PL/SQL
block, The declaration is done with the keyword EXCEPTION following the
variable name.

The following example declares an exception Zero_Error.


DECLARE
Zero_Error Exception;
BEGIN
Exception and variable declarations are similar.But,an exception is an error
condition, not an object.

Handling Raised Exceptions:


Exception handlers are written to catch raised exceptions. When an
exception is raised in a block, normal execution of the block stops and control
is transferred to its exception handler.
The exception handling part of a PL/SQL block begins with the
keyword EXCEPTION and always appears at the end of the block. each handler
consists of a WHEN clause specifying an exception name followed by a
sequence of statements to be executed when that exception is raised. These
statements complete execution of the block that is control does not return to
statements from where the exception was raised.

Example:
EXCEPTION
When Zero_Error then
Dbms_output.put_line (‘Value cannot be Zero or less than zero’);
END;

Using the RAISE Statement


Exceptions are raised implicitly by the runtime system, or explicitly
by RAISE statements. A block should RAISE an exception only when an error
makes it possible or impractical to finish processing. A RAISE statement for a
given expression can be coded anywhere within the scope of that expression.

Example:
DECLARE
----
BEGIN
………
If(condn<=0)then
Raise Zero_Error;
END IF;
EXCEPTION
WHEN Zero_Error THEN
----------
END;
The RAISE statement stops normal execution of the PL/SQL block and
transfers control to the appropriate exception handler. The exception can be a
predefined exception or a user-defined exception.

The example given below accepts data to be inserted in the service table. The
user-defined exception is raised if the service if the service charge is less than
Zero.

Built−In Packages
Contents:
Using the Built−in Packages
DBMS_ALERT
DBMS_DDL
DBMS_ JOB
DBMS_LOB (PL/SQL8 Only)
DBMS_LOCK
DBMS_MAIL
DBMS_OUTPUT
DBMS_SQL
DBMS_TRANSACTION

DBMS_ALERT : Provides support for notification of database events on an


asynchronous basis. Registers a process with an alert and then waits for a
signal from that alert.

DBMS_DDL : Provides programmatic access to some of the SQL DDL


statements.

DBMS_JOB : Submits and manages regularly scheduled jobs for execution


inside the database

DBMS_LOB : Provides a set of programs to manipulate LOBs (large objects)


(PL/SQL8 only).

DBMS_LOCK : Lets you create your own user locks in the database.

DBMS_MAIL : Interfaces to Oracle Office (formerly known as Oracle*Mail).

DBMS_OUTPUT : Displays output from PL/SQL programs to the terminal.


DBMS_SQL : Provides full support for dynamic SQL within PL/SQL. Dynamic
SQL refers to statements that are not prewritten into your programs. They are,
instead, constructed at run time as character strings and then passed to the
SQL engine for execution.

DBMS_ TRANSACTION : Provides a programmatic interface to a number of the


SQL transaction statements, such as SET TRANSACTION.

You might also like