0% found this document useful (0 votes)
4 views

Workshop on SQL & PL_SQL

The document provides an overview of PL/SQL, highlighting its block structure, advantages over SQL, and various control structures such as conditional, iterative, and sequential. It discusses error handling, including predefined and user-defined exceptions, and illustrates PL/SQL programming concepts with examples. Additionally, it covers built-in datatypes, variable declaration, and the use of control statements for effective programming.

Uploaded by

Prachi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Workshop on SQL & PL_SQL

The document provides an overview of PL/SQL, highlighting its block structure, advantages over SQL, and various control structures such as conditional, iterative, and sequential. It discusses error handling, including predefined and user-defined exceptions, and illustrates PL/SQL programming concepts with examples. Additionally, it covers built-in datatypes, variable declaration, and the use of control statements for effective programming.

Uploaded by

Prachi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Workshop

on
Basic to Advance
SQL & PL/SQL

Prepared by :

Dr. Ajay N. Upadhyaya


Prof. Krupa Patel
Prof. Bhoomi Patel
Overview to PL/SQL

BASIC OF PL/SQL CODE BLOCK:

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.

Figure 1-1 Block Structure

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.

Advance Database Workshop Page 2


Disadvantage of SQL
 SQL do not have any procedural capabilities. It means it do not provide
techniques of condition checking, looping and branching.
 Statements are passed one at a time to Oracle Engine. Due to this for each
statement call is made to Oracle Engine which increases network traffic which
decreases execution speed.
 Error Messages are not handled. Means while processing if any error occurs
then Oracle Engine displays it’s own error, so there is no facility of
programmed handling of errors.

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

Advance Database Workshop Page 3


Data Type

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.

Advance Database Workshop Page 4


Variable:
Variable used in PL/SQL code block are named as variable.
 Variable must begin with a character and can be followed by maximum 29
characters.
 Reserved words can not be used as a variable name.
 Variable can be separated with each other using space or punctuation
mark.
 A space can not be used in variable name.
 There is 2 different ways for assigning values:
1) Using assignment operator(:=)
2) Selecting or fetching data values into variables.

Displaying message on VDU (Video Display Unit) screen.


 DBMS_OUTPUT.PUT_LINE is used to display messages & values.
 Message is displayed in ’ ‘ & can be displayed directly by using ||.
 For displaying a message the necessary thing is writing SET SERVER
OUTPUT ON on the PL/SQL screen.

Advance Database Workshop Page 5


Control structures

2.1 Conditional Control

Often, it is necessary to take alternative actions depending on circumstances. The IF-


THEN-ELSE statement lets you execute a sequence of statements conditionally. The IF
clause checks a condition; the THEN clause defines what to do if the condition is true;
the ELSE clause defines what to do if the condition is false or null.

IF-THEN

The simplest form of IF statement associates a condition with a sequence of statements


enclosed by the keywords THEN and END IF (not ENDIF), as follows:

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;

Advance Database Workshop Page 6


IF-THEN-ELSE

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;

Advance Database Workshop Page 7


2.2 Iterative structures:

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;

Advance Database Workshop Page 8


WHILE-LOOP

The WHILE-LOOP statement associates a condition with a sequence of statements


enclosed by the keywords LOOP and END LOOP, as follows:

WHILE <condition> LOOP


sequence_of_statements
END LOOP;

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;

Advance Database Workshop Page 9


FOR-LOOP

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:

FOR variable in [reverse] start..end


loop
--sequence of statements
end loop;

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;

Advance Database Workshop Page 10


PR: Write a PL/SQL code block for printing the following output.
1
12
123
1234
12345

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;

Advance Database Workshop Page 11


2.3 Sequential structures:

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;

Advance Database Workshop Page 12


Error Handling

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

Predefined Exceptions [System Defined]


 An internal exception is raised implicitly whenever your PL/SQL program
violates an Oracle rule or exceeds a system-dependent limit.
 Every Oracle error has a number, but exceptions must be handled by name. So,
