Unit Iv
Unit Iv
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.
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.
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
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:
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:
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.
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;
Emprowvar.sal:=5000;
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.
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;
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.
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-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');
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.
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.
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>>];
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.
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.
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:
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:
SYNTAX: NULL;
Example
In the following example, NULL has been used as a placeholder for code that
needs to be written later:
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:
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;
Execute Procedure :
After write the procedure call a procedure.
Execute procedure name(parameters);
Execute incr(empno,amount)
PL/SQL Packages
Parameters:
Create
Or replace
Schema
package
Example :
Parameters
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.
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:
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.
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.
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);
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;
Because reliability is crucial for database programs, use both error checking
and exception handling to ensure your program can handle all possibilities:
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.
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.
Example:
EXCEPTION
When Zero_Error then
Dbms_output.put_line (‘Value cannot be Zero or less than zero’);
END;
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_LOCK : Lets you create your own user locks in the database.