SlideShare a Scribd company logo
PL/SQL
Overview..
 Introduction
 PL/SQL Block Structure
 PL/SQL Variables
 PL/SQL IF Statement
 PL/SQL Loop Statement:
 PL/SQL WHILE Loop Statement PL/SQL FOR Loop
Statement.
 PL/SQL Function ; PL/SQL Procedure
 Exceptions
 Cursors and Triggers
About SQL
 The purpose of SQL is to provide an interface to a
relational database such as Oracle Database,
and all SQL statements are instructions to the
database.
 The strengths of SQL provide benefits for all
types of users, including application
programmers, database administrators,
managers, and end users.
Why PL/SQL?
How can we have a chain of SQL statements which produce
result according to the output of previous queries?
How can we take any smart decisions based on users input
or based on output on previous queries..?
How can we automate any task using SQL?
Introduction
• The PL/SQL programming language was
developed by Oracle Corporation in the late
1980s as procedural extension language for
SQL and the Oracle relational database.
• PL/SQL, supplement SQL with standard
programming-language features like:
• Block (modular) structure
• Flow-control statements and loops
• Variables, constants, and types
• Structured data
• Customized error handling
Why PL/SQL?
• The purpose of PL/SQL is to combine database
language and procedural programming
language.
• By extending SQL, PL/SQL offers a unique
combination of power and ease of use.
• PL/SQL fully supports all SQL data manipulation
statements.
• We can write procedures and functions which
can be invoked from different applications.
PL/SQL Block
• PL/SQL is a block-structured language.
• Each program written in PL/SQL is written as a
block.
• Blocks can also be nested.
• Each block is meant for a particular task.
PL/SQL Block Structure
IS
BEGIN
EXCEPTION
END;
Header (named blocks only)
Declare Section
Execution Section
Exception Section
Header Section
Relevant for named blocks only
Stored procedures (used to perform repetitive code.)
Stored functions (used to return value to the calling block),
Packages (allows related objects to be stored together),
Triggers (pl/sql block executed implicitly whenever the
triggering event takes place).
Determines the way that the named block or program
must be called.
Includes the name, parameter list, and RETURN clause (for
a function only).
• Header Section: Example
• Below is header section of stored procedure:
CREATE OR REPLACE PROCEDURE
print ( p_num NUMBER ) …
• Below is header section of stored function:
CREATE OR REPLACE FUNCTION
add ( p_num1 NUMBER, p_num2 NUMBER )
RETURN NUMBER …
Declare Section
 Relevant for anonymous blocks.
 Contains declarations of variables, constants,
cursors, user-defined exceptions and types.
 Optional section , but if you have one, it must
come before the execution and exception sections.
DECLARE
v_name VARCHAR2(35);
v_id NUMBER := 0;
Execution Section
 Mandatory section of PLSQL block
 Contains SQL statements to manipulate data in the
database
 Contains PL/SQL statements to manipulate data in the
block.
 Every block must have at least one executable
statement in the execution section.
BEGIN
SELECT ename
INTO v_ename
FROM emp
WHERE empno = 7900 ;
DBMS_OUTPUT.PUT_LINE
(‘Employee name :’ || v_ename);
END;
Exception Section
 The last section of the PL/SQL block.
 It contains statements that are executed when a runtime
error occurs within a block.
 An optional section.
 Control is transferred to this section when an run time
