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;
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

Similar to PLSQL.pptx

PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
vamsiyadav39
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
Vibrant Technologies & Computers
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
Rushdi Shams
 
PL SQL.pptx in computer language in database
PL SQL.pptx in computer language in databasePL SQL.pptx in computer language in database
PL SQL.pptx in computer language in database
ironman82715
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
Peter Schouboe
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
Ashwin Kumar
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
Dhilip Prakash
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
Dhilip Prakash
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
Jafar Nesargi
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
VADAPALLYPRAVEENKUMA1
 
Plsql
PlsqlPlsql
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
Prabhat106214
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
lubna19
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
Quang Minh Đoàn
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
Belal Arfa
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
PLSQL
PLSQLPLSQL
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
Jay Patel
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
Jay Patel
 
4. plsql
4. plsql4. plsql
4. plsql
Amrit Kaur
 

Similar to PLSQL.pptx (20)

PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
PL SQL.pptx in computer language in database
PL SQL.pptx in computer language in databasePL SQL.pptx in computer language in database
PL SQL.pptx in computer language in database
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
Plsql
PlsqlPlsql
Plsql
 
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
PLSQL
PLSQLPLSQL
PLSQL
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
4. plsql
4. plsql4. plsql
4. plsql
 

Recently uploaded

Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 

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