3. About this course
• Introduction to the PL/SQL database
programming language
• Course prerequisites
– SQL Fundamentals
• Next course
– PL/SQL Fundamentals II – Develop Program Units
– Advanced PL/SQL Programming & Tuning
• Certification
– 1Z0-144 - Oracle Database 11g: Program with
PL/SQL (OCA – OCP)
6. Setup environment
• As SYS, create a new user
– CreateUser.sql
• Connect as that user
• Create the COMPANY tables (DDL)
– CompanyDefine.sql
• Insert the COMPANY data (DML)
– CompanyInsert.sql
7. 1. Using the database interface
• Tools to communicate with the Oracle Database
– SQL Developer, SQL*Plus, Application Express, ...
• Database authentication elements
– Database connection
– User authentication
• Bind variables
– Variable values – e.g. &employee_id
– Applies to both SQL and PL/SQL
8. 2. Language features
• Procedural Language extensions to the
Structured Query Language
– Highly structured, readable and accessible language
– Standard and portable language for Oracle
development
– High-performance, highly integrated database
language (cfr. SGA)
9. A PL/SQL program block
declare
-- internal program objects (e.g. variables)
begin
-- program logic
exception
-- exception handling
end;
10. Comments
• Single-line comment
-- I’m a single-line comment
• Multi-line comment
/*
I’m a multi-line comment.
I could write a whole story here
...
*/
11. Additional syntax rules
• One statement per line – isn’t mandatory
• End all execution statements with a semi-colon
begin
null;
end;
12. What about SQL DDL?
• DML operations work just fine in PL/SQL
• Explicit DDL is NOT allowed
– You can bypass this restriction by using dynamic SQL
execute immediate ‘create table EMP (...)’;
13. Generating output
• Write to the output buffer using dbms_output()
• set serveroutput on
• GUI option in SQL Developer
17. Complex types – Table types
type ltt_emp_ssn
is table of employee.ssn%type
index by pls_integer;
l_emp_ssn_list ltt_emp_ssn;
l_emp_ssn_list(1) := ‘123456789’;
18. Complex types – Record types
type lrt_emp
is record(
fname employee.fname%type,
lname employee.lname%type
);
l_emp_list lrt_emp;
l_emp_list.fname := ‘John’;
l_emp_list.lname := ‘Doe’;
19. Complex types – Nesting records
type lrt_bonus_compensation
is record(
cash_payment number(6),
company_car boolean
);
type lrt_employee
is record(
ssn
employee.ssn%type,
bonus_payment lrt_bonus_compensation
);
21. 4. The BEGIN clause
• Includes the program execution logic
–
–
–
–
All sorts of data manipulation
Database access using SQL statements
Standard logic control and branching instructions
...
23. Comparison operators
Operator Description
=
equality
!= <>
inequality
is null
checks for a null value
is not null checks for a not null value
like
pattern matching (% and _)
in
equality with multiple values
between
checks if a value lies in a range
24. Using SQL functions
• Most of the functions in SQL are available in
PL/SQL
– upper, round, max, rownum, sysdate, nvl, ...
• Regular expressions
– Perform searches within character strings
– regexp_like()
25. Handling string literals
l_text := ‘I don’t like single quotes’;
l_text := ‘I don’’t like single quotes’;
l_text := q‘!I don’t like single quotes!’;
26. DML within PL/SQL
• CRUD statements
– select, insert, update, delete
• Transaction control
– commit, rollback, savepoint
27. Using SELECT
• Returning multiple rows
– Cursors (cfr. Chapter 6)
• Returning a single row
– SELECT ... INTO
– NO_DATA_FOUND or TOO_MANY_ROWS exceptions
select *
into l_emp
from employee
where ssn = ‘123456789’;
28. Using sequences
l_id := employee_seq.nextval;
• Starting from Oracle Database 11g
• Use currval after nextval
29. Program labels & GOTO
• Labels are location markers
– Enclosed by angle brackets
– <<labelName>>
• Improves documentation and readability
• A GOTO statement jumps to a label location
– GOTO labelName;
• Using GOTO is a bad practice
30. Loops
loop ... end loop;
loop ... exit [when condition]; end loop;
while condition loop ... end loop;
for index in [reverse] x .. y loop
...
end loop;
31. IF – THEN – ELSE
if condition then
...
elsif condition then
...
else
...
end if;
35. 5. The EXCEPTION clause
• Catch errors during execution
• Isolate main line programming logic from
exception logic
• Two different types of exceptions
– System exceptions raised by Oracle
– Programmer-defined exceptions
36. Exception processing
• Anything that can be done in the BEGIN clause
can be done in the EXCEPTION clause
• Impossible to jump back to the BEGIN clause
• An untrapped exception aborts the program with
an error condition
• An error in the EXCEPTION clause also aborts the
program
37. Trapping exceptions
exception
when zero_divide then
-- handler for one exception
when no_data_found or too_many_rows then
-- handler for multiple exceptions
when others then
-- global exception handler
-- must be the last exception handler
end;
39. PRAGMA EXCEPTION_INIT
• A limited number of errors have system-defined
exception names
– Unnamed exceptions can only be handled by the
WHEN OTHERS clause
• PRAGMA is a compile-time command
• EXCEPTION_INIT associates a name with an
internal error code
40. An example
declare
-- declare an exception type
not_null_constraint exception;
-- associate the exception with an error code
pragma exception_init(not_null_constraint, -1407);
begin
...
exception
when not_null_constraint then
...
41. SQLCODE & SQLERRM
• We can’t isolate every single exception that may
arise within a PL/SQL program
• Use the WHEN OTHERS clause in combination
with SQLCODE and SQLERRM
• System functions used to detect the propagated
error code and error message
• DBMS_UTILITY.FORMAT_ERROR_STACK is even
better
42. Implicit cursor attributes
• An implicit cursor is created each time a SQL
DML statement is executed
• We can reference the SQL% attributes from the
most recently executed SQL statement
–
–
–
–
SQL%FOUND
SQL%NOTFOUND
SQL%ROWCOUNT
SQL%ISOPEN
43. User-defined events
• Enforce business rules within your program
• Violating these rules can be considered as an
exception
too_young exception;
if age < 18 then
raise too_young;
end if;
when too_young then
...
45. 6. Explicit cursors
• An explicit cursor is a named pointer to the result
set of a SQL statement
• Used for sequential processing
• Avoids common exceptions such as
TOO_MANY_ROWS or NO_DATA_FOUND
• Explicit cursors have the same attributes as
implicit cursors
– cursor_name%attribute
46. An example
declare
cursor lcu_emp is
select *
from employee;
l_emp_rec employee%rowtype;
begin
open lcu_emp;
loop
fetch lcu_emp into l_emp_rec;
exit when lcu_emp%notfound;
dbms_output.put_line(l_emp_rec.lname);
end loop;
end;
47. The CONTINUE statement
• Terminate the current iteration of a loop
• Conditional WHEN clause
• Similar to the EXIT statement
continue when l_emp_rec.ssn is null;
48. FOR UPDATE OF clause
• The rows that are part of the cursor are locked
after the OPEN statement is issued
• Close the cursor and terminate the transaction to
unlock the rows
cursor lcu_emp is
select *
from employee
for update of salary, lname;
49. WHERE CURRENT OF clause
• Can only be used in combination with the FOR
UPDATE OF clause
• Uniquely identifies the most recently fetched row
from a cursor
update employee
set salary = salary – l_pay_cut
where current of lcu_emp;
50. Cursor parameters
cursor lcu_emp (p_department number) is
select *
from employee
where dno = p_department;
for update of salary, lname;
open lcu_emp (l_department);
51. FOR ... LOOP cursors
begin
for emp_rec in (select *
from employee) loop
dbms_output.put_line(emp_rec.ssn);
end loop;
end;
53. 7. Nested blocks
• A complete PL/SQL program block enclosed
within the BEGIN or EXCEPTION clause of another
program
• Inner block versus outer block
• Mainly used to prevent the outer block from
branching to the EXCEPTION clause
• Global versus local objects and exceptions
• RAISE statement