SlideShare a Scribd company logo
Database SystemsDatabase Systems
1
Server side DatabaseServer side Database
Programming using PL/SQLProgramming using PL/SQL
Version 1.1Version 1.1
2
What is PL/SQL?
 SQL
Structured language to access database
ANSI Standard
Declarative
○ Specifies what to access but not how to
- SELECT id, first_name, family_name FROM
authors
 PL/SQL
Developed by Oracle as a procedural extension to
SQL
Declare variables, IF..ELSE, WHILE & FOR loops,
functions, procedures and other features found in a
programming language
3
Server Side Programming
 PL/SQL executes inside DBMS
DBMS maintains Relational data
Also stores and executes Procedural code!
Advantages
Results from one query can be used as a
basis for the next query without having to
pull data from DBMS to client side for
processing!
4
Client Side Procedural logic
 DBMS maintains relational data
 Client side programs implement procedural
logic
Is there a problem?
 Performance impact due increased network
traffic
 Cumulative effect if many clients run at the same
time
 Code re-use may not be possible
 Many applications may incorporate processing that
are quite similar but sharing may not be easy!
5
PL/SQL - Basics
 Block structured
Basic program unit is a block
Contains variables, code and error handler
 A BLOCK is contained within BEGIN and END
statements with executable commands in
between
Must contain some commands, even if they do
nothing!
 PL/SQL programs must at least contain 1
block
 Blocks can be nested (block within another
block)
6
PL/SQL – Block Syntax
DECLARE
variable declarations
BEGIN
program code
EXCEPTION
exception handler code
END;
7
Optional
PL/SQL - EXCEPTIONs
 EXCEPTIONS
“unexpected errors” that occur during execution
occurs at run-time not at compile time!
 EXCEPTION HANDLER
Code that executes when EXCEPTION occurs
Makes the code more robust
 Oracle Server has many pre-defined errors
no_data_found, value_error, too_many_rows, others
8
PL/SQL - Anonymous Block
DECLARE
today date;
BEGIN
SELECT sysdate INTO today FROM dual;
DBMS_OUTPUT.PUT_LINE (‘Today -’ ||
today);
END;
• What exactly happens in this code?
• What is DUAL? (revision test !)
9
PL/SQL - Named Block
 Has a name and stored in Oracle Server
 Contains Header section
name,
key word - a function, procedure or trigger
type of value it returns in case of function
 At the time of creation, the code within
the named block is NOT executed but
compiled and stored in Oracle Server
10
PL/SQL - Data type - Character
DECLARE
family_name VARCHAR2 (20);
Age NUMBER(3);
 Assignment
family_name := ‘Anderson’;
Age := 21;
11
PL/SQL – %Type
 %TYPE
To map a variable directly to the same datatype as the
table column
DECLARE
author_id AUTHORS.ID%TYPE;
 PL/SQL variable ‘author_id’ is of same datatype
which is used to define column name ‘id’ of table AUTHORS.
 If column type changes PL/SQL Code would still work!
{Example: VARCHAR2(20) to VARCHAR(30)}
12
PL/SQL - Scope Rules
 Variables, procedures and functions can
be referenced by the code executing
inside the block in which they are
defined
 Understanding of scope of variables,
functions is especially important in the
context of nested blocks!
13
PL/SQL Scope Example
DECLARE
father_name VARCHAR2(20):='Patrick';
date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
child_name VARCHAR2(20):='Mike';
date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''s Name: '||
father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||
date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||
child_name);
END;
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||
date_of_birth);
END;
/ 14
PL/SQL Operators
 Expressions consist of PL/SQL operators
and operands
Arithmetic Operators
○ **, *, /, +, -
Comparison Operators
○ =, <>, !=, <, >, <=, >=, LIKE, BETWEEN, IN, IS
NULL
Logical Operators
○ AND, OR, NOT
 String Operator – Concatenation using ‘||’
15
PL/SQL – NULL
 NULL means “UNKNOWN” value
 Use IS NULL or IS NOT NULL to check
for NULL value
 NULL value comparison with ‘= NULL’
or ‘!= NULL’ may produce
unpredictable results!
 Use NVL function when appropriate