error is encountered and it is handled
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
(‘ There is no employee with Employee no 7900 ’);
END;
PL/SQL Variables
• These are placeholders that store the values that can change
through the PL/SQL Block
• PL/SQL lets you declare constants and variables, then use
them in SQL and procedural statements anywhere an
expression can be used
• A constant or variable must be declared before referencing it in
other statements
Syntax for declaring variables
variable_name [CONSTANT] datatype
[NOT NULL] [:= expr | DEFAULT expr]
Note: Square brace indicates optional
• Variable_name is the name of the variable.
• Datatype is a valid PL/SQL datatype.
• NOT NULL is an optional specification on the
variable.
• A value or DEFAULT value is also an optional
specification, where you can initialize a variable.
• Each variable declaration is a separate statement
and must be terminated by a semicolon.
• CONSTANT keyword is used to declare constants.
PL/SQL variables
• Valid variable declarations

 DECLARE
 v_Activedate DATE;
 V_cust_id NUMBER(2) NOT NULL := 10;
 V_Address VARCHAR2(13) := ’Pune’;
 V_sr_id NUMBER DEFAULT 201;
 V_Name VARCHAR2(20) DEFAULT ‘Aditya’
• Valid constant declaration

 c_constant CONSTANT NUMBER := 1400;
• Invalid Declarations
v_cust_id NUMBER(2) NOT NULL;
v_name VARCHAR2 DEFAULT ‘Sachin’;
c_constant CONSTANT NUMBER ;
c_constant NUMBER CONSTANT;
Guidelines for Declaring PL/SQL
Variables
• Follow the naming Rules
 The variable name must be less than 31 characters
 The starting of a variable must be an ASCII letter
 It can be either lowercase or uppercase
 A variable name can contain numbers, underscore, and dollar sign
characters followed by the first character
• Follow the naming conventions
• Initialize variables designated as NOT NULL and CONSTANT
• Declare one identifier per line
• Initialize identifiers by using the assignment operator (:=) or the
reserved word “DEFAULT”
Declaring variable of record type :
Example
DECLARE
-- Type declaration
TYPE EmpRec IS RECORD(
empno emp.empno%TYPE,
ename emp.ename%TYPE,
salary emp.sal%TYPE
);
-- Record type variable declaration
V_emp_Rec emprec;
V_emp_Rec
empno number(10)
ename varchar2(25)
salary varchar2(75)
Sample program of PL/SQL
Program using variables
DECLARE
X NUMBER(3) := 10;
Y NUMBER(3) := 20;
BEGIN
DBMS_OUTPUT.PUT_LINE
(‘The value of variable X is : ‘ || X);
DBMS_OUTPUT.PUT_LINE
(‘The value of variable Y is : ‘ || Y);
END;
Accepting variables from users
DECLARE
v_num1 NUMBER(3):=&n1;
v_num2 NUMBER(3):=&n2;
IS
BEGIN
DBMS_OUTPUT.PUT_LINE
(‘The value of variable v_num1 is : ‘ || v_num1);
DBMS_OUTPUT.PUT_LINE
(‘The value of variable v_num2 is : ‘ || v_num2);
END;
PL/SQL Control Structures
• PL/SQL, like other 3GL has a variety of control
structures which include
• Conditional statements
o IF
o CASE
• Loops
o Simple loop
o While loop
o For loop
IF .. End if
 Syntax