PL/SQL predefines some common Oracle errors as exceptions. For example,
PL/SQL raises the predefined exception NO_DATA_FOUND if a SELECT INTO
statement returns no rows.
 Predefined exception categories in two categories: Named Exception, Numbered
Exception.
 Oracle engine has 20(app.) Named exception handlers.
 Oracle engine has 20,000(app.) Numbered exception handlers. Each Exception
handler is identified by 4 digit number preceded by hyphen(-1422).

Advance Database Workshop Page 13


Named Exception
Exception Raised when ...
ACCESS_INTO_NULL Your program attempts to assign values to the attributes
of an uninitialized (atomically null) object.
COLLECTION_IS_NULL Your program attempts to apply collection methods
other than EXISTS to an uninitialized (atomically null)
nested table or varray, or the program attempts to assign
values to the elements of an uninitialized nested table or
varray.
CURSOR_ALREADY_OPEN Your 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.
DUP_VAL_ON_INDEX Your program attempts to store duplicate values in a
database column that is constrained by a unique index.
INVALID_CURSOR Your program attempts an illegal cursor operation such
as closing an unopened cursor.
INVALID_NUMBER 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.)
LOGIN_DENIED Your program attempts to log on to Oracle with an
invalid username and/or password.
NO_DATA_FOUND A SELECT INTO statement returns no rows, or your
program references a deleted element in a nested table or
an uninitialized element in an index-by table.
SQL aggregate functions such as AVG and SUM always
return a value or a null. So, a SELECT INTO statement
that calls a aggregate function will never raise
NO_DATA_FOUND.
The FETCH statement is expected to return no rows
eventually, so when that happens, no exception is raised.

NOT_LOGGED_ON Your program issues a database call without being


connected to Oracle.

Advance Database Workshop Page 14


Exception Raised when ...
PROGRAM_ERROR PL/SQL has an internal problem.
ROWTYPE_MISMATCH 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 is
passed to a stored subprogram, the return types of the
actual and formal parameters must be compatible.
SELF_IS_NULL Your program attempts to call a MEMBER method on a
null instance. That is, the built-in parameter SELF (which
is always the first parameter passed to a MEMBER
method) is null.
STORAGE_ERROR PL/SQL runs out of memory or memory has been
corrupted.
SYS_INVALID_ROWID The conversion of a character string into a universal
rowid fails because the character string does not
represent a valid rowid.
TIMEOUT_ON_RESOURCE A time-out occurs while Oracle is waiting for a resource.
TOO_MANY_ROWS A SELECT INTO statement returns more than one row.
VALUE_ERROR An arithmetic, conversion, truncation, or size-constraint
error occurs. For example, when your program selects a
column value 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.)
ZERO_DIVIDE Your program attempts to divide a number by zero.
OTHERS Stands fro all other exception.

Advance Database Workshop Page 15


Programme

Divide by zero Error handling.


Declare
x number(4); y number(5); z number(5);
Begin
x:= &x; y:= &y; z := x/y;
dbms_output.put_line ('Ans: ' || z);
Exception
When ZERO_DIVIDE then
dbms_output.put_line ('Can not divide by Zero');
End;
Output:-
Enter value for x:23
Enter value for y:0
Can’t divide by zero

No data found Error handling


Declare
bal emp.e_bal%type;
Begin
select e_bal into bal from emp where bal>50,00,000;
Exception
when no_data_found then
dbms_output.put_line('Sorry we cant find the appropriate data!!');
End;
Output:-
Sorry we cant find the appropriate data!!

Advance Database Workshop Page 16


User-Defined Exceptions
PL/SQL lets you define exceptions of your own. Unlike predefined exceptions, user-
defined exceptions must be declared and must be raised explicitly by RAISE statements.
Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram,
or package.
Syntax:
Declare
Exception_Name Exception;
Begin
<SQL statement>
IF <Condition> then
Raise Exception_Name;
End IF;
Exception
When Exception_Name Then
< User defined action>
End;
Exception and variable declarations are similar. But remember, an exception is an error
condition, not a data item. Unlike variables, exceptions cannot appear in assignment
statements or SQL statements.

