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

PL SQL

It includes concepts of PL/SQL

Uploaded by

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

PL SQL

It includes concepts of PL/SQL

Uploaded by

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

Unit No.

04-PL/SQL Programming
Unit No. 4.PL/SQL
Programming
Unit No. 4.PL/SQL
Programming
Introduction
• PL/SQL stand for Procedural Language /
Structured Query Language
• An extension to SQL with design features of
programming languages .
• Allows user to write a program to do the
various operations on databases.
• PL/SQL is a combination of SQL statements
with the programming Language.

K. K. WAGH POLYTECHNIC, NASHIK


Difference between SQL and PL/SQL
• SQL is a nonprocedural language. When you
issue a SQL command, your command tells the
database server what to do. However, you
cannot specify how to do it.
• PL/SQL integrates control statements and
conditional statements with SQL. This gives
you better control of your SQL statements and
their execution.

K. K. WAGH POLYTECHNIC, NASHIK


Advantages Of PL/SQL

1. Procedural Language Capability

PL/SQL consist of Procedural language


such as conditional statement(if statement )
and loops like (FOR loop).

K. K. WAGH POLYTECHNIC, NASHIK


2.Modularized program development
• The basic unit in a PL/SQL program is a block.
All PL/SQL programs consist of blocks.
• These blocks can be thought of as modules
and can be “modularized” in a sequence or
nested in other blocks.

K. K. WAGH POLYTECHNIC, NASHIK


CONTD…
• You can break your application into smaller
modules. If you are designing a complex
application, PL/SQL allows you to break down
the application into smaller, manageable, and
logically related modules.
• You can easily read, maintain, and debug the
code

K. K. WAGH POLYTECHNIC, NASHIK


3.Improved Performance
•PL/SQL allows you to logically combine multiple
SQL statements as one unit or block.
• PL/SQL engine Processes multiple SQL
statements simultaneously as a single block ,
thereby reducing network traffic, and provides
high performance for the application.

K. K. WAGH POLYTECHNIC, NASHIK


4.Portability
• Applications written in PL/SQL are portable to
any computer hardware and operating systems.
• You can write portable program packages and
create libraries that can be reused on Oracle
databases in different environments.

K. K. WAGH POLYTECHNIC, NASHIK


5.Exception handling
• An exception is an error that occurs in the
database or in a user’s program during
runtime.
• Examples of errors include: hardware or
network failures, application logic errors,
data integrity errors, and so on.

K. K. WAGH POLYTECHNIC, NASHIK


• You can prepare for errors by writing exception
handling code.
• Exception handling code tells your program
what to do in the event of an exception.
• PL/SQL allows you to handle database and
program exceptions efficiently. You can define
separate blocks for dealing with exceptions.

K. K. WAGH POLYTECHNIC, NASHIK


PL/SQL Block Structure

• PL/SQL blocks contain three sections


1. Declare section
2. Executable section and
3. Exception-handling section.

• Declare Section - This is optional section Start with


key word Declare . Declare section is used to Declare
variables, constants, cursor.

• Execution Section – This Section is Compulsory


(mandatory ) . This section is start with keyword BEGIN
and ends with END . The Program Logic is Written in
this section.
K. K. WAGH POLYTECHNIC, NASHIK
• PL /SQL Block Structure
DECLARE – Optional

/*Variables, cursors, user-defined


exceptions

BEGIN – Mandatory

/* SQL statement , PL/SQL


statements

EXCEPTION – Optional

/* Actions to perform when errors Every statement in each


occur section is end with a
END ; – Mandatory
semicolon ;
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL Execution Environment

PL/SQL Block Of Code


Declare Oracle Engine
Procedural Statements;
Begin
Procedural Statements; PL/SQL Engine
SQL Statements;
Exceptions
SQL Statements;
END; SQL
Statement Executor

K. K. WAGH POLYTECHNIC, NASHIK


Variables And Datatypes
Variables are entities which stores certain type of values.
Variables must be declared before its use.

PL/SQL Variable Types


1.Scalar (char, varchar2, number, date, etc)
2.Composite (%rowtype)
3.Reference (pointers)
4.LOB (large objects)

K. K. WAGH POLYTECHNIC, NASHIK


PL/SQL Data types :

1)Char(size): This data type is used to store strings values of fixed


length. The size in brackets determines the number of characters
the cell can hold. It can hold maximum 255 characters. Example :
char(50)

1) varchar (size)/varchar2(size): This data type is used to store


variable length alphanumeric data. The maximum this data type can
hold up to 4000 characters. Example : varchar2(80)

1) Date: This data type is used to represent date and time. The
Default format is : DD-MM-YY , Example : ‘20-oct-14’

1) Number(p,s): This data type is used to store fixed or floating


point numbers. P is the precision & S specifies scale. The maximum
precision is 38 digits. Example : number(5,2) , number(5).
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL Data types :

5) Long: This data type is used to store variable length character


strings containing up to 2 GB. Only one long Column allowed per
Table.

6)RAW :- This data type is used to store Binary Data such as


Digitized, Picture or Image Maximum storage up to 255 bytes.

6)RAW LONG : - This data type is used store Binary data such as
as Digitized, Picture or Image Maximum storage up to 2 GB.

6) BOOLEAN :- The PL/SQL data type BOOLEAN stores logical


values, which are the Boolean values TRUE

K. K. WAGH POLYTECHNIC, NASHIK


LOB Types

1)BLOB –This Data type is use to store Binary


Character Like Songs,video,Image maximum size up
to 4 GB.

1)CLOB – This data type is used to store Character


value maximum size up to 4 GB.

K. K. WAGH POLYTECHNIC, NASHIK


Reference Variables
• Reference variables directly reference specific database column
or row
• Reference variables assume data type of associated column or
row
• %TYPE data declaration syntax:

variable_name tablename.fieldname%TYPE;

• The (%TYPE) reference data type specifies a variable that


references a single DB field.
Empid emp.empno%TYPE;

• The empid variable assumes a data type of VARCHAR2(30),


because this is the data type of the empno in the emp table .

K. K. WAGH
POLYTECHNIC, NASHIK
GENERATING OUTPUT
SET SERVEROUTPUT ON;
Put the command at the beginning of the
program, right before the declaration section.

K. K. WAGH POLYTECHNIC, NASHIK


Displaying the output
DBMS_OUTPUT.PUT_LINE(<string>);
• In which PUT_LINE is the procedure to generate
the output on the screen, and DBMS_OUTPUT is
the package to which the PUT_LINE belongs.
DBMS_OUTPUT_PUT_LINE(‘My age is ‘||num_age);

K. K. WAGH POLYTECHNIC, NASHIK


PL/SQL is strongly typed
• All variables must be declared before their
use.
Variable_name datatype(size);
Variable_name datatype(size) :=value;
• The assignment statement
:=
is not the same as the equality operator
=
• All statements end with a ;
K. K. WAGH POLYTECHNIC, NASHIK
TO Run the PL/SQL Block you may need to Type / at the
End of PL /SQL block.

when PL/SQL is executed it prompts ,the output .

K. K. WAGH POLYTECHNIC, NASHIK


PL/SQL Example ‘ Wel Come To PL/SQL Programming ’.

SQL > SET SERVEROUTPUT ON;

SQL> DECLARE

Message varchar2(40) : = 'Wel come To PL/SQL Programming ';

BEGIN

dbms_output.put_line(Message);

END;
/

Output as follows :

Wel come To PL/SQL Programming

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
Program for addition of two numbers

SQL > SET SERVEROUTPUT ON;


SQL> declare
2 a number(10);
3 b number(10);
4 c number(10);
5 begin
6 a := &a;
7 b:= &b;
8 c:= a+b;
9 dbms_output.put_line('Addition is'||c);
10 end;
11 /
K. K. WAGH POLYTECHNIC, NASHIK
Output
Enter value for a: 2

old 6: a := &a;
new 6: a := 2;

Enter value for b: 3

old 7: b:= &b;


new 7: b:= 3;
Addition is 5

PL/SQL procedure successfully completed


K. K. WAGH POLYTECHNIC, NASHIK
Program for area of circle

SQL> declare
2 radius number(3);
3 pi number:=3.14;
4 area number(8,3);
5 begin
6 radius:=& radius;
7 area:= pi * power(radius,2);
8 dbms_output.put_line('area of circle is' || area);
9 end;
10 /

Enter value for radius: 2


old 6: radius:=& radius;
new 6: radius:=2;
area of circle is12.56

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
Use of date datatype

SQL> declare
2 date1 date;
3 begin
4 date1 := sysdate +7;
5 dbms_output.put_line(date1);
6 end;
7 /

28-AUG-15

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
Use of string functions

SQL> declare
2 name varchar2(30);
3 begin
4 name := '& name';
5 dbms_output.put_line('name is' || lpad(name,15,'*'));
6 end;
7 /
Enter value for name: kunal
old 4: name := '& name';
new 4: name := „kunal';
name is**********kunal

PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


Program to increase the salary of employee from emp table

SQL> declare
2 newsal emp.sal%type;
3 val number;
4 begin
5 val:=& val;
6 update emp set sal= sal + val;
7 dbms_output.put_line( 'the salary is increased by' || val);
8 select sal into newsal from emp where ename= 'ajay';
9 dbms_output.put_line('salary of ajay is'|| newsal);
10 end;
11 /

K. K. WAGH POLYTECHNIC, NASHIK


Enter value for val: 200
old 5: val:=& val;
new 5: val:=200;
the salary is increased by200
salary of ajay is12900
PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


University Questions

1)Give 4 advantages of PL/SQL?


2)Which Command is used for displaying
the output in PL/SQL?
3)Draw the block structure of PL/SQL.
4)Explain with suitable diagram the
execution environment of PL/SQL.
5)Explain the block structure of PL/SQL?

K. K. WAGH POLYTECHNIC, NASHIK


CONTROL STRUCTURE
Control structure is used for decision
making and changing the control flow of
the program.

Conditional Control
1)IF - THEN
2)IF – THEN- ELSE
3)IF –THEN –ELSE –IF
K. K. WAGH POLYTECHNIC, NASHIK
1)IF - THEN
• An IF-THEN statement allows you to specify only
one group of actions to take.
• If condition is TRUE then statement get execute ,if
False then if statement does nothing .
Syntax:
IF <condition> then

Statements;

End IF ;

K. K. WAGH POLYTECHNIC, NASHIK


Program to find out whether second number is big.
SQL> declare
2 a number:=10;
3 b number:=20;
4 begin
5 if b > a then
6 dbms_output.put_line(' B is Big ');
7 end if;
8 end;
9 /
B is Big

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
2) IF – THEN- ELSE
If the value of condition is true, the statements run;
otherwise, the else_statements run
Syntax:
IF <Condition > then

statements;

Else

statements;
End if ;
K. K. WAGH POLYTECHNIC, NASHIK
Program for finding out greatest between two numbers.
Declare
A number(3);
B number(3);
Begin
A:=&A;
B:=&B;
If (A>B) then
Dbms_output.put_line(‘ Greater number=‘||A);
else
Dbms_output.put_line(‘ Greater number=‘||B);
End if;
End;
/ K. K. WAGH POLYTECHNIC, NASHIK
Enter value for a: 10
old 5: A:=&A;
new 5: A:=10;

Enter value for b: 20


old 6: B:=&B;
new 6: B:=20;

Greater number=20

PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


Program for finding out the character is vowel or consonent
SQL> declare
2 ch varchar2(30);
3 begin
4 ch:='&ch';
5 if (ch=‘a' or ch='i' or ch='e' or ch='o' or ch='u')
6 then
7 dbms_output.put_line(ch||'is a vowel');
8 else
9 dbms_output.put_line(ch||'is a not vowel');
10 end if;
11 end;
12 /
Enter value for ch: i
old 4: ch:='&ch';
new 4: a:=‘i';
i is a vowel
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL procedure successfully completed.
3)IF –THEN –ELSE –IF
The IF THEN ELSE IF statement runs the
first statements for which condition is true.
Remaining conditions are not evaluated. If
no condition is true, the else_statements run
Syntax :
IF < condition 1> Then
statements;
ELSE IF < condition 2> Then
statements;
ELSE IF < condition n> Then
statements;
ELSE
statements;
END IF; K. K. WAGH POLYTECHNIC, NASHIK
Program for finding out greatest between three numbers
SQL> declare
2 A number;
3 B number;
4 C number;
5 begin
6 A :=&a;
7 B :=&b;
8 C :=&c;
9 if ( A > B) and (A >C) then
10 dbms_output.put_line(' A IS BIG ');
11 else if ( B > A) and (B >C) then
12 dbms_output.put_line(' B IS BIG ');
13 else
14 dbms_output.put_line(' C IS BIG ');
15 end if;
16 end;
17 / K. K. WAGH POLYTECHNIC, NASHIK
Enter value for a: 20
Enter value for b: 30
Enter value for c: 40
C IS BIG
PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


Iterative Control
Iterative control Statements are used when we want
to repeat the execution of one or more statements for
specified number of times.
1)LOOP
2)While LOOP
3)FOR LOOP

K. K. WAGH POLYTECHNIC, NASHIK


1)LOOP
•A Simple Loop is used when a set of statements is to be
executed at least once before the loop terminates.
• An EXIT condition must be specified in the loop, When the
EXIT condition is satisfied the process exits from the loop.
Syntax :
LOOP
statements;
EXIT WHEN condition;
END LOOP;

K. K. WAGH POLYTECHNIC, NASHIK


Flowchart of Loop

K. K. WAGH POLYTECHNIC, NASHIK


Program to print the numbers from 1 to 5
SQL> declare
2 i number:=1;
3 begin Loop executes till the Condition
4 loop FALSE .
5 dbms_output.put_line(i); Once the Condition True it Come
6 i:=i+1; out From LOOP

7 EXIT WHEN i >5;


8 END LOOP;
9 end;
10 /

1
2
3
4
5
PL/SQL procedure successfully completed.
K. K. WAGH POLYTECHNIC, NASHIK
Program to print the numbers from 20 to 15 in reverse
SQL> declare
2 i number(10):=20;
3 begin
4 loop
5 dbms_output.put_line(i);
6 i:=i-1;
7 exit when i<15;
8 end loop;
9 end;
10 /

20
19
18
17
16
K. K. WAGH POLYTECHNIC, NASHIK
15
Program to print the even numbers from 1 to 10
SQL> declare
2 i number:=1;
3 begin
4 loop
5 if (mod(i,2)=0) then
6 dbms_output.put_line(i);
7 else
8 null;
9 end if;
10 i:=i+1;
11 exit when i>10;
12 end loop;
13 end;
14 /
2
4
6
8
10
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL procedure successfully completed.
2)While Loop

•A WHILE LOOP is used when a set of statements


has to be executed as long as a condition is true.
•The condition is evaluated at the beginning of each
iteration. The iteration continues until the condition
becomes false
The General Syntax to write a WHILE LOOP is:

WHILE <condition> LOOP

statements;

END LOOP;
K. K. WAGH POLYTECHNIC, NASHIK
Flowchart of While Loop

K. K. WAGH POLYTECHNIC, NASHIK


Program to print the numbers from 1 to 5

SQL> declare
2 a number :=1;
3 begin
4 while a <= 5 loop
5 dbms_output.put_line(a);
6 a:=a+1;
7 end loop;
8 end;
9 /

1
2
3
4
5 K. K. WAGH POLYTECHNIC, NASHIK
Program to find the factorial of number

SQL> declare
2 i number(10):=1;
3 fact number:=1;
4 num number(10);
5 begin
6 num:=&num;
7 while (i<=num) loop
8 fact:=fact*i;
9 i:=i+1;
10 end loop;
11 dbms_output.put_line(fact);
12 end;
13 /
Enter value for num: 5
old 6: num:=&num;
new 6: num:=5;
120
PL/SQL procedure successfully completed.
K. K. WAGH POLYTECHNIC, NASHIK
3)For Loop
•A FOR LOOP is used to execute a set of statements for a
predetermined number of times.
•Iteration occurs between the start and end integer values given.

The General Syntax to write a FOR LOOP is:

FOR counter IN [reverse] val1..val2 LOOP

statements;

END LOOP;

val1 - Start integer value.


val2 - End integer value.
K. K. WAGH POLYTECHNIC, NASHIK
Flowchart of For Loop

K. K. WAGH POLYTECHNIC, NASHIK


Program to print the numbers from 1 to 5

SQL> declare
2 a number (10);
3 begin
4 for a in 1..5 loop
5 dbms_output.put_line(a);
6 end loop;
7 end;
8 /
1
2
3
4
5

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
Program to print the sum of numbers from 1 to 10

SQL> declare
2 i number(10);
3 ans number(20):=0;
4 begin
5 for i in 1..10 loop
6 ans:= ans + i;
7 end loop;
8 dbms_output.put_line(ans);
9 end;
10 /
55
PL/SQL procedure successfully completed.
K. K. WAGH POLYTECHNIC, NASHIK
Program to print the numbers from 10 to 1 in reverse

SQL> declare
2 i number(10);
3 begin
4 for i in reverse 1..10 loop
5 dbms_output.put_line(i);
6 end loop;
7 end;
8 /
10
9
8
7
6
5
4
3
2
K. K. WAGH POLYTECHNIC, NASHIK
1
Sequential Control
•Changes the flow of control within the block.
•Entry point is markes using tag
<<userdefined name>
• GOTO Statement is used to jump to this label.
Syntax :

Begin
Statements;
GOTO Lablel_1;
Statements;
<<Lablel_1>>
Statements;
END;

K. K. WAGH POLYTECHNIC, NASHIK


SQL> declare
2 i number;
3 begin
4 for i in 1..10 loop
5 dbms_output.put_line(i);
6 if (i=5) then
7 goto label1;
8 else
9 null;
10 end if;
11 end loop;
12 <<label1>>
13 dbms_output.put_line('As i=5, label1 is displayed');
14 end;
15 /

K. K. WAGH POLYTECHNIC, NASHIK


1
2
3
4
5
As i=5, label1 is displayed

K. K. WAGH POLYTECHNIC, NASHIK


Exception handling:
Exception is nothing but an error.
When the system throws a warning or has an error it can
lead to an exception.
Such exception needs to be handled and can be defined
internally or user defined .
The Exception section start with the keyword EXCEPTION
and optional . Any ERROR in the program are handle in this
section

K. K. WAGH POLYTECHNIC, NASHIK


Syntax:

DECLARE

Declaration section

Begin

executable statement;

EXCEPTION

WHEN ex_name1 THEN

-Error handling statements/user defined action to be carried out;

END;
K. K. WAGH POLYTECHNIC, NASHIK
Predefined Exception Or System Defined Exceptions

System exception are automatically Raised by Oracle ,when


a Program violates a RDBMS rules .

The most common errors that can occurs during the


execution of PL/SQL. i.e no data found, zero divide and too
many rows etc.

K. K. WAGH POLYTECHNIC, NASHIK


zero divide exception

SQL> declare
2 a number;
3 begin
4 a:=10/0;
5 end;
6 /
declare
*
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at line 4

K. K. WAGH POLYTECHNIC, NASHIK


zero_divide Exception

SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:= a/b;
9 dbms_output.put_line(c);
10 exception
11 when zero_divide then
12 dbms_output.put_line('divisor is zero');
13 end;
14 /
K. K. WAGH POLYTECHNIC, NASHIK
Enter value for a: 6
old 6: a:=&a;
new 6: a:=6;

Enter value for b: 0


old 7: b:=&b;
new 7: b:=0;

divisor is zero

PL/SQL procedure
successfully completed.
K. K. WAGH POLYTECHNIC, NASHIK
SQL> select * from course;

CID SUB DURATION SID


---------- ---------- ---------- --
c001 RDM 48 1
c002 VB 45 2
c003 DSU 34 3
c004 PIC 40 4

K. K. WAGH POLYTECHNIC, NASHIK


NO_DATA_FOUND Exception

SQL> declare
2 c_id course.cid%type;
3 begin
4 select cid into c_id from course where
sub='VBS';
5 end;
6 /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
K. K. WAGH POLYTECHNIC, NASHIK
NO_DATA_FOUND Exception
SQL> declare
2 c_id course.cid%type;
3 begin
4 select cid into c_id from course where sub='VBS';
5 Exception
6 when NO_DATA_FOUND then
7dbms_output.put_line(' Data is No Found by Select Query');
8 end;
9 /

Data is No Found by Select Query

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
TOO_MANY_ROWS Exception

SQL> declare
2 c_id course.cid%type;
3 begin
4 select cid into c_id from course;
5 end;
6 /
declare
*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested
number of rows
ORA-06512: at line 4
K. K. WAGH POLYTECHNIC, NASHIK
TOO_MANY_ROWS Exception

SQL> declare
2 c_id course.cid%type;
3 begin
4 select cid into c_id from course;
5 exception
6 when TOO_MANY_ROWS then
7 dbms_output.put_line(' Many Rows are Fetched .... ');
8 end;
9 /

Many Rows are Fetched ....

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
User Defined Exceptions

K. K. WAGH POLYTECHNIC, NASHIK


Syntax:

DECLARE
<exception_name> exception ;
BEGIN
<SQL Sentences>;
if <condition> Then
Raise <exception_name>
End if;
EXCEPTION

WHEN <exception_name> THEN

-Error handling statements/user defined action to be carried


out;

END;
K. K. WAGH POLYTECHNIC, NASHIK
declare
my_exe Exception;
D1 course.duration%type;
begin
select duration into d1 from course where sid=3;
if d1 <40 then
raise my_exe;
end if;
exception
when my_exe then
dbms_output.put_line(' Duration is less than 40');
end;
/

Duration is less than 40


PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


Raise_Application_Error :
To display your own error message one can use the bulit in
RAISE_APPLICATION_ERROR.

Use negative number between -20000 to -20999 for the


Error_number and the error message should not exceed 512
character.

Syntax :

RAISE_APPLICATION_ERROR( error_number,’error message’);

K. K. WAGH POLYTECHNIC, NASHIK


SQL> declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:= a/0;
7 exception
8 when zero_divide then
9 raise_application_error(-20202,'divisor is zero');
10 end;
11 /
Enter value for a: 2
old 5: a:=&a;
new 5: a:=2;
declare
*
ERROR at line 1:
ORA-20202: divisor is zero
ORA-06512: at line 9 K. K. WAGH POLYTECHNIC, NASHIK
SQL >declare
1 dur course.duration%type;
2 begin
3 select duration into dur from course where sid=6;
4 Exception
5 when NO_DATA_FOUND then
6 Raise_application_error(-20100,'NO Data Found');
7 end;
8/
ERROR at line 1:
ORA-20100: NO Data Found
ORA-06512: at line 6

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
SQL> declare
2 no1 s1.no%type;
3 exe exception;
4 begin
5 select no into no1 from s1 where name='nikita';
6 if (no1>1) then
7 raise exe;
8 end if;
9 exception
10 when exe then
11 raise_application_error(-20202,'number is greater than 1');
12 end;
13 /
declare
*
ERROR at line 1:
ORA-20202: number is greater than 1
ORA-06512: at line 11
K. K. WAGH POLYTECHNIC, NASHIK
CURSORS

1)Implicit
2) Explicit

K. K. WAGH POLYTECHNIC, NASHIK


CURSORS
• Cursor is a temporary work area created in the
system memory when SQL statement is executed.
• It is used to store the data retrieved from the
database and manipulate this data.
• The data stored in the cursor is called as Active
Data Set.
• A cursor can hold more than one row but can
process only one row at a time.
• Cursor is used with select Statement and store
result.
K. K. WAGH POLYTECHNIC, NASHIK
1) Implicit
• Implicit cursors are created for every query made
in Oracle Like Delete ,Update, Insert ,Select etc .
• When we write command ,we use implicit cursors.
• They are system generated cursors.
• Oracle will perform the open, fetches, and
close for you automatically.
• Implicit cursors are used in statements that
return only one row.
• The most recently opened cursor is called the
“SQL%” Cursor.
K. K. WAGH POLYTECHNIC, NASHIK
ATTRIBUTES OF IMPLICIT CURSOR

Attribute Description Format


%FOUND If SELECT statement return one or more rows SQL%FOUND
or DML statement (INSERT, UPDATE, DELETE)
affect one or more rows . IT return
TRUE otherwise return FALSE.

%NOTFOUND No rows found then Return TRUE SQL%NOTFOUND


Else Return False .

%ISOPEN Oracle engine automatically open the cursor SQL%ISOPEN


If cursor open return TRUE otherwise return
FALSE.

%ROWCOUNT Count the Row Affected by DML operations SQL%ROWCOUNT

K. K. WAGH POLYTECHNIC, NASHIK


SQL> select * from student1;

NO NAME MARKS
---------- -------------------- ----------
1 akash 85
2 nikita 65
3 puja 75
4 nisha 35
5 manas 50
6 akash 56
7 vijay 85

7 rows selected.

K. K. WAGH POLYTECHNIC, NASHIK


Count the No of Row Deleted from table using rowcount.

SQL> begin
2 delete from student1 where name='puja';
3 dbms_output.put_line('Number of rows
deleted:='||sql%rowcount);
4 end;
5 /
Number of rows deleted:=1

PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


SQL> select * from student1;

NO NAME MARKS
---------- -------------------- ----------
1 akash 85
2 nikita 65
4 nisha 35
5 manas 50
6 akash 56
7 vijay 85

6 rows selected.
K. K. WAGH POLYTECHNIC, NASHIK
Implicit cursors with update statement

SQL> begin
2 update student1 set marks=55 where no=4;
3 dbms_output.put_line('Number of rows updated:='||sql%rowcount);
4 end;
5 /

Number of rows updated:=1

PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


SQL> select * from student1;

NO NAME MARKS
---------- -------------------- ----------
1 akash 85
2 nikita 65
4 nisha 55
5 manas 50
6 akash 56
7 vijay 85

6 rows selected.

K. K. WAGH POLYTECHNIC, NASHIK


SQL> declare
2 rowcnt number(11);
3 begin
4 update student1 set marks=marks+1;
5 if (sql%found) then
6 rowcnt:=sql%rowcount;
7 dbms_output.put_line('Number of rows
updated:='||rowcnt);
8 else if (sql%notfound) then
9 dbms_output.put_line('no rows updated');
10 end if;
11 end if;
12 end;
13 /
Number of rows updated:=6

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
SQL> select * from student1;

NO NAME MARKS
---------- -------------------- ----------
1 akash 86
2 nikita 66
4 nisha 56
5 manas 51
6 akash 57
7 vijay 86

6 rows selected.

K. K. WAGH POLYTECHNIC, NASHIK


2) Explicit Cursor.
Cursors can be declared by a programmer within PL/SQL

They must be created when you are executing a SELECT


statement that returns more than one row.

 Even though the cursor stores multiple records, only


one record can be processed at a time, which is called as
current row.

When you fetch a row the current row position moves


to next row.
K. K. WAGH POLYTECHNIC, NASHIK
Explicit Cursor Operations
• Think of the context area (named by the cursor)
as a box, and the active set as the contents of
the box.
– To get at the data, we must OPEN the box and
– FETCH each row from the box one at a time.
– When finished, we must CLOSE the box.

K. K. WAGH POLYTECHNIC, NASHIK


Steps for Creating Explicit Cursors
1) Declare Cursor
Defines name and structure of cursor.
Syntax:
Cursor <cursor_name> IS Select statement ;
Example:
Cursor c1 is select name,marks from student1;

2) Open
Syntax:
Open <Cursor_name>;
Example:
open c1;

K. K. WAGH POLYTECHNIC, NASHIK


3) Fetch Data from cursor
Syntax:
fetch <Cursor_name>into <Variable_name>;
Example:
fetch c1 into var1;

4) Close
Syntax:
close <Cursor_name>;
Example:
close c1;
K. K. WAGH POLYTECHNIC, NASHIK
SQL> select * from student1;

NO NAME MARKS
---------- -------------------- ----------
1 akash 85
2 nikita 65
3 puja 75
4 nisha 35
5 manas 50
6 akash 56
7 vijay 85

7 rows selected.

K. K. WAGH POLYTECHNIC, NASHIK


SQL> declare
2 cursor cs1 is select name,marks from student1;
3 info cs1%rowtype;
4 begin
5 open cs1;
6 loop
7 fetch cs1 into info;
8 dbms_output.put_line(info.name || info.marks);
9 exit when cs1%notfound;
10 end loop;
11 close cs1;
12 end;
13 /
akash 85
nikita 65
puja 75
nisha 35
manas 50
akash 56
vijay 85
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL procedure successfully completed.
Parameterized Cursor:
1. DECLARE
2. cursor c(no number) is select * from emp_information where emp_no = no;
3. tmp emp_information%rowtype;
4. BEGIN
5. OPEN c(4);
6. FOR tmp IN c(4) LOOP
7. dbms_output.put_line('EMP_No: '||tmp.emp_no);
8. dbms_output.put_line('EMP_Name: '||tmp.emp_name);
9. dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
10.dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
11 END Loop;
12 CLOSE c;
13END;
/
EMP_No: 4
EMP_Name: Zenia Sroll
EMP_Dept: Web Developer
EMP_Salary: 42k
K. K. WAGH POLYTECHNIC, NASHIK
Procedure

A procedure is named PL/SQL block perform one or more specific task


.

Creating Procedure :

Procedure consist of Header and Body .

Header – Contain name of Procedure and Parameter


Passed to it.

Body - Contain Declaration ,Execution, Exception


section Same AS PL/SQL
K. K. WAGH POLYTECHNIC, NASHIK
Syntax :

Create OR Replace Procedure < name_Procedure>

[ Parameter name [IN | OUT | IN OUT] Data_type ]

[ IS | AS ]

Variable declaration;
Constant declarations;
Begin

Pl/sql subprogram;

END < name_Procedure> ;


K. K. WAGH POLYTECHNIC, NASHIK
Passing Parameter to Procedure by Following Way :

1)IN - This Parameter are used to send the Value to


Procedure .

2) Out - This Parameter are used to Get the Value


From Procedure .

3) IN OUT - This Parameter are used to get and send


the Value to Procedure if IN and OUT data
type is same .

K. K. WAGH POLYTECHNIC, NASHIK


Query :

Write a program to insert the record into


table through procedure

K. K. WAGH POLYTECHNIC, NASHIK


SQL> create or replace procedure ins21(no1 in
number,name1 in varchar2,marks1 in number) as
2 begin
3 insert into student1 values(no1,name1,marks1);
4 dbms_output.put_line(‘record inserted’);
4 end ins21;
5 /
Procedure created.

SQL> exec ins21(12,'punam',75);


record inserted
PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


SQL> select * from student1;

NO NAME MARKS
---------- -------------------- ----------
1 akash 85
2 nikita 65
3 puja 75
4 nisha 35
5 manas 50
6 akash 56
7 vijay 85
65 prakash 95
12 punam 75
7 rows selected.

K. K. WAGH POLYTECHNIC, NASHIK


Query :

Write a program to delete the record from


table through procedure

K. K. WAGH POLYTECHNIC, NASHIK


SQL> create or replace procedure select3(name1 in
varchar) as
2 begin
3 delete from student1 where name=name1;
4 end select3;
5 /

Procedure created.

SQL> exec select3('puja');

PL/SQL procedure successfully completed.

K. K. WAGH POLYTECHNIC, NASHIK


Deleteting a Proceduer

To delete Procedure use Following Command


DROP Procedure <Procedure_name>;

K. K. WAGH POLYTECHNIC, NASHIK


Function
Function is named PL/SQL Block that accept the value and
Return only one value .
It is used for code reusability.

Synax:
SQL> create or replace function <Function_name>(Parameter
in Data type ) return Data Type
[IS | AS]
Variable declaration;
Constant declarations;
Begin
Pl/sql subprogram;
return Value ;
end <Funcation_name >;
K. K. WAGH POLYTECHNIC, NASHIK
Program to Find Square .
SQL> create or replace function sqr( no in number ) return number
2 AS
3 begin
4 return no*no;
5 end sqr;
6 /
Function created.

SQL> declare
2 val1 number;
3 begin
4 val1 :=&val1;
5 dbms_output.put_line(‘Square’ || sqr(val1));
6 end;
7 /
Enter value for val1: 4
Square 16 K. K. WAGH POLYTECHNIC, NASHIK
Program to Find area of circle

SQL> create or replace function area20(r1 in number) return number as


2 pi number :=3.14;
3 area number(10);
4 begin
5 area:=pi*r1*r1;
6 return area;
7 end area20;
8 /
Function created.

SQL> declare
2 a number(10);
3 begin
4 a:=area20(2);
5 dbms_output.put_line('area is'||a);
6 end;
7 /
area is13
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL procedure successfully completed.
Program to Find area of circle

SQL> create or replace function area13(rad in number) return number as


2 pi number:=3.14;
3 begin
4 return pi*power(rad,2);
5 end area13;
6 /

Function created.

SQL> declare
2 r1 number;
3 begin
4 r1:=&r1;
5 dbms_output.put_line('area is'||area13(r1));
6 end ;
7 /
Enter value for r1: 2
old 4: r1:=&r1;
new 4: r1:=2;
area is12.56

PL/SQL procedure successfully completed.


K. K. WAGH POLYTECHNIC, NASHIK
Program to Find addition of numbers
SQL> create or replace function add1(a in number,b in number)
return number as
2 c number(10);
3 begin
4 c:=a+b;
5 return c;
6 end add1;
7 /

Function created.

SQL> declare
2 result number(20);
3 begin
4 result:=add1(10,30);
5 dbms_output.put_line('addition is'||result);
6 end;
7 /
addition is 40
PL/SQL procedure successfully completed.
K. K. WAGH POLYTECHNIC, NASHIK
Write a function which will count the number of rows deleted
SQL> create or replace function del(name1 in varchar2)return number as
2 no number(10);
3 begin
4 delete from mp1 where name=name1;
5 no:=sql%rowcount;
6 return no;
7 end del;
8 /

Function created.

SQL> declare
2 a number;
3 begin
4 a:=del(‘manas');
5 dbms_output.put_line(‘number of rows deleted :’||a);
6 end;
7 /
number of rows deleted :1
K. K. WAGH POLYTECHNIC, NASHIK
PL/SQL procedure successfully completed.
Difference between procedures and functions

1.A function must return a value back to caller.


2.A function return only one value to the calling
PL/SQL block

1.Procedure may or may not be return the value.


2.By defining the OUT parameters multiple
values can be passed to the procedure.

K. K. WAGH POLYTECHNIC, NASHIK


ADVANTAGES OF USING A PROCEDURE AND FUNCTION

1. Security
Procedures and functions can help to enforce data security.
2. Performance
It improves database performance.
Amount of information sent over the network is less.
No compilation is required to execute the code.
3. Memory Allocation
Due to only one copy of procedure and functions need to load ,
the amount of memory used reduces
4. Productivity
By writing procedures and functions redundant coding can be
avoided.
5. Integrity
It increases the integrity of data.

K. K. WAGH POLYTECHNIC, NASHIK


Database Trigger

Database Tigger - is PL/SQL Block that Is


Executed On an Event in the Database .
It is fired when DML statement like
insert,update,delete executed.

Event - Data Manipulation of a Table such as


Inserting,Deleting or Updating a Row of Table.

A trigger is triggered automatically


when an associated DML statement is
executed. K. K. WAGH POLYTECHNIC, NASHIK
Types of PL/SQL Triggers

There are two types of triggers based on the which level it is


triggered.

1) Row level trigger - An event is triggered for each row


upated, inserted or deleted.

2) Statement level trigger - An event is triggered for each sql


statement executed.

K. K. WAGH POLYTECHNIC, NASHIK


Syntax for Creating a Trigger
SQL> CREATE [OR REPLACE ] TRIGGER <trigger_name >

{ BEFORE | AFTER}

{ INSERT [OR] | UPDATE [OR] | DELETE }

[OF col_name]

ON <table_name >

[FOR EACH ROW]

WHEN (condition)

BEGIN

--- sql statements

END;
/
K. K. WAGH POLYTECHNIC, NASHIK
CREATE [OR REPLACE ] TRIGGER trigger_name - This
clause creates a trigger with the given name or overwrites an
existing trigger with the same name.

{BEFORE | AFTER } - This clause indicates at what time


should the trigger get fired. i.e for example : before(validation
purpose) or after updating a table.

{INSERT [OR] | UPDATE [OR] | DELETE} - This clause


determines the triggering event. More than one triggering
events can be used together separated by OR keyword.

K. K. WAGH POLYTECHNIC, NASHIK


[OF col_name] - This clause is used when you want to
trigger an event only when a specific column is updated.

[ON table_name] - This clause identifies the name of the


table or view to which the trigger is associated.

[FOR EACH ROW] - This clause is used to determine


whether a trigger must fire when each row gets affected ( i.e.
a Row Level Trigger)

WHEN (condition) - This clause is valid only for row level


triggers. The trigger is fired only for rows that satisfy the
condition specified.
K. K. WAGH POLYTECHNIC, NASHIK
SQL> create trigger studtrigger
2 after insert or update on student1
3 for each row
4 begin
5 if(:new.marks<40) then
6 dbms_output.put_line('fail');
7 else
8 dbms_output.put_line('pass');
9 end if;
10 end;
11 /

Trigger created.
K. K. WAGH POLYTECHNIC, NASHIK
SQL> insert into student1 values(9,'amin',30);
fail

1 row created.

SQL> insert into student1 values(10,'neeta',80);


pass

1 row created.

K. K. WAGH POLYTECHNIC, NASHIK


SQL> update student1 set marks=46 where marks=20;
pass

1 row updated.

SQL> update student1 set marks=15 where marks=46;


fail

1 row updated.

K. K. WAGH POLYTECHNIC, NASHIK


Comparison of procedures and triggers

Database Trigger Procedure

Triggers are fired when Procedures are executed when


particular SQL command(DML) is they are called
executed

Triggers have event and actions Procedures do not have event


and actions

Triggers are called implicitly Procedures are called explicitly

K. K. WAGH POLYTECHNIC, NASHIK


Use of database triggers

1. Triggers can be used to prevent invalid transaction


and to apply complex security authorization.
2. It can be used to various integrity constraint.
3. It can be used to check data modifications.

K. K. WAGH POLYTECHNIC, NASHIK


5. Remove the Trigger .

SQL> Drop Trigger <Trigger_name>;

E.g.

SQL> DROP TRIGGER studtrigger ;

Trigger dropped.

K. K. WAGH POLYTECHNIC, NASHIK

You might also like