IF condition THEN
Statements;
ELSE
Statements;
END IF;
Simple example
-- Block to demonstrate IF...ELSE...END IF
DECLARE
v_empno emp.empno%TYPE;
v_comm emp.comm%TYPE;
BEGIN
SELECT comm INTO v_comm FROM emp
WHERE empno = v_empno;
IF v_comm IS NULL THEN
DBMS_OUTPUT.PUT_LINE
(‘This employee doesnt get commission');
ELSE
DBMS_OUTPUT.PUT_LINE
 (‘This employee gets commission’);
END IF;
DBMS_OUTPUT.PUT_LINE
('This line executes irrespective of the condition');
END;
PL/SQL Loop Control Structures
 LOOP Statements
• Simple Loops
• WHILE Loops
• FOR Loops
LOOP Statements
• Simple Loops
Note: Add EXIT statement to exit from the loop
• WHILE Loops
Note: Condition is evaluated before each iteration of the loop
LOOP
Sequence_of_statements;
END LOOP;
WHILE condition
LOOP
Statements;
END LOOP;
Loop Example
DECLARE
v_i NUMBER(2) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
EXIT WHEN v_i = 10;
v_i:=v_i+1;
END LOOP;
END;
While loop example
DECLARE
v_i NUMBER(2) := 1;
BEGIN
WHILE ( v_i <= 10 )
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
v_i:=v_i+1;
END LOOP;
END;
For loop
• The number of iterations for simple loops and WHILE loops is not known in
advance, it depends on the loop condition. Numeric FOR loops, on the
other hand, have defined number of iterations.
 Where:
• counter: is an implicitly declared integer whose value
automatically increases or decreases by 1 on each iteration
• REVERSE: causes the counter to decrement from upper
bound to lower bound
• Low_bound: specifies the lower bound for the range of
counter values
• High_bound: specifies the upper bound for the range of
counter values
FOR counter IN [REVERSE] low_bound .. high_bound
LOOP
Statements;
END
For Loop example
BEGIN
FOR v_i IN 1..10
/* The LOOP VARIABLE v_i of
type BINARY_INTEGER is declared
automatically */
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
END LOOP;
END;
For Loop with EXIT condition
DECLARE
myNo NUMBER(5):= &myno;
counter NUMBER(5):=1;
BEGIN
FOR i IN 2..myNo-1
LOOP
counter:= counter+1;
EXIT WHEN myNo mod i = 0;
END LOOP;
IF counter = myNo-1 THEN
DBMS_OUTPUT.PUT_LINE( 'The given
number is prime' );
ELSE
DBMS_OUTPUT.PUT_LINE('The given number is
not
a prime number' );
END IF;
END;
Procedures
 A Procedure is a subprogram unit that consists of a group of
PL/SQL statements. Each procedure in Oracle has its own
unique name by which it can be referred. This subprogram unit is
stored as a database object. Below are the characteristics of this
subprogram unit.
 CREATE OR REPLACE PROCEDURE
 <procedure_name>
 (
 <parameterl IN/OUT <datatype>
 )
 [ IS | AS ]
 <declaration_part>
 BEGIN
 <execution part>
 EXCEPTION
 <exception handling part>
 END;
What is Function
 Functions is a standalone PL/SQL subprogram.
Like PL/SQL procedure, functions have a unique
name by which it can be referred. These are
stored as PL/SQL database objects. Below are
some of the characteristics of functions.
 CREATE OR REPLACE FUNCTION
<procedure_name>(<parameterl IN/OUT
<datatype>)RETURN <datatype>[ IS | AS
]<declaration_part>BEGIN<execution part>
EXCEPTION<exception handling part>END;
PLSQL.pptx
Add two numbers
declare
-- declare variable x, y
-- and z of datatype number
x number(5);
y number(5);
z number(7);
begin
-- Here we Assigning 10 into x
x:=10;
-- Assigning 20 into x
y:=20;
-- Assigning sum of x and y into z
z:=x+y;
-- Print the Result
dbms_output.put_line('Sum is '||z);
end;
 Swapping:
-- declare variable num1, num2
-- and temp of datatype number
num1 number;
num2 number;
temp number;
begin
num1:=1000;
num2:=2000;
-- print result before swapping
dbms_output.put_line('before');
dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);
-- swapping of numbers num1 and num2
temp := num1;
num1 := num2;
num2 := temp;
-- print result after swapping
dbms_output.put_line('after');
dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);
end;
Prime Number
declare
-- declare variable n, i
-- and temp of datatype number
n number;
i number;
temp number;
begin
-- Here we Assigning 13 into n
n := 13;
-- Assigning 2 to i
i := 2;
-- Assigning 1 to temp
temp := 1;
-- loop from i = 2 to n/2
for i in 2..n/2
loop
if mod(n, i) = 0
then
temp := 0;
exit;
end if;
end loop;
if temp = 1
then
dbms_output.put_line('true');
else
dbms_output.put_line('false');
end if;
end;
-- Program End
Fibonocci
declare
-- declare variable first = 0,
-- second = 1 and temp of datatype number
first number := 0;
second number := 1;
temp number;
n number := 5;
i number;
begin
dbms_output.put_line('Series:');
--print first two term first and second
dbms_output.put_line(first);
dbms_output.put_line(second);
-- loop i = 2 to n
for i in 2..n
loop
temp:=first+second;
first := second;
second := temp;
--print terms of fibonacci series
dbms_output.put_line(temp);
end loop;
end;
--Program End
Factorial
declare
-- it gives the final answer after computation
fac number :=1;
-- given number n
-- taking input from user
n number := &1;
-- start block
begin
-- start while loop
while n > 0 loop
-- multiple with n and decrease n's value
fac:=n*fac;
n:=n-1;
end loop;
-- end loop
-- print result of fac
dbms_output.put_line(fac);
-- end the begin block
end;
Max of two numbers:
1.ECLARE
2. N NUMBER;
3. M NUMBER;
4.BEGIN
5. DBMS_OUTPUT.PUT_LINE('ENTER A
NUMBER');
6. N:=&NUMBER;
7. DBMS_OUTPUT.PUT_LINE('ENTER A
NUMBER');
8. M:=&NUMBER;
9.IF N<M THEN
10. DBMS_OUTPUT.PUT_LINE(''|| N ||' IS
GREATER THAN '|| M ||'');
11.ELSE
12. DBMS_OUTPUT.PUT_LINE(''|| M ||' IS
GREATER THAN '|| N ||'');
13.END IF;
14.END;
15./
Sum of N natural numbers
Even or Odd
DECLARE
-- Declare variable n, s, r, len
-- and m of datatype number
n NUMBER := 1634;
r NUMBER;
BEGIN
-- Calculating modulo
r := MOD(n, 2);
IF r = 0 THEN
dbms_output.Put_line('Even');
ELSE
dbms_output.Put_line('Odd');
END IF;
END;
--End program
Leap year
-- To check if a
-- given year is leap year or not
DECLARE
year NUMBER := 1600;
BEGIN
-- true if the year is a multiple
-- of 4 and not multiple of 100.
-- OR year is multiple of 400.
IF MOD(year, 4)=0
AND
MOD(year, 100)!=0
OR
MOD(year, 400)=0 THEN
dbms_output.Put_line(year
|| ' is a leap year ');
ELSE
dbms_output.Put_line(year
|| ' is not a leap year.');
END IF;
END;

More Related Content

PPT
plsql.ppt
faizan992426
 
PPT
SQL / PL
srijanani2030
 
PDF
rdbms.pdf plsql database system notes for students to study
rarelyused
 
ODP
Open Gurukul Language PL/SQL
Open Gurukul
 
PPTX
Pl sql Prograaming of Database management system
AjitPatil801582
 
PPT
PLSQL (1).ppt
MadhuriAnaparthy
 
PPTX
PL_SQL - II.pptx
priyaprakash11
 
PPTX
Pl-sql blocks and block types and variablesdeclaring.pptx
abobakralwaylysocial
 
plsql.ppt
faizan992426
 
SQL / PL
srijanani2030
 
rdbms.pdf plsql database system notes for students to study
rarelyused
 
Open Gurukul Language PL/SQL
Open Gurukul
 
Pl sql Prograaming of Database management system
AjitPatil801582
 
PLSQL (1).ppt
MadhuriAnaparthy
 
PL_SQL - II.pptx
priyaprakash11
 
Pl-sql blocks and block types and variablesdeclaring.pptx
abobakralwaylysocial
 

Similar to PLSQL.pptx (20)

PDF
Assignment#08
Sunita Milind Dol
 
PDF
PL-SQL.pdf
Anas Nakash
 
PPTX
PLSQLmy Updated (1).pptx
vamsiyadav39
 
PDF
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
PPT
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
PPT
L9 l10 server side programming
Rushdi Shams
 
PPTX
PL_SQL_1.pptx fvbxcfbhxdfgh .
RAMIROENRIQUERAMALLO
 
PPT
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
Noorien3
 
PPTX
PL SQL.pptx in computer language in database
ironman82715
 
PDF
Meg bernal insight2014 4219
Peter Schouboe
 
DOC
3963066 pl-sql-notes-only
Ashwin Kumar
 
PDF
Pl sql programme
Dhilip Prakash
 
PDF
Pl sql programme
Dhilip Prakash
 
PPT
Chapter8 pl sql
Jafar Nesargi
 
PPT
Triggers n Cursors.ppt
VADAPALLYPRAVEENKUMA1
 
PPT
Plsql
fika sweety
 
PDF
plsql notes.pdf for students Oracle databases
azkacade16
 
PPT
pl_sql.ppt
Prabhat106214
 
PDF
Programming in Oracle with PL/SQL
lubna19
 
PPTX
PLSQL Tutorial
Quang Minh Đoàn
 
Assignment#08
Sunita Milind Dol
 
PL-SQL.pdf
Anas Nakash
 
PLSQLmy Updated (1).pptx
vamsiyadav39
 
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
L9 l10 server side programming
Rushdi Shams
 
PL_SQL_1.pptx fvbxcfbhxdfgh .
RAMIROENRIQUERAMALLO
 
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
Noorien3
 
PL SQL.pptx in computer language in database
ironman82715
 
Meg bernal insight2014 4219
Peter Schouboe
 
3963066 pl-sql-notes-only
Ashwin Kumar
 
Pl sql programme
Dhilip Prakash
 
Pl sql programme
Dhilip Prakash
 
Chapter8 pl sql
Jafar Nesargi
 
Triggers n Cursors.ppt
VADAPALLYPRAVEENKUMA1
 
plsql notes.pdf for students Oracle databases
azkacade16
 
pl_sql.ppt
Prabhat106214
 
Programming in Oracle with PL/SQL
lubna19
 
PLSQL Tutorial
Quang Minh Đoàn
 
Ad

Recently uploaded (20)

PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
How to Apply for a Job From Odoo 18 Website
Celine George
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
CDH. pptx
AneetaSharma15
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
How to Apply for a Job From Odoo 18 Website
Celine George
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
CDH. pptx
AneetaSharma15
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
Ad

PLSQL.pptx

  • 2. Overview..  Introduction  PL/SQL Block Structure  PL/SQL Variables  PL/SQL IF Statement  PL/SQL Loop Statement:  PL/SQL WHILE Loop Statement PL/SQL FOR Loop Statement.  PL/SQL Function ; PL/SQL Procedure  Exceptions  Cursors and Triggers
  • 3. About SQL  The purpose of SQL is to provide an interface to a relational database such as Oracle Database, and all SQL statements are instructions to the database.  The strengths of SQL provide benefits for all types of users, including application programmers, database administrators, managers, and end users.
  • 4. Why PL/SQL? How can we have a chain of SQL statements which produce result according to the output of previous queries? How can we take any smart decisions based on users input or based on output on previous queries..? How can we automate any task using SQL?
  • 5. Introduction • The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. • PL/SQL, supplement SQL with standard programming-language features like: • Block (modular) structure • Flow-control statements and loops • Variables, constants, and types • Structured data • Customized error handling
  • 6. Why PL/SQL? • The purpose of PL/SQL is to combine database language and procedural programming language. • By extending SQL, PL/SQL offers a unique combination of power and ease of use. • PL/SQL fully supports all SQL data manipulation statements. • We can write procedures and functions which can be invoked from different applications.
  • 7. PL/SQL Block • PL/SQL is a block-structured language. • Each program written in PL/SQL is written as a block. • Blocks can also be nested. • Each block is meant for a particular task.
  • 8. PL/SQL Block Structure IS BEGIN EXCEPTION END; Header (named blocks only) Declare Section Execution Section Exception Section
  • 9. Header Section Relevant for named blocks only Stored procedures (used to perform repetitive code.) Stored functions (used to return value to the calling block), Packages (allows related objects to be stored together), Triggers (pl/sql block executed implicitly whenever the triggering event takes place). Determines the way that the named block or program must be called. Includes the name, parameter list, and RETURN clause (for a function only).
  • 10. • Header Section: Example • Below is header section of stored procedure: CREATE OR REPLACE PROCEDURE print ( p_num NUMBER ) … • Below is header section of stored function: CREATE OR REPLACE FUNCTION add ( p_num1 NUMBER, p_num2 NUMBER ) RETURN NUMBER …
  • 11. Declare Section  Relevant for anonymous blocks.  Contains declarations of variables, constants, cursors, user-defined exceptions and types.  Optional section , but if you have one, it must come before the execution and exception sections. DECLARE v_name VARCHAR2(35); v_id NUMBER := 0;
  • 12. Execution Section  Mandatory section of PLSQL block  Contains SQL statements to manipulate data in the database  Contains PL/SQL statements to manipulate data in the block.  Every block must have at least one executable statement in the execution section. BEGIN SELECT ename INTO v_ename FROM emp WHERE empno = 7900 ; DBMS_OUTPUT.PUT_LINE (‘Employee name :’ || v_ename); END;
  • 13. Exception Section  The last section of the PL/SQL block.  It contains statements that are executed when a runtime error occurs within a block.  An optional section.  Control is transferred to this section when an run time error is encountered and it is handled EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE (‘ There is no employee with Employee no 7900 ’); END;
  • 14. PL/SQL Variables • These are placeholders that store the values that can change through the PL/SQL Block • PL/SQL lets you declare constants and variables, then use them in SQL and procedural statements anywhere an expression can be used • A constant or variable must be declared before referencing it in other statements
  • 15. Syntax for declaring variables variable_name [CONSTANT] datatype [NOT NULL] [:= expr | DEFAULT expr] Note: Square brace indicates optional • Variable_name is the name of the variable. • Datatype is a valid PL/SQL datatype. • NOT NULL is an optional specification on the variable. • A value or DEFAULT value is also an optional specification, where you can initialize a variable. • Each variable declaration is a separate statement and must be terminated by a semicolon. • CONSTANT keyword is used to declare constants.
  • 16. PL/SQL variables • Valid variable declarations   DECLARE  v_Activedate DATE;  V_cust_id NUMBER(2) NOT NULL := 10;  V_Address VARCHAR2(13) := ’Pune’;  V_sr_id NUMBER DEFAULT 201;  V_Name VARCHAR2(20) DEFAULT ‘Aditya’ • Valid constant declaration   c_constant CONSTANT NUMBER := 1400; • Invalid Declarations v_cust_id NUMBER(2) NOT NULL; v_name VARCHAR2 DEFAULT ‘Sachin’; c_constant CONSTANT NUMBER ; c_constant NUMBER CONSTANT;
  • 17. Guidelines for Declaring PL/SQL Variables • Follow the naming Rules  The variable name must be less than 31 characters  The starting of a variable must be an ASCII letter  It can be either lowercase or uppercase  A variable name can contain numbers, underscore, and dollar sign characters followed by the first character • Follow the naming conventions • Initialize variables designated as NOT NULL and CONSTANT • Declare one identifier per line • Initialize identifiers by using the assignment operator (:=) or the reserved word “DEFAULT”
  • 18. Declaring variable of record type : Example DECLARE -- Type declaration TYPE EmpRec IS RECORD( empno emp.empno%TYPE, ename emp.ename%TYPE, salary emp.sal%TYPE ); -- Record type variable declaration V_emp_Rec emprec; V_emp_Rec empno number(10) ename varchar2(25) salary varchar2(75)
  • 20. Program using variables DECLARE X NUMBER(3) := 10; Y NUMBER(3) := 20; BEGIN DBMS_OUTPUT.PUT_LINE (‘The value of variable X is : ‘ || X); DBMS_OUTPUT.PUT_LINE (‘The value of variable Y is : ‘ || Y); END;
  • 21. Accepting variables from users DECLARE v_num1 NUMBER(3):=&n1; v_num2 NUMBER(3):=&n2; IS BEGIN DBMS_OUTPUT.PUT_LINE (‘The value of variable v_num1 is : ‘ || v_num1); DBMS_OUTPUT.PUT_LINE (‘The value of variable v_num2 is : ‘ || v_num2); END;
  • 22. PL/SQL Control Structures • PL/SQL, like other 3GL has a variety of control structures which include • Conditional statements o IF o CASE • Loops o Simple loop o While loop o For loop
  • 23. IF .. End if  Syntax IF condition THEN Statements; ELSE Statements; END IF;
  • 24. Simple example -- Block to demonstrate IF...ELSE...END IF DECLARE v_empno emp.empno%TYPE; v_comm emp.comm%TYPE; BEGIN SELECT comm INTO v_comm FROM emp WHERE empno = v_empno; IF v_comm IS NULL THEN DBMS_OUTPUT.PUT_LINE (‘This employee doesnt get commission'); ELSE DBMS_OUTPUT.PUT_LINE  (‘This employee gets commission’); END IF; DBMS_OUTPUT.PUT_LINE ('This line executes irrespective of the condition'); END;
  • 25. PL/SQL Loop Control Structures  LOOP Statements • Simple Loops • WHILE Loops • FOR Loops
  • 26. LOOP Statements • Simple Loops Note: Add EXIT statement to exit from the loop • WHILE Loops Note: Condition is evaluated before each iteration of the loop LOOP Sequence_of_statements; END LOOP; WHILE condition LOOP Statements; END LOOP;
  • 27. Loop Example DECLARE v_i NUMBER(2) := 1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i); EXIT WHEN v_i = 10; v_i:=v_i+1; END LOOP; END;
  • 28. While loop example DECLARE v_i NUMBER(2) := 1; BEGIN WHILE ( v_i <= 10 ) LOOP DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i); v_i:=v_i+1; END LOOP; END;
  • 29. For loop • The number of iterations for simple loops and WHILE loops is not known in advance, it depends on the loop condition. Numeric FOR loops, on the other hand, have defined number of iterations.  Where: • counter: is an implicitly declared integer whose value automatically increases or decreases by 1 on each iteration • REVERSE: causes the counter to decrement from upper bound to lower bound • Low_bound: specifies the lower bound for the range of counter values • High_bound: specifies the upper bound for the range of counter values FOR counter IN [REVERSE] low_bound .. high_bound LOOP Statements; END
  • 30. For Loop example BEGIN FOR v_i IN 1..10 /* The LOOP VARIABLE v_i of type BINARY_INTEGER is declared automatically */ LOOP DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i); END LOOP; END;
  • 31. For Loop with EXIT condition DECLARE myNo NUMBER(5):= &myno; counter NUMBER(5):=1; BEGIN FOR i IN 2..myNo-1 LOOP counter:= counter+1; EXIT WHEN myNo mod i = 0; END LOOP; IF counter = myNo-1 THEN DBMS_OUTPUT.PUT_LINE( 'The given number is prime' ); ELSE DBMS_OUTPUT.PUT_LINE('The given number is not a prime number' ); END IF; END;
  • 32. Procedures  A Procedure is a subprogram unit that consists of a group of PL/SQL statements. Each procedure in Oracle has its own unique name by which it can be referred. This subprogram unit is stored as a database object. Below are the characteristics of this subprogram unit.  CREATE OR REPLACE PROCEDURE  <procedure_name>  (  <parameterl IN/OUT <datatype>  )  [ IS | AS ]  <declaration_part>  BEGIN  <execution part>  EXCEPTION  <exception handling part>  END;
  • 33. What is Function  Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique name by which it can be referred. These are stored as PL/SQL database objects. Below are some of the characteristics of functions.  CREATE OR REPLACE FUNCTION <procedure_name>(<parameterl IN/OUT <datatype>)RETURN <datatype>[ IS | AS ]<declaration_part>BEGIN<execution part> EXCEPTION<exception handling part>END;
  • 35. Add two numbers declare -- declare variable x, y -- and z of datatype number x number(5); y number(5); z number(7); begin -- Here we Assigning 10 into x x:=10; -- Assigning 20 into x y:=20; -- Assigning sum of x and y into z z:=x+y; -- Print the Result dbms_output.put_line('Sum is '||z); end;
  • 36.  Swapping: -- declare variable num1, num2 -- and temp of datatype number num1 number; num2 number; temp number; begin num1:=1000; num2:=2000; -- print result before swapping dbms_output.put_line('before'); dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2); -- swapping of numbers num1 and num2 temp := num1; num1 := num2; num2 := temp; -- print result after swapping dbms_output.put_line('after'); dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2); end;
  • 37. Prime Number declare -- declare variable n, i -- and temp of datatype number n number; i number; temp number; begin -- Here we Assigning 13 into n n := 13; -- Assigning 2 to i i := 2; -- Assigning 1 to temp temp := 1;
  • 38. -- loop from i = 2 to n/2 for i in 2..n/2 loop if mod(n, i) = 0 then temp := 0; exit; end if; end loop; if temp = 1 then dbms_output.put_line('true'); else dbms_output.put_line('false'); end if; end; -- Program End
  • 39. Fibonocci declare -- declare variable first = 0, -- second = 1 and temp of datatype number first number := 0; second number := 1; temp number; n number := 5; i number; begin dbms_output.put_line('Series:'); --print first two term first and second dbms_output.put_line(first); dbms_output.put_line(second); -- loop i = 2 to n for i in 2..n loop temp:=first+second; first := second; second := temp; --print terms of fibonacci series dbms_output.put_line(temp); end loop; end; --Program End
  • 40. Factorial declare -- it gives the final answer after computation fac number :=1; -- given number n -- taking input from user n number := &1; -- start block begin -- start while loop while n > 0 loop -- multiple with n and decrease n's value fac:=n*fac; n:=n-1; end loop; -- end loop -- print result of fac dbms_output.put_line(fac); -- end the begin block end;
  • 41. Max of two numbers: 1.ECLARE 2. N NUMBER; 3. M NUMBER; 4.BEGIN 5. DBMS_OUTPUT.PUT_LINE('ENTER A NUMBER'); 6. N:=&NUMBER; 7. DBMS_OUTPUT.PUT_LINE('ENTER A NUMBER'); 8. M:=&NUMBER; 9.IF N<M THEN 10. DBMS_OUTPUT.PUT_LINE(''|| N ||' IS GREATER THAN '|| M ||''); 11.ELSE 12. DBMS_OUTPUT.PUT_LINE(''|| M ||' IS GREATER THAN '|| N ||''); 13.END IF; 14.END; 15./
  • 42. Sum of N natural numbers
  • 43. Even or Odd DECLARE -- Declare variable n, s, r, len -- and m of datatype number n NUMBER := 1634; r NUMBER; BEGIN -- Calculating modulo r := MOD(n, 2); IF r = 0 THEN dbms_output.Put_line('Even'); ELSE dbms_output.Put_line('Odd'); END IF; END; --End program
  • 44. Leap year -- To check if a -- given year is leap year or not DECLARE year NUMBER := 1600; BEGIN -- true if the year is a multiple -- of 4 and not multiple of 100. -- OR year is multiple of 400. IF MOD(year, 4)=0 AND MOD(year, 100)!=0 OR MOD(year, 400)=0 THEN dbms_output.Put_line(year || ' is a leap year '); ELSE dbms_output.Put_line(year || ' is not a leap year.'); END IF; END;