Advance Database Workshop Page 17


User defined Error handling.

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

Advance Database Workshop Page 18


Procedure and Function

Introduction

A procedure or function is a logically grouped set of SQL and PL/SQL statements that

perform a specific task.

 A procedure and function are made up of:

1. A declarative part

2. An executable part

3. An optional exception-handling 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

procedure or function is expected to perform is coded here.

3. Exception Handling Part

This part contains code that deals with exception that may be raised during the

execution of code in the executable part.

Advance Database Workshop Page 19


Procedure

Syntax

Create or replace procedure [schema] <procedure name>

(<argument> {IN, OUT, IN OUT} <Data type>,<){IS,AS}

<Variable> declaration;

<Constant> declaration;

Begin

<PL/SQL subprogram body>;

Exception

<Exception PL/SQL block>

End;

Key words and parameters

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

Advance Database Workshop Page 20


Function

Create or replace function [schema] <function name>

(<argument>IN <Data type><)

Return <data type>{IS, AS}

<Variable> declaration;

<Constant> declaration;

Begin

<PL/SQL subprogram body>;

Exception

<Exception PL/SQL block>

End;

Key words and parameters

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

Argument Is the name of an argument to the function parenthesis can be omitted if no


arguments are presents
IN Indicates that the parameter will accept the value from a user

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

Advance Database Workshop Page 21


Procedures versus Functions

 Function must return a value back to the caller.A function can return only one

value to the calling pl/sql code block.

 By defining multiple OUT parameter we can pass multiple values to the

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 OUT variable is global by nature.

View Errors in Procedure/Function

 The compilation process does not display the errors. These errors can be viewed

using the select statement: SELECT * FROM USER_ERRORS;

 If any error is occur in procedure/function then procedure/function will be

created with compilation errors. Which give message procedure/function created

with compilation errors.

System Global Area(SGA)

 When a procedure or function is invoked, the oracle engine loads the compiled

procedure or function in a memory area called the System Global Area.

 This allows the code to be executed quickly.

 Once loaded in the SGA other users also access the same procedure or function if

they have been granted permission to do so.

Storing of procedure/function

Procedure/function is stored in Oracle database. The following steps are performed

automatically by Oracle Engine when procedure/function is created:

1) Compile the procedure/function.

2) Store this procedure/function in database.

Advance Database Workshop Page 22


Execution of procedure/function by Oracle Engine

The oracle Engine performs the following steps to execute procedure/function:

1) Verifies user access.

2) Verifies procedure/function validity.

3) Execute the procedure/function.

To view the status of prcedure/function

Select obj_name,obj_type,status from user_object(s) where object_type =

procedure/function

Advantages of using a procedure/function

 Security: Stored procedure/function can enforce data security. User can grant the

permission for particular prcedure/function.Granted users can access the

procedure/function.

 Performance: It improves the database performance in following ways:

1) By sending less information over Network.

2) For execution, no compilation step is required.

3) Reduction in disk I/O.(due to SGA)

 Memory Allocation: Due to shared memory capabilities, reduction in total memory

area.

 Productivity: By writing procedure/function redundant coding can be avoided &

through that productivity can be increased.

 Integrity: Testing is required only once.

Delete procedure/function

 drop procedure procedure_name;

 drop function function_name;

Advance Database Workshop Page 23


Programs:

WRITE A PROCEDURE FOR MULTIPLICATION OF TWO NUMBERS


create or replace procedure mul
(x in number,y in number) is
begin
dbms_output.put_line(x*y);
end;

output:
Procedure created.
SQL> exec mul(2,3);
6
PL/SQL procedure successfully completed.

WRITE A PROCEDURE FOR ACCEPTING A STRING FROM USER AND


DISPLAYING ITS SIZE
create or replace procedure str
(x in varchar) is
y number;
begin
y:=length(x);
dbms_output.put_line('the length is'||y);
end;

