Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
PL/SQL Fundamentals I
Kontich, Belgium
14/10 – 15/10
Agenda
•
•
•
•
•
•
•
•
•

Introduction and setup
Using the database interface
Language features
The DECLARE clause
The BEG...
About this course
• Introduction to the PL/SQL database
programming language
• Course prerequisites
– SQL Fundamentals

• ...
The COMPANY database
• Sample data model we’ll use during the course
Setup software
• Oracle Database Express Edition (XE)
• Oracle SQL Developer
Setup environment
• As SYS, create a new user
– CreateUser.sql

• Connect as that user
• Create the COMPANY tables (DDL)
–...
1. Using the database interface
• Tools to communicate with the Oracle Database
– SQL Developer, SQL*Plus, Application Exp...
2. Language features
• Procedural Language extensions to the
Structured Query Language
– Highly structured, readable and a...
A PL/SQL program block
declare
-- internal program objects (e.g. variables)
begin
-- program logic
exception
-- exception ...
Comments
• Single-line comment
-- I’m a single-line comment

• Multi-line comment
/*

I’m a multi-line comment.
I could wr...
Additional syntax rules
• One statement per line – isn’t mandatory
• End all execution statements with a semi-colon
begin
...
What about SQL DDL?
• DML operations work just fine in PL/SQL
• Explicit DDL is NOT allowed
– You can bypass this restrict...
Generating output
• Write to the output buffer using dbms_output()
• set serveroutput on
• GUI option in SQL Developer
Exercises
3. The DECLARE clause
• Define or declare internal program objects
Name [constant] datatype [not null] [ := | default valu...
Complex types
• %TYPE
– l_first_name employee.fname%type;

• Maintaining internal consistency
– l_last_name l_first_name%t...
Complex types – Table types
type ltt_emp_ssn
is table of employee.ssn%type
index by pls_integer;
l_emp_ssn_list ltt_emp_ss...
Complex types – Record types
type lrt_emp
is record(
fname employee.fname%type,
lname employee.lname%type
);
l_emp_list lr...
Complex types – Nesting records
type lrt_bonus_compensation
is record(
cash_payment number(6),
company_car boolean
);

typ...
Exercises
4. The BEGIN clause
• Includes the program execution logic
–
–
–
–

All sorts of data manipulation
Database access using S...
Variable assignment
• Strings
– l_fname := ‘John’;
– l_name := l_fname || ' ' || l_lname;

• Numbers
– l_salary := 1000;
–...
Comparison operators
Operator Description
=

equality

!= <>

inequality

is null

checks for a null value

is not null ch...
Using SQL functions
• Most of the functions in SQL are available in
PL/SQL
– upper, round, max, rownum, sysdate, nvl, ...
...
Handling string literals
l_text := ‘I don’t like single quotes’; 
l_text := ‘I don’’t like single quotes’; 
l_text := q‘...
DML within PL/SQL
• CRUD statements
– select, insert, update, delete

• Transaction control
– commit, rollback, savepoint
Using SELECT
• Returning multiple rows
– Cursors (cfr. Chapter 6)

• Returning a single row
– SELECT ... INTO
– NO_DATA_FO...
Using sequences
l_id := employee_seq.nextval;
• Starting from Oracle Database 11g
• Use currval after nextval
Program labels & GOTO
• Labels are location markers
– Enclosed by angle brackets
– <<labelName>>

• Improves documentation...
Loops
loop ... end loop;
loop ... exit [when condition]; end loop;
while condition loop ... end loop;

for index in [rever...
IF – THEN – ELSE
if condition then
...
elsif condition then
...
else
...
end if;
Simple case
case expression
when result1 then
…
when result2 then
…
when result3 then
…
else
…
end case;
Searched case
case
when expression1 then
…
when expression2 then
…
when expression3 then
…
else
…
end case;
Exercises
5. The EXCEPTION clause
• Catch errors during execution
• Isolate main line programming logic from
exception logic
• Two d...
Exception processing
• Anything that can be done in the BEGIN clause
can be done in the EXCEPTION clause
• Impossible to j...
Trapping exceptions
exception
when zero_divide then
-- handler for one exception
when no_data_found or too_many_rows then
...
System-defined exceptions
• Common system-defined exception names
– NO_DATA_FOUND
– TOO_MANY_ROWS
– CASE_NOT_FOUND
– ZERO_...
PRAGMA EXCEPTION_INIT
• A limited number of errors have system-defined
exception names
– Unnamed exceptions can only be ha...
An example
declare
-- declare an exception type
not_null_constraint exception;
-- associate the exception with an error co...
SQLCODE & SQLERRM
• We can’t isolate every single exception that may
arise within a PL/SQL program
• Use the WHEN OTHERS c...
Implicit cursor attributes
• An implicit cursor is created each time a SQL
DML statement is executed
• We can reference th...
User-defined events
• Enforce business rules within your program
• Violating these rules can be considered as an
exception...
Exercises
6. Explicit cursors
• An explicit cursor is a named pointer to the result
set of a SQL statement
• Used for sequential pro...
An example
declare
cursor lcu_emp is
select *
from employee;
l_emp_rec employee%rowtype;
begin
open lcu_emp;
loop
fetch lc...
The CONTINUE statement
• Terminate the current iteration of a loop
• Conditional WHEN clause
• Similar to the EXIT stateme...
FOR UPDATE OF clause
• The rows that are part of the cursor are locked
after the OPEN statement is issued
• Close the curs...
WHERE CURRENT OF clause
• Can only be used in combination with the FOR
UPDATE OF clause
• Uniquely identifies the most rec...
Cursor parameters
cursor lcu_emp (p_department number) is
select *
from employee
where dno = p_department;
for update of s...
FOR ... LOOP cursors
begin
for emp_rec in (select *
from employee) loop
dbms_output.put_line(emp_rec.ssn);
end loop;
end;
Exercises
7. Nested blocks
• A complete PL/SQL program block enclosed
within the BEGIN or EXCEPTION clause of another
program
• Inne...
Exercises
8. Declared subprograms
• Enclose commonly used logic within callable
subprograms
• Procedure versus function
• Parameteri...
Exercises
Sie haben dieses Dokument abgeschlossen.
Nächste SlideShare
1 - Introduction to PL/SQL
Weiter
Nächste SlideShare
1 - Introduction to PL/SQL
Weiter

Teilen

PL/SQL Fundamentals I

The powerpoint presentation I used for a PL/SQL fundamentals course (14/10/2013 - Kontich, Belgium).

Ähnliche Bücher

Kostenlos mit einer 30-tägigen Testversion von Scribd

Alle anzeigen

Ähnliche Hörbücher

Kostenlos mit einer 30-tägigen Testversion von Scribd

Alle anzeigen

PL/SQL Fundamentals I

  1. 1. PL/SQL Fundamentals I Kontich, Belgium 14/10 – 15/10
  2. 2. Agenda • • • • • • • • • Introduction and setup Using the database interface Language features The DECLARE clause The BEGIN clause The EXCEPTION clause Explicit cursors Nested blocks Declared subprograms
  3. 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)
  4. 4. The COMPANY database • Sample data model we’ll use during the course
  5. 5. Setup software • Oracle Database Express Edition (XE) • Oracle SQL Developer
  6. 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. 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. 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. 9. A PL/SQL program block declare -- internal program objects (e.g. variables) begin -- program logic exception -- exception handling end;
  10. 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. 11. Additional syntax rules • One statement per line – isn’t mandatory • End all execution statements with a semi-colon begin null; end;
  12. 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. 13. Generating output • Write to the output buffer using dbms_output() • set serveroutput on • GUI option in SQL Developer
  14. 14. Exercises
  15. 15. 3. The DECLARE clause • Define or declare internal program objects Name [constant] datatype [not null] [ := | default value]; l_first_name varchar2(10) := ‘Nick’; • Object name rules – – – – Maximum 30 characters Start with a letter Legal characters: $ # _ Case-insensitive
  16. 16. Complex types • %TYPE – l_first_name employee.fname%type; • Maintaining internal consistency – l_last_name l_first_name%type; – Order matters • %ROWTYPE – l_emp_rec employee%rowtype; – l_emp_rec.fname := ‘John’;
  17. 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. 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. 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 );
  20. 20. Exercises
  21. 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 ...
  22. 22. Variable assignment • Strings – l_fname := ‘John’; – l_name := l_fname || ' ' || l_lname; • Numbers – l_salary := 1000; – l_year_salary := 1000 * 12; • Dates – l_now := sysdate; – l_next_week := l_now + 7; • Booleans – l_is_active := true;
  23. 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. 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. 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. 26. DML within PL/SQL • CRUD statements – select, insert, update, delete • Transaction control – commit, rollback, savepoint
  27. 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. 28. Using sequences l_id := employee_seq.nextval; • Starting from Oracle Database 11g • Use currval after nextval
  29. 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. 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. 31. IF – THEN – ELSE if condition then ... elsif condition then ... else ... end if;
  32. 32. Simple case case expression when result1 then … when result2 then … when result3 then … else … end case;
  33. 33. Searched case case when expression1 then … when expression2 then … when expression3 then … else … end case;
  34. 34. Exercises
  35. 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. 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. 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;
  38. 38. System-defined exceptions • Common system-defined exception names – NO_DATA_FOUND – TOO_MANY_ROWS – CASE_NOT_FOUND – ZERO_DIVIDE – INVALID_NUMBER
  39. 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. 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. 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. 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. 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 ...
  44. 44. Exercises
  45. 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. 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. 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. 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. 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. 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. 51. FOR ... LOOP cursors begin for emp_rec in (select * from employee) loop dbms_output.put_line(emp_rec.ssn); end loop; end;
  52. 52. Exercises
  53. 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
  54. 54. Exercises
  55. 55. 8. Declared subprograms • Enclose commonly used logic within callable subprograms • Procedure versus function • Parameterizable
  56. 56. Exercises
  • NareshBhati7

    Jan. 1, 2021
  • fbarrio

    Oct. 28, 2019
  • VaishaliChinchkhede

    Sep. 30, 2019
  • YunusEmreien

    Oct. 22, 2018
  • yahyaali

    Sep. 17, 2018
  • MohamedShaam

    Jul. 19, 2017
  • CrystalGuider

    Jun. 6, 2017
  • bhagatsudheer77

    May. 22, 2017
  • valsad786

    Apr. 19, 2017
  • thomaskouadio2

    Mar. 3, 2017
  • slkn8276

    Feb. 8, 2017
  • jawadAhmadAhmad

    Oct. 26, 2016
  • sultanfahadkhan

    Sep. 28, 2016
  • MohammedKhalil54

    Sep. 13, 2016
  • yadhavdon

    Feb. 9, 2016
  • Shibukurian3

    Jan. 20, 2016
  • sonalimohanty5

    Jan. 12, 2016
  • logeshwari3

    Nov. 18, 2015
  • tmon368

    Sep. 20, 2015
  • ErikFernandoEspindol

    Sep. 18, 2015

The powerpoint presentation I used for a PL/SQL fundamentals course (14/10/2013 - Kontich, Belgium).

Aufrufe

Aufrufe insgesamt

15.588

Auf Slideshare

0

Aus Einbettungen

0

Anzahl der Einbettungen

8

Befehle

Downloads

2

Geteilt

0

Kommentare

0

Likes

37

×