NVL (<expression>, <value if expression is NULL>)
16
PL/SQL – SELECT sample
DECLARE
name VARCHAR2(20);
surname VARCHAR2(20);
BEGIN
SELECT first_name, family_name
INTO name, surname
FROM AUTHORS
WHERE id = 1 ;
DBMS_OUTPUT.PUT_LINE
(‘Row selected is : ‘ || name || ‘-’ || surname);
END;
17
Performing DML Operations from PL/SQL
(INSERT, UPDATE, and DELETE)
 You can write INSERT, UPDATE, and DELETE
statements directly in PL/SQL programs, without any
special notation:
 %ROWCOUNT Attribute: How Many Rows Affected So
Far?
 Example
SET SERVEROUTPUT ON;
BEGIN
UPDATE employees SET salary = salary * 1.05
WHERE ...;
dbms_output.put_line('Updated ' || SQL%ROWCOUNT || '
salaries.');
END;
/
18
PL/SQL – Program Flow Control
 Conditional execution
IF-THEN, IF-THEN-ELSE, IF-THEN-ELSIF
CASE
 Repeated execution until some condition
 LOOP-END LOOP, FOR-LOOP-END
LOOP
WHILE-LOOP-END LOOP
EXIT WHEN
 Jump to code section
GOTO
19
PL/SQL – Conditional Execution
IF <condition>
THEN
statement1;
statement2;
…..
END IF;
 can be evaluated to TRUE, FALSE or
NULL – statement1, statement2 etc., are
executed only if it evaluates to TRUE
20
IF Example
IF sales > quota THEN
compute_bonus(empid);
UPDATE payroll SET pay = pay + bonus
WHERE empno = emp_id;
END IF;
21
PL/SQL – IF-THEN-ELSE
IF <condition>
THEN
statement1;
statement2;
…..
ELSE
statement3;
statement4;
…..
END IF;
22
PL/SQL IF-THEN-ELSIF
IF <condition1>
THEN
statement1;
…..
ELSIF <condition2>
statement3;
……
ELSE
…..
END IF;
23
Example
BEGIN ...
IF sales > 50000 THEN bonus := 1500;
ELSIF sales > 35000 THEN bonus :=
500;
ELSE bonus := 100; END IF;
INSERT INTO payroll VALUES
(emp_id,
bonus, ...);
END;
24
25
PL/SQL – Simple Loop
 The EXIT-WHEN statement lets you complete a
loop if further processing is impossible or
undesirable.
 When the EXIT statement is encountered, the
condition in the WHEN clause is evaluated.
 If the condition is true, the loop completes and
control passes to the next statement.E.G.
LOOP
statement1;
……
EXIT {WHEN ….} ;
END LOOP;
26
PL/SQL LOOP Example
 In the following example, the loop
completes when the value of total
exceeds 25,000:
LOOP ...
total := total + salary;
EXIT WHEN total > 25000; -- exit loop if
condition is true
END LOOP;
27
PL/SQL – FOR LOOP
FOR counter IN number1..number2
LOOP
statement1;
……
END LOOP;
FOR counter IN REVERSE
number1..number2
28
PL/SQL – FOR LOOP Example
FOR i IN 1..3 LOOP -- assign the values 1,2,3 to
i
sequence_of_statements -- executes three
times
END LOOP;
29
PL/SQL – WHILE LOOP
WHILE <condition>
LOOP
statement1;
…..
END LOOP;
30
Pre-defined Errors - examples
 NO_DATA_FOUND
A SELECT INTO statement returns no rows, or your
program references a deleted element in a nested
table or an uninitialized element in an index-by table.
 TOO_MANY_ROWS
A SELECT INTO statement returns more than one
row.
 ZERO_DIVIDE
A program attempts to divide a number by zero.
31
PL/SQL Error Handling example
DECLARE
comm_missing EXCEPTION; -- declare own exception
name VARCHAR2(20);
surname VARCHAR2(20);
BEGIN
SELECT first_name, family_name INTO name, surname
FROM AUTHORS;
IF commission IS NULL THEN
RAISE comm_missing; -- raise exception
END IF;
bonus := (salary * 0.10) + (commission * 0.15);
EXCEPTION
WHEN comm_missing THEN
DBMS_OUPUT.PUT_LINE(‘Sorry cannot calculate bonus as there is no
commission’);
WHEN TOO_MANY_ROWS THEN
DBMS_OUPUT.PUT_LINE(‘To much information to store ‘);
END;
/
32
Subprograms
 An ideal way of writing Writing Reusable
PL/SQL Code
 PL/SQL has two types of subprograms
called procedures and functions, which can
take parameters and be invoked (called).
 a subprogram is like a miniature program,
beginning with a header followed by an
optional declarative part, an executable
part, and an optional exception-handling
part:
33
Procedure Example
PROCEDURE award_bonus (emp_id NUMBER) IS
bonus REAL;
comm_missing EXCEPTION;
BEGIN -- executable part starts here
SELECT comm * 0.15 INTO bonus FROM emp WHERE empno =
emp_id;
IF bonus IS NULL THEN
RAISE comm_missing;
ELSE
UPDATE payroll SET pay = pay + bonus
WHERE empno = emp_id;
END IF;
EXCEPTION -- exception-handling part starts here
WHEN comm_missing THEN ... END award_bonus;
.
.
.
34
Function Example
CREATE OR REPLACE FUNCTION square(
original NUMBER) RETURN NUMBER AS
original_squared NUMBER;
BEGIN
original_squared := original * original;
RETURN original_squared;
END;
/
35
Packages
 PL/SQL lets you bundle logically related types,
variables, cursors, and subprograms into a
package
 The packages defines a simple, clear,
interface to a set of related procedures and
types.
 Packages usually have two parts: a
specification and a body.
 The specification defines the application
programming interface; it declares the types,
constants, variables, exceptions, cursors, and
subprograms.
 The body fills in the SQL queries for cursors
and the code for subprograms.
36
Packages Example
37
Database Triggers
 A database trigger is a stored subprogram
associated with a database table, view, or event.
 The trigger can be called once, when some event
occurs, or many times, once for each row affected
by an INSERT, UPDATE, or DELETE statement.
 The trigger can be called after the event, to record
it or take some followup action. Or, the trigger can
be called before the event to prevent erroneous
operations or fix new data so that it conforms to
business rules.
38
Triggers Example
CREATE TRIGGER audit_sal
AFTER UPDATE OF sal ON emp
FOR EACH ROW
BEGIN
INSERT INTO emp_audit VALUES ...
END;
39
Cursors
 A cursor is a pointer to the private
memory area allocated by the Oracle
server.
 There are two types of cursors:
Implicit cursors: Created and managed
internally by the Oracle server to process
SQL statements
Explicit cursors: Explicitly declared by the
programmer
40
Processing Explicit Cursors
 The following three commands are used to
process an explicit cursor:
○ OPEN
○ FETCH
○ CLOSE
 Every explicit cursor has the following four
attributes:
○ cursor_name%FOUND
○ cursor_name%ISOPEN
○ cursor_name%NOTFOUND
○ cursor_name%ROWCOUNT
41
Cursor Example
42

More Related Content

PPT
PPTX
PL/SQL Fundamentals I
PPT
Oracle PLSQL Step By Step Guide
PPT
PL/SQL Introduction and Concepts
PPTX
PLSQL Tutorial
ODP
Open Gurukul Language PL/SQL
PPT
Oracle Baisc Tutorial
PPTX
Introduction to PL/SQL
PL/SQL Fundamentals I
Oracle PLSQL Step By Step Guide
PL/SQL Introduction and Concepts
PLSQL Tutorial
Open Gurukul Language PL/SQL
Oracle Baisc Tutorial
Introduction to PL/SQL

What's hot (17)

PPT
Pl sql guide
PPT
DOC
3963066 pl-sql-notes-only
PPTX
ORACLE PL SQL FOR BEGINNERS
PPT
10g plsql slide
PDF
PPT
Basic cursors in oracle
PPTX
PL/SQL - CURSORS
PPT
1 - Introduction to PL/SQL
PPT
Chapter8 pl sql
PPTX
4. plsql
PPTX
Procedure and Functions in pl/sql
PPTX
pl/sql online Training|sql online Training | iTeknowledge
PPTX
Cursors, triggers, procedures
PPT
11 Understanding and Influencing the PL/SQL Compilar
PPT
ORACLE PL SQL
PPT
PLSQL Cursors
Pl sql guide
3963066 pl-sql-notes-only
ORACLE PL SQL FOR BEGINNERS
10g plsql slide
Basic cursors in oracle
PL/SQL - CURSORS
1 - Introduction to PL/SQL
Chapter8 pl sql
4. plsql
Procedure and Functions in pl/sql
pl/sql online Training|sql online Training | iTeknowledge
Cursors, triggers, procedures
11 Understanding and Influencing the PL/SQL Compilar
ORACLE PL SQL
PLSQL Cursors
Ad

Viewers also liked (20)

PDF
OpenStack-Design-Summit-HA-Pairs-Are-Not-The-Only-Answer copy.pdf
PPT
L14 l15 Object Oriented DBMS
PPTX
DBMS Lecture 8 - Normalization
PPTX
NORMALIZATION - BIS 1204: Data and Information Management I
PPTX
Normalization in Database
PPTX
Database indexing techniques
PPT
Data independence
PPSX
DISE - Database Concepts
PPT
Lecture 04 normalization
PPTX
Data Dictionary
PPT
Databases: Locking Methods
PPTX
physical and logical data independence
PPS
Architecture of-dbms-and-data-independence
PPT
Indexing and hashing
PPT
Data dictionary
PPTX
Systems Analyst and Design - Data Dictionary
PDF
SAP ABAP data dictionary
PDF
CBSE XII Database Concepts And MySQL Presentation
PPTX
Types of databases
PPT
DBMS - Normalization
OpenStack-Design-Summit-HA-Pairs-Are-Not-The-Only-Answer copy.pdf
L14 l15 Object Oriented DBMS
DBMS Lecture 8 - Normalization
NORMALIZATION - BIS 1204: Data and Information Management I
Normalization in Database
Database indexing techniques
Data independence
DISE - Database Concepts
Lecture 04 normalization
Data Dictionary
Databases: Locking Methods
physical and logical data independence
Architecture of-dbms-and-data-independence
Indexing and hashing
Data dictionary
Systems Analyst and Design - Data Dictionary
SAP ABAP data dictionary
CBSE XII Database Concepts And MySQL Presentation
Types of databases
DBMS - Normalization
Ad

Similar to L9 l10 server side programming (20)

PPTX
PLSQLmy Updated (1).pptx
PPT
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
PPTX
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
PPTX
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
PDF
rdbms.pdf plsql database system notes for students to study
DOC
Oracle etl openworld
PPTX
3130703_DBMS_GTU_Study_Material_Presentations_Unit-10_17102019083650AM.pptx
PPT
PDF
PL-SQL.pdf
PPTX
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PPTX
Unit 3(rdbms)
PPTX
Unit 3(rdbms)
PDF
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PDF
PL/SQL Complete Tutorial. All Topics Covered
PPS
Procedures/functions of rdbms
PPTX
PL SQL.pptx in computer language in database
PPT
plsql.ppt
PPTX
PLSQL.pptx
PPTX
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
PPTX
PL_SQL_1.pptx fvbxcfbhxdfgh .
PLSQLmy Updated (1).pptx
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
rdbms.pdf plsql database system notes for students to study
Oracle etl openworld
3130703_DBMS_GTU_Study_Material_Presentations_Unit-10_17102019083650AM.pptx
PL-SQL.pdf
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
Unit 3(rdbms)
Unit 3(rdbms)
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PL/SQL Complete Tutorial. All Topics Covered
Procedures/functions of rdbms
PL SQL.pptx in computer language in database
plsql.ppt
PLSQL.pptx
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
PL_SQL_1.pptx fvbxcfbhxdfgh .

More from Rushdi Shams (20)

PDF
Research Methodology and Tips on Better Research
PPTX
Common evaluation measures in NLP and IR
PPTX
Machine learning with nlp 101
PPTX
Semi-supervised classification for natural language processing
PPTX
Natural Language Processing: Parsing
PPT
Types of machine translation
PDF
L1 l2 l3 introduction to machine translation
PPT
Syntax and semantics
PPTX
Propositional logic
PPTX
Probabilistic logic
PPT
L15 fuzzy logic
PPT
Knowledge structure
PPT
Knowledge representation
PPT
First order logic
PPTX
Belief function
PPT
L5 understanding hacking
PPT
L4 vpn
PPT
L3 defense
PPT
L2 Intrusion Detection System (IDS)
PPT
L1 phishing
Research Methodology and Tips on Better Research
Common evaluation measures in NLP and IR
Machine learning with nlp 101
Semi-supervised classification for natural language processing
Natural Language Processing: Parsing
Types of machine translation
L1 l2 l3 introduction to machine translation
Syntax and semantics
Propositional logic
Probabilistic logic
L15 fuzzy logic
Knowledge structure
Knowledge representation
First order logic
Belief function
L5 understanding hacking
L4 vpn
L3 defense
L2 Intrusion Detection System (IDS)
L1 phishing

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Approach and Philosophy of On baking technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
sap open course for s4hana steps from ECC to s4
PDF
cuic standard and advanced reporting.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Encapsulation theory and applications.pdf
Electronic commerce courselecture one. Pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Empathic Computing: Creating Shared Understanding
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
Encapsulation_ Review paper, used for researhc scholars
Approach and Philosophy of On baking technology
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Machine learning based COVID-19 study performance prediction
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
sap open course for s4hana steps from ECC to s4
cuic standard and advanced reporting.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Unlocking AI with Model Context Protocol (MCP)
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Digital-Transformation-Roadmap-for-Companies.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation theory and applications.pdf

L9 l10 server side programming

  • 1. Database SystemsDatabase Systems 1 Server side DatabaseServer side Database Programming using PL/SQLProgramming using PL/SQL Version 1.1Version 1.1
  • 2. 2
  • 3. What is PL/SQL?  SQL Structured language to access database ANSI Standard Declarative ○ Specifies what to access but not how to - SELECT id, first_name, family_name FROM authors  PL/SQL Developed by Oracle as a procedural extension to SQL Declare variables, IF..ELSE, WHILE & FOR loops, functions, procedures and other features found in a programming language 3
  • 4. Server Side Programming  PL/SQL executes inside DBMS DBMS maintains Relational data Also stores and executes Procedural code! Advantages Results from one query can be used as a basis for the next query without having to pull data from DBMS to client side for processing! 4
  • 5. Client Side Procedural logic  DBMS maintains relational data  Client side programs implement procedural logic Is there a problem?  Performance impact due increased network traffic  Cumulative effect if many clients run at the same time  Code re-use may not be possible  Many applications may incorporate processing that are quite similar but sharing may not be easy! 5
  • 6. PL/SQL - Basics  Block structured Basic program unit is a block Contains variables, code and error handler  A BLOCK is contained within BEGIN and END statements with executable commands in between Must contain some commands, even if they do nothing!  PL/SQL programs must at least contain 1 block  Blocks can be nested (block within another block) 6
  • 7. PL/SQL – Block Syntax DECLARE variable declarations BEGIN program code EXCEPTION exception handler code END; 7 Optional
  • 8. PL/SQL - EXCEPTIONs  EXCEPTIONS “unexpected errors” that occur during execution occurs at run-time not at compile time!  EXCEPTION HANDLER Code that executes when EXCEPTION occurs Makes the code more robust  Oracle Server has many pre-defined errors no_data_found, value_error, too_many_rows, others 8
  • 9. PL/SQL - Anonymous Block DECLARE today date; BEGIN SELECT sysdate INTO today FROM dual; DBMS_OUTPUT.PUT_LINE (‘Today -’ || today); END; • What exactly happens in this code? • What is DUAL? (revision test !) 9
  • 10. PL/SQL - Named Block  Has a name and stored in Oracle Server  Contains Header section name, key word - a function, procedure or trigger type of value it returns in case of function  At the time of creation, the code within the named block is NOT executed but compiled and stored in Oracle Server 10
  • 11. PL/SQL - Data type - Character DECLARE family_name VARCHAR2 (20); Age NUMBER(3);  Assignment family_name := ‘Anderson’; Age := 21; 11
  • 12. PL/SQL – %Type  %TYPE To map a variable directly to the same datatype as the table column DECLARE author_id AUTHORS.ID%TYPE;  PL/SQL variable ‘author_id’ is of same datatype which is used to define column name ‘id’ of table AUTHORS.  If column type changes PL/SQL Code would still work! {Example: VARCHAR2(20) to VARCHAR(30)} 12
  • 13. PL/SQL - Scope Rules  Variables, procedures and functions can be referenced by the code executing inside the block in which they are defined  Understanding of scope of variables, functions is especially important in the context of nested blocks! 13
  • 14. PL/SQL Scope Example DECLARE father_name VARCHAR2(20):='Patrick'; date_of_birth DATE:='20-Apr-1972'; BEGIN DECLARE child_name VARCHAR2(20):='Mike'; date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '|| father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '|| date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '|| child_name); END; DBMS_OUTPUT.PUT_LINE('Date of Birth: '|| date_of_birth); END; / 14
  • 15. PL/SQL Operators  Expressions consist of PL/SQL operators and operands Arithmetic Operators ○ **, *, /, +, - Comparison Operators ○ =, <>, !=, <, >, <=, >=, LIKE, BETWEEN, IN, IS NULL Logical Operators ○ AND, OR, NOT  String Operator – Concatenation using ‘||’ 15
  • 16. PL/SQL – NULL  NULL means “UNKNOWN” value  Use IS NULL or IS NOT NULL to check for NULL value  NULL value comparison with ‘= NULL’ or ‘!= NULL’ may produce unpredictable results!  Use NVL function when appropriate NVL (<expression>, <value if expression is NULL>) 16
  • 17. PL/SQL – SELECT sample DECLARE name VARCHAR2(20); surname VARCHAR2(20); BEGIN SELECT first_name, family_name INTO name, surname FROM AUTHORS WHERE id = 1 ; DBMS_OUTPUT.PUT_LINE (‘Row selected is : ‘ || name || ‘-’ || surname); END; 17
  • 18. Performing DML Operations from PL/SQL (INSERT, UPDATE, and DELETE)  You can write INSERT, UPDATE, and DELETE statements directly in PL/SQL programs, without any special notation:  %ROWCOUNT Attribute: How Many Rows Affected So Far?  Example SET SERVEROUTPUT ON; BEGIN UPDATE employees SET salary = salary * 1.05 WHERE ...; dbms_output.put_line('Updated ' || SQL%ROWCOUNT || ' salaries.'); END; / 18
  • 19. PL/SQL – Program Flow Control  Conditional execution IF-THEN, IF-THEN-ELSE, IF-THEN-ELSIF CASE  Repeated execution until some condition  LOOP-END LOOP, FOR-LOOP-END LOOP WHILE-LOOP-END LOOP EXIT WHEN  Jump to code section GOTO 19
  • 20. PL/SQL – Conditional Execution IF <condition> THEN statement1; statement2; ….. END IF;  can be evaluated to TRUE, FALSE or NULL – statement1, statement2 etc., are executed only if it evaluates to TRUE 20
  • 21. IF Example IF sales > quota THEN compute_bonus(empid); UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id; END IF; 21
  • 22. PL/SQL – IF-THEN-ELSE IF <condition> THEN statement1; statement2; ….. ELSE statement3; statement4; ….. END IF; 22
  • 23. PL/SQL IF-THEN-ELSIF IF <condition1> THEN statement1; ….. ELSIF <condition2> statement3; …… ELSE ….. END IF; 23
  • 24. Example BEGIN ... IF sales > 50000 THEN bonus := 1500; ELSIF sales > 35000 THEN bonus := 500; ELSE bonus := 100; END IF; INSERT INTO payroll VALUES (emp_id, bonus, ...); END; 24
  • 25. 25
  • 26. PL/SQL – Simple Loop  The EXIT-WHEN statement lets you complete a loop if further processing is impossible or undesirable.  When the EXIT statement is encountered, the condition in the WHEN clause is evaluated.  If the condition is true, the loop completes and control passes to the next statement.E.G. LOOP statement1; …… EXIT {WHEN ….} ; END LOOP; 26
  • 27. PL/SQL LOOP Example  In the following example, the loop completes when the value of total exceeds 25,000: LOOP ... total := total + salary; EXIT WHEN total > 25000; -- exit loop if condition is true END LOOP; 27
  • 28. PL/SQL – FOR LOOP FOR counter IN number1..number2 LOOP statement1; …… END LOOP; FOR counter IN REVERSE number1..number2 28
  • 29. PL/SQL – FOR LOOP Example FOR i IN 1..3 LOOP -- assign the values 1,2,3 to i sequence_of_statements -- executes three times END LOOP; 29
  • 30. PL/SQL – WHILE LOOP WHILE <condition> LOOP statement1; ….. END LOOP; 30
  • 31. Pre-defined Errors - examples  NO_DATA_FOUND A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table.  TOO_MANY_ROWS A SELECT INTO statement returns more than one row.  ZERO_DIVIDE A program attempts to divide a number by zero. 31
  • 32. PL/SQL Error Handling example DECLARE comm_missing EXCEPTION; -- declare own exception name VARCHAR2(20); surname VARCHAR2(20); BEGIN SELECT first_name, family_name INTO name, surname FROM AUTHORS; IF commission IS NULL THEN RAISE comm_missing; -- raise exception END IF; bonus := (salary * 0.10) + (commission * 0.15); EXCEPTION WHEN comm_missing THEN DBMS_OUPUT.PUT_LINE(‘Sorry cannot calculate bonus as there is no commission’); WHEN TOO_MANY_ROWS THEN DBMS_OUPUT.PUT_LINE(‘To much information to store ‘); END; / 32
  • 33. Subprograms  An ideal way of writing Writing Reusable PL/SQL Code  PL/SQL has two types of subprograms called procedures and functions, which can take parameters and be invoked (called).  a subprogram is like a miniature program, beginning with a header followed by an optional declarative part, an executable part, and an optional exception-handling part: 33
  • 34. Procedure Example PROCEDURE award_bonus (emp_id NUMBER) IS bonus REAL; comm_missing EXCEPTION; BEGIN -- executable part starts here SELECT comm * 0.15 INTO bonus FROM emp WHERE empno = emp_id; IF bonus IS NULL THEN RAISE comm_missing; ELSE UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id; END IF; EXCEPTION -- exception-handling part starts here WHEN comm_missing THEN ... END award_bonus; . . . 34
  • 35. Function Example CREATE OR REPLACE FUNCTION square( original NUMBER) RETURN NUMBER AS original_squared NUMBER; BEGIN original_squared := original * original; RETURN original_squared; END; / 35
  • 36. Packages  PL/SQL lets you bundle logically related types, variables, cursors, and subprograms into a package  The packages defines a simple, clear, interface to a set of related procedures and types.  Packages usually have two parts: a specification and a body.  The specification defines the application programming interface; it declares the types, constants, variables, exceptions, cursors, and subprograms.  The body fills in the SQL queries for cursors and the code for subprograms. 36
  • 38. Database Triggers  A database trigger is a stored subprogram associated with a database table, view, or event.  The trigger can be called once, when some event occurs, or many times, once for each row affected by an INSERT, UPDATE, or DELETE statement.  The trigger can be called after the event, to record it or take some followup action. Or, the trigger can be called before the event to prevent erroneous operations or fix new data so that it conforms to business rules. 38
  • 39. Triggers Example CREATE TRIGGER audit_sal AFTER UPDATE OF sal ON emp FOR EACH ROW BEGIN INSERT INTO emp_audit VALUES ... END; 39
  • 40. Cursors  A cursor is a pointer to the private memory area allocated by the Oracle server.  There are two types of cursors: Implicit cursors: Created and managed internally by the Oracle server to process SQL statements Explicit cursors: Explicitly declared by the programmer 40
  • 41. Processing Explicit Cursors  The following three commands are used to process an explicit cursor: ○ OPEN ○ FETCH ○ CLOSE  Every explicit cursor has the following four attributes: ○ cursor_name%FOUND ○ cursor_name%ISOPEN ○ cursor_name%NOTFOUND ○ cursor_name%ROWCOUNT 41

Editor's Notes

  • #8: BEGIN NULL; END; This is a valid PL/SQL block that does nothing! Try without ‘NULL;’ statement, see what happens!
  • #10: Not stored in Oracle Server, Not named Executed in the same session and can not be called from another session To execute again, re-type the code or save it to a OS file and run it
  • #15: The output of the block shown in the slide is as follows: Father_name Patrick Date of Birth 12-Dec-2002 Childs Name Mike Date of birth 20 Apr 1972 Examine the date of birth that is printed for father and child. The scope of a variable is the portion of the program in which the variable is declared and is accessible. The visibility of a variable is the portion of the program where the variable can be accessed without using a qualifier. Scope • The variables father_name and date_of_birth are declared in the outer block. These variables will have the scope of the block in which they are declared and accessible. Therefore, the scope of these variables are limited to the outer block. Scope (continued) • The variables child_name and date_of_birth are declared in the inner block or the nested block. These variables are accessible only within the nested block and are not accessible in the outer block. When a variable is out of scope, PL/SQL frees the memory used to store the variable and therefore these variables cannot be referenced. Visibility • The date_of_birth variable declared in the outer block has the scope even in the inner block. However, this variable is not visible in the inner block because the inner block has a local variable with the same name. 1. Observe the code in the executable section of the PL/SQL block. You can print the father’s name, the child’s name, and the date of birth. Only the child’s date of birth can be printed here because the father’s date of birth is not visible here. 2. Father’s date of birth is visible here and therefore can be printed. You cannot have variables with same name in a block. However, you can declare variables with same name in two different blocks (nested blocks). The two items represented by the identifiers are distinct, and any change in one does not affect the other.
  • #19: You can write INSERT, UPDATE, and DELETE statements directly in PL/SQL programs, without any special notation:
  • #20: Control structures are the most important PL/SQL extension to SQL. Not only does PL/SQL let you manipulate Oracle data, it lets you process the data using conditional, iterative, and sequential flow-of-control statements such as IF-THEN-ELSE, CASE, FOR-LOOP, WHILE-LOOP, EXIT-WHEN, and GOTO.
  • #21: The sequence of statements is executed only if the condition is true. If the condition is false or null, the IF statement does nothing. In either case, control passes to the next statement. An example follows:
  • #22: Consider the program below, which processes a bank transaction. Before allowing you to withdraw $500 from account 3, it makes sure the account has sufficient funds to cover the withdrawal. If the funds are available, the program debits the account. Otherwise, the program inserts a record into an audit table.
  • #34: Writing Reusable PL/SQL Code PL/SQL lets you break an application down into manageable, well-defined modules. PL/SQL meets this need with program units , which include blocks, subprograms, and packages. You can reuse program units by loading them into the database as triggers, stored procedures, and stored functions.
  • #35: When called, this procedure accepts an employee number. It uses the number to select the employee&apos;s commission from a database table and, at the same time, compute a 15% bonus. Then, it checks the bonus amount. If the bonus is null, an exception is raised; otherwise, the employee&apos;s payroll record is updated.
  • #37: Packages are database objects that are a step above regular stored procedures
  • #38: The following example packages two employment procedures: Applications that call these procedures only need to know the names and parameters from the package spec. You can change the implementation details inside the package body without affecting the calling applications. Packages are stored in the database, where they can be shared by many applications. Calling a packaged subprogram for the first time loads the whole package and caches it in memory, saving on disk I/O for subsequent calls. Thus, packages enhance reuse and improve performance in a multi-user, multi-application environment.
  • #42: Alternatively, you can also use a cursor FOR loops. before the first fetch from an OPEN cursor. Returns FALSE if the last fetch failed to return a row. • cursor_name%ISOPEN: Returns TRUE if the cursor is open, otherwise returns FALSE. • cursor_name%NOTFOUND: Returns FALSE if the last fetch returned a row. Returns NULL before the first fetch from an OPEN cursor. Returns TRUE if the last fetch failed to return a row. • cursor_name%ROWCOUNT: Returns zero before the first fetch. After every fetch returns the number of rows fetched so far.