Workshop on SQL & PL_SQL
Workshop on SQL & PL_SQL
on
Basic to Advance
SQL & PL/SQL
Prepared by :
PL/SQL is a block-structured language. That is, the basic units (procedures, functions,
and anonymous blocks) that make up a PL/SQL program are logical blocks, which
can contain any number of nested sub-blocks. Typically, each logical block
corresponds to a problem or sub problem to be solved. Thus, PL/SQL supports the
divide-and-conquer approach to problem solving called stepwise refinement.
A block (or sub-block) lets you group logically related declarations and statements.
That way, you can place declarations close to where they are used. The declarations
are local to the block and cease to exist when the block completes.
As Figure 1-1 shows, a PL/SQL block has three parts: a declarative part, an
executable part, and an exception-handling part. (In PL/SQL, a warning or error
condition is called an exception.) Only the executable part is required.
The order of the parts is logical. First comes the declarative part, in which items can
be declared. Once declared, items can be manipulated in the executable part.
Exceptions raised during execution can be dealt with in the exception-handling
part.
You can nest sub-blocks in the executable and exception-handling parts of a PL/SQL
block or subprogram but not in the declarative part. Also, you can define local
subprograms in the declarative part of any block. However, you can call local
subprograms only from the block in which they are defined.
Advantages of PL/SQL
PL/SQL is a completely portable, high-performance transaction processing language
that offers the following advantages:
Checking , branching and looping facility is available in PL/SQL.
We can sent entire PL/SQL block at the same time.
Reduce network traffic.
It is faster then SQL.
It can deal with the errors which are generated.
Declaration and use of variables is possible.
Calculation can be done quickly and efficiently without the use of oracle
engine.
It is a portable language.
It allows to create our own structure.
Support for SQL
Support for object-oriented programming
Better performance
Higher productivity
Built-in Datatypes
%Type:
It is used to assign same data type as table to variable. %TYPE
The %TYPE attribute provides the datatype of a variable or database column.
This is particularly useful when declaring variables that will hold database
values. For example, assume there is a column named title in a table named
books. To declare a variable named my_title that has the same datatype as
column title, use dot notation and the %TYPE attribute, as follows:
my_title books.title%TYPE;
Declaring my_title with %TYPE has two advantages. First, you need not know
the exact datatype of title. Second, if you change the database definition of title
(make it a longer character string for example), the datatype of my_title changes
accordingly at run time.
IF-THEN
IF <condition> THEN
sequence_of_statements
END IF;
The sequence of statements is executed only if the condition is true. If the condition is
false or null, the IF statement does nothing. In either case, control passes to the next
statement.
Example:-
DECLARE
A number(4):=8;
B number(4):=6;
BEGIN
IF A>B THEN
DBMS_OUTPUT.PUT_LINE(‘A is Grater then B’);
END IF;
END;
The second form of IF statement adds the keyword ELSE followed by an alternative
sequence of statements, as follows:
IF <condition> THEN
sequence_of_statements1
ELSE
sequence_of_statements2
END IF;
Examples:
DECLARE
YEAR number(4,0);
BEGIN
YEAR:=&YEAR;
IF mod(YEAR,4)=0 THEN
DBMS_OUTPUT.PUT_LINE('entered year is leap year');
ELSE
DBMS_OUTPUT.PUT_LINE('entered year is not leap year');
END IF;
END;
DECLARE
A number(5); B number(5); C number(5);
BEGIN
A:=&A; B:=&B;C:=&C;
IF A>B then
IF A>C then
DBMS_OUTPUT.PUT_LINE('value of A is maximum :'||A);
ELSE
DBMS_OUTPUT.PUT_LINE('value of C is maximum :'||C);
END IF;
ELSE
IF C>B then
DBMS_OUTPUT.PUT_LINE('value of C is maximum :'||C);
ELSE
DBMS_OUTPUT.PUT_LINE('value of B is maximum :'||B);
END IF;
END IF;
END;
LOOP statements let you execute a sequence of statements multiple times. You place the
keyword LOOP before the first statement in the sequence and the keywords END LOOP
after the last statement in the sequence. The following example shows the simplest kind
of loop, which repeats a sequence of statements continually:
LOOP
The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a
sequence of statements between the keywords LOOP and END LOOP, as follows:
LOOP
sequence_of_statements
exit when Condition
END LOOP;
Examples:
DECLARE
A number(4):=0;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(A);
A:=A+1;
EXIT WHEN(A>5);
END LOOP;
END;
Before each iteration of the loop, the condition is evaluated. If the condition is true, the
sequence of statements is executed, then control resumes at the top of the loop. If the
condition is false or null, the loop is bypassed and control passes to the next statement.
An example follows:
Examples:
DECLARE
A number(4):=0;
BEGIN
WHILE(A<5)
LOOP
A:=A+1;
DBMS_OUTPUT.PUT_LINE(A);
END LOOP;
END;
DECLARE
no number(15); ans number(15):=1;
BEGIN
no:=&no;
WHILE no>0
LOOP
ans:=ans*no;
no:=no-1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(ans);
END;
Whereas the number of iterations through a WHILE loop is unknown until the loop
completes, the number of iterations through a FOR loop is known before the loop is
entered. FOR loops iterate over a specified range of integers. The range is part of an
iteration scheme, which is enclosed by the keywords FOR and LOOPS. A double dot (..)
serves as the range operator. The syntax follows:
DECLARE
no number(5); a number(5);b number(5); summ number(5);
BEGIN
no:=&no;
a:=0; b:=1; summ:=1;
FOR i in 0..no
LOOP
DBMS_OUTPUT.PUT_LINE(summ);
summ:=a+b;
a:=b;
b:=summ;
END LOOP;
END;
DECLARE
BEGIN
FOR i in 0..5
LOOP
FOR j in 1..i
LOOP
DBMS_OUTPUT.PUT(j||' ');
END LOOP;
DBMS_OUTPUT.PUT_LINE(' ');
END LOOP;
END;
PR: Write a pl\sql code block for reversing the entered number from user.
DECLARE
s varchar(10);
str varchar(10);
no varchar(10);
BEGIN
s := &s;
no:=length(s);
FOR i in reverse 1..no
LOOP
str:=str||substr(s,i,1);
END LOOP;
DBMS_OUTPUT.PUT_LINE(‘reversed number is’||str); END;
GOTO
Unlike the IF and LOOP statements, the GOTO and NULL statements are not crucial to
PL/SQL programming. The structure of PL/SQL is such that the GOTO statement is
seldom needed. Occasionally, it can simplify logic enough to warrant its use. The NULL
statement can improve readability by making the meaning and action of conditional
statements clear.
GOTO Statement
The GOTO statement branches to a label unconditionally. The label must be unique
within its scope and must precede an executable statement or a PL/SQL block. When
executed, the GOTO statement transfers control to the labeled statement or block. In the
following example, you go to an executable statement farther down in a sequence of
statements:
BEGIN
...
GOTO insert_row;
...
<<insert_row>>
INSERT INTO emp VALUES ...
END;
In the next example, you go to a PL/SQL block farther up in a sequence of statements
DECLARE
a number(5); b number(5);
BEGIN
a:=&a; b:=&b;
IF a>b then
goto aa;
ELSE
goto bb;
END IF;
<<aa>>
DBMS_OUTPUT.PUT_LINE('A is greater');
<<bb>>
DBMS_OUTPUT.PUT_LINE('B is greater');
END;
Overview
Run-time errors arise from design faults, coding mistakes, hardware failures, and
many other sources. Although you cannot anticipate all possible errors, you can
plan to handle certain kinds of errors meaningful to your PL/SQL program.
In PL/SQL, a warning or error condition is called an exception. Exceptions can be
internally defined (by the run-time 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.
If an error is occur at that time exception condition will raise. To handle raised
exceptions, you write separate routines called exception handlers [Code block
which will handle exception Condition].
Two type of Exception: System Defined and User Defined
Declare
eid emp.e_id %type;
Sal emp.esal %type;
Excp1 exception;
Begin
eid:=&eid;
update emp set sal=esal+10,000 where emp.e_id=eid;
select esal into sal from emp where emp.e_id=eid;
if sal>50,000 then
dbms_output.put_line(‘You have good salary’);
else
raise excp1;
end if;
Exception
When excp1 then
Dbms_output.put_line(‘You have poor salary’);
End;
Output:-
Enter value for eid:1234.
You have poor salary
Introduction
A procedure or function is a logically grouped set of SQL and PL/SQL statements that
1. A declarative part
2. An executable part
1. A Declarative Part:
The declarative path may contain the declaration of cursors, constants, variables,
exception and subprograms. These objects are local to the procedure or function.
2. An executable part:
The executable part is a PL/SQL block consisting of SQL and PL/SQL statements
that assign values, control execution and manipulate data. The action that the
This part contains code that deals with exception that may be raised during the
Syntax
<Variable> declaration;
<Constant> declaration;
Begin
Exception
End;
Replace Recreate the procedure if it already exists. This option is used to change the
definition of an existing procedure without dropping ,recreating and re-
granting object privileges
Schema It is a schema which contain the procedure. The oracle engine takes a default
schema.
Procedure Is the name of the procedure to be created
Argument Is the name of an argument to the procedure parenthesis can be omitted if
no arguments are presents
IN Indicates that the parameter will accept the value from a user
OUT Indicates that the parameter will return the value to the user
IN OUT Indicate that the parameter will either accept value from the user or return a
value to the user.
Data type Is the data type of an argument. It supports any data type supported by
PL/SQL
<Variable> declaration;
<Constant> declaration;
Begin
Exception
End;
Replace Recreate the function if it already exists. This option is used to change the
definition of an existing function without dropping ,recreating and re-
granting object privileges
Schema Is a schema to contain the procedure. the oracle engine takes a default
schema.
Function Is the name of the function to be created
Return data Is the data type of the function return value. Because every function must
return a value, this clause is required. It supports any data type supported
type
by PL/SQL
PL/SQL Is the definition of function consisting of PL/SQL statements.
subprogram
body
Function must return a value back to the caller.A function can return only one
caller.We can retrieve the values of procedure parameters in a pl/sql code block.
A function can return only one value to the calling PL/SQL code block.
The compilation process does not display the errors. These errors can be viewed
When a procedure or function is invoked, the oracle engine loads the compiled
Once loaded in the SGA other users also access the same procedure or function if
Storing of procedure/function
procedure/function
Security: Stored procedure/function can enforce data security. User can grant the
procedure/function.
area.
Delete procedure/function
output:
Procedure created.
SQL> exec mul(2,3);
6
PL/SQL procedure successfully completed.
output:
Procedure created.
SQL> exec str('hello');
5
PL/SQL procedure successfully completed.
output:
Procedure created.
SQL> exec str('hello','hi');
hello
PL/SQL procedure successfully completed.
• Procedure: a program unit that can receive multiple input parameters and return multiple output values or
return no output values
• Function: a program unit that can receive multiple input parameters, and always returns a single output
value.
Calling a Function
Introduction
It is an oracle object which holds other object within it.
Objects commonly held in package are procedure, function, variable, constants, cursor
& exceptions.
Package will be stored in Oracle database.
User who has permission can only use the package.
If package is not required any input from other PL/SQL code block, then that package is
called stand alone subprograms.
Otherwise , it is known as Non-stand alone.
Advantages of Package:
Syntax:
create package package_name
IS/AS
Function f1;
Function f2;<
Procedure p1;
Procedure p2;<
End package_name;
Package Body:
Syntax:
create or replace packagebody package_name
IS/AS
Function f1(with argument & datatype);
Begin
Execution code;
End;
Procedure p1(with argument & datatype);
Begin
Execution code;
End;
End package_name;
DECLARE
p number(4):=10;
BEGIN
for y in 1..10
loop
p:=p-1;
FOR x IN 1..p
LOOP
dbms_output.put('*');
END LOOP;
END LOOP;
END;
/
dbms_output.put_line('');
Output:-
*********
********
*******
******
*****
****
***
**
*
PL/SQL procedure successfully completed.
Introduction
The oracle engine allows the definition of procedure that is implicitly executed when an
INSERT, UPDATE or DELETE is fired against a table from SQL*PLUS. This is called a
database trigger.
Use of trigger
1) A trigger can permit DML statement against the table.
2) Only if they are issued during the specific time.
3) It is to keep an audit trial of the stage.(log maintenance)
4) Used to prevent invalid transaction.
5) Enforce complex security authorization.
Types of trigger
1) Row trigger.
2) Statement Trigger.
3) Before Trigger.
4) After Trigger.
Syntax:
create or replace[schema] trigger_name
{before, after}
{delete, insert, update} [of column]} on [schema] table_name
[referencing {old as old, new as new}]
[for each row[when condition]]
Declare
Variable declaration;
Constant declaration;
Begin
PL/SQL code block
Exception
Exception handler code;
End;
Delete a trigger
Drop trigger trigger_name;
Example
Create the transparent audit system which manages the employee details in emp
table.
Manage the record emp_old table whenever any record is updated or deleted from emp
table with the transaction date, transaction type done by user.
Create trigger t1
After
Update or delete
On emp
For each row
Declare
X varchar2;
Begin
If updating then
X :=’update’;
End if;
If deleting then
X :=’delete’;
End if;
Insert into emp_old values(:old.id, :old.name, :old.sal, sysdate, x, user)
End;