output:
Procedure created.
SQL> exec str('hello');
5
PL/SQL procedure successfully completed.

Advance Database Workshop Page 24


WRITE A PROCEDURE WHICH ACCEPTS TWO STRING FROM USER AND
RETURNS THE LARGEST ONE .
create or replace procedure str
(x in varchar,y in varchar) is
len1 number;
len2 number;
begin
len1:=length(x);
len2:=length(y);
if (len1>len2) then
dbms_output.put_line(x);
else
dbms_output.put_line(y);
end if;
end;

output:
Procedure created.
SQL> exec str('hello','hi');
hello
PL/SQL procedure successfully completed.

CREATE A PROCEDURE THAT DELETE ROWS FROM ENQUIRY WHICH ARE 1


YRS BEFORE

Create or replace procedure myprocedure is


begin
delete from enquiry where enquirydate <= sysdate - 1;
end;

• 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.

Advance Database Workshop Page 25


Function Program

Calling a Function

Advance Database Workshop Page 26


Oracle Packages

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.

Standalone sub programs:

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.

Components of Oracle package:


Components:
 Package Specification: It declares the different memory variables, constant,
exception, cursor & other sub programs.
 Package Body: It fully defines cursor, function procedure with implementation.

Advantages of Package:

1) Easily understandable.(simple clear & well-defined)


2) Granting of privileges efficiently.
3) Common execution environment.
4) Overloading of Procedure/function can be possible.
5) Less number of disk I/O.
6) Performance increase.
7) Code reusability is high.
8) Productivity will increase.

Advance Database Workshop Page 27


Package Specification:
It contains:
1) Name of Package.
2) Name of argument with datatype.
3) Local variable & constant.

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;

Advance Database Workshop Page 28


Example: Create a package with which we can do the multiplication of either 2 or 3
numbers, using procedure.

Create package pk2


IS
Procedure p1(X IN number, Y IN number);
Procedure p1(X IN number, Y IN number, Z IN number);
End pk2;

Create or replace package body pk2


as
Procedure p1(X IN number, Y IN number)
IS
Begin
Dbms_output.put_line(X*Y);
End;
Procedure p1(X IN number, Y IN number, Z IN number)
IS
Begin
Dbms_output.put_line(X*Y*Z);
End;
End pk2;

Advance Database Workshop Page 29


Print pattern
*********
********
*******
******
*****
****
***
**
*

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.

Advance Database Workshop Page 30


Oracle Trigger

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.

Difference between Procedure & Trigger


1) Trigger cannot accept the parameter when procedure can accept the
parameter.
2) Trigger executes implicitly when procedure executes explicitly.
3) User can explicitly called procedure and implicitly called trigger.

Basic parts of Trigger


1) Trigger event or statement.
2) Trigger restriction.
3) Trigger action.

Types of trigger
1) Row trigger.
2) Statement Trigger.
3) Before Trigger.
4) After Trigger.

Advance Database Workshop Page 31


Different combinations of trigger
1) Before-Statement Trigger.
2) After-Statement Trigger.
3) Before-Row Trigger.
4) Before-Statement 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;

Keywords & parameters

 Create :- create new trigger


 Or replace :- recreate the trigger if already exists.
 Schema :- it is the schema which contains the trigger.
 Before :- oracle engine fire the trigger before executing triggering statement.
 After :- oracle engine fire the trigger after executing triggering statement.
 Delete :- oracle engine fire the trigger when delete statement will fire on the
table.
 Update :- oracle engine fire the trigger when update statement will fire on the
table.
 Insert :- oracle engine fire the trigger when insert statement will fire on the
table.
 Referencing :- (1) old as old—refers old values.
(2) new as new—refers new values.

Advance Database Workshop Page 32


 For each row :- define the trigger as new trigger.
 When :- specify the trigger restriction.

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.

Let’s assume we have two tables:


Emp(id,name,sal)
Emp_old(id,name,sal,e_date,opr,user1)

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;

Advance Database Workshop Page 33

You might also like