SlideShare ist ein Scribd-Unternehmen logo
1 von 56
PL/SQL Fundamentals I
Kontich, Belgium
14/10 – 15/10
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
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)
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)
– CompanyDefine.sql

• Insert the COMPANY data (DML)
– CompanyInsert.sql
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
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)
A PL/SQL program block
declare
-- internal program objects (e.g. variables)
begin
-- program logic
exception
-- exception handling
end;
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
...
*/
Additional syntax rules
• One statement per line – isn’t mandatory
• End all execution statements with a semi-colon
begin
null;
end;
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 (...)’;
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 value];
l_first_name varchar2(10) := ‘Nick’;

• Object name rules
–
–
–
–

Maximum 30 characters
Start with a letter
Legal characters: $ # _
Case-insensitive
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’;
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’;
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’;
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
);
Exercises
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
...
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;
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
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()
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!’; 
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_FOUND or TOO_MANY_ROWS exceptions

select *
into l_emp
from employee
where ssn = ‘123456789’;
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 and readability
• A GOTO statement jumps to a label location
– GOTO labelName;

• Using GOTO is a bad practice
Loops
loop ... end loop;
loop ... exit [when condition]; end loop;
while condition loop ... end loop;

for index in [reverse] x .. y loop
...
end loop;
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 different types of exceptions
– System exceptions raised by Oracle
– Programmer-defined exceptions
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
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;
System-defined exceptions
• Common system-defined exception names
– NO_DATA_FOUND
– TOO_MANY_ROWS
– CASE_NOT_FOUND
– ZERO_DIVIDE
– INVALID_NUMBER
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
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
...
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
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
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
...
Exercises
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
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;
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;
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;
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;
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);
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
• 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
Exercises
8. Declared subprograms
• Enclose commonly used logic within callable
subprograms
• Procedure versus function
• Parameterizable
Exercises

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Plsql
PlsqlPlsql
Plsql
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statments
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
PLSQL
PLSQLPLSQL
PLSQL
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 

Andere mochten auch

Oracle sql & plsql
Oracle sql & plsqlOracle sql & plsql
Oracle sql & plsqlSid Xing
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overviewhonglee71
 
Oracle database 12c sql worshop 2 student guide vol 2
Oracle database 12c sql worshop 2 student guide vol 2Oracle database 12c sql worshop 2 student guide vol 2
Oracle database 12c sql worshop 2 student guide vol 2Otto Paiz
 
Oracle 11g PL/SQL notes
Oracle 11g PL/SQL notesOracle 11g PL/SQL notes
Oracle 11g PL/SQL notesanilakduygu
 
Oracle Database 11g: Learn and Master PL/SQL | Course Outline
Oracle Database 11g: Learn and Master PL/SQL | Course OutlineOracle Database 11g: Learn and Master PL/SQL | Course Outline
Oracle Database 11g: Learn and Master PL/SQL | Course OutlineDwight Cummings
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorialMohd Tousif
 
Oracle 10g sql fundamentals i
Oracle 10g sql fundamentals iOracle 10g sql fundamentals i
Oracle 10g sql fundamentals iManaswi Sharma
 
Oracle 11g new features for developers
Oracle 11g new features for developersOracle 11g new features for developers
Oracle 11g new features for developersScott Wesley
 
Oracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsOracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsScott Wesley
 
Advanced PL/SQL Optimizing for Better Performance 2016
Advanced PL/SQL Optimizing for Better Performance 2016Advanced PL/SQL Optimizing for Better Performance 2016
Advanced PL/SQL Optimizing for Better Performance 2016Zohar Elkayam
 
Oracle - Program with PL/SQL - Lession 04
Oracle - Program with PL/SQL - Lession 04Oracle - Program with PL/SQL - Lession 04
Oracle - Program with PL/SQL - Lession 04Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07Thuan Nguyen
 
Oracle database 12c sql worshop 2 activity guide
Oracle database 12c sql worshop 2 activity guideOracle database 12c sql worshop 2 activity guide
Oracle database 12c sql worshop 2 activity guideOtto Paiz
 

Andere mochten auch (19)

Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
Oracle sql & plsql
Oracle sql & plsqlOracle sql & plsql
Oracle sql & plsql
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 
Oracle database 12c sql worshop 2 student guide vol 2
Oracle database 12c sql worshop 2 student guide vol 2Oracle database 12c sql worshop 2 student guide vol 2
Oracle database 12c sql worshop 2 student guide vol 2
 
Oracle 11g PL/SQL notes
Oracle 11g PL/SQL notesOracle 11g PL/SQL notes
Oracle 11g PL/SQL notes
 
Oracle Database 11g: Learn and Master PL/SQL | Course Outline
Oracle Database 11g: Learn and Master PL/SQL | Course OutlineOracle Database 11g: Learn and Master PL/SQL | Course Outline
Oracle Database 11g: Learn and Master PL/SQL | Course Outline
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorial
 
Oracle 10g sql fundamentals i
Oracle 10g sql fundamentals iOracle 10g sql fundamentals i
Oracle 10g sql fundamentals i
 
Plsql
PlsqlPlsql
Plsql
 
Oracle 11g new features for developers
Oracle 11g new features for developersOracle 11g new features for developers
Oracle 11g new features for developers
 
Oracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsOracle PL/SQL Bulk binds
Oracle PL/SQL Bulk binds
 
Advanced PL/SQL Optimizing for Better Performance 2016
Advanced PL/SQL Optimizing for Better Performance 2016Advanced PL/SQL Optimizing for Better Performance 2016
Advanced PL/SQL Optimizing for Better Performance 2016
 
Oracle - Program with PL/SQL - Lession 04
Oracle - Program with PL/SQL - Lession 04Oracle - Program with PL/SQL - Lession 04
Oracle - Program with PL/SQL - Lession 04
 
Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18
 
Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10Oracle - Program with PL/SQL - Lession 10
Oracle - Program with PL/SQL - Lession 10
 
Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07Oracle - Program with PL/SQL - Lession 07
Oracle - Program with PL/SQL - Lession 07
 
Oracle database 12c sql worshop 2 activity guide
Oracle database 12c sql worshop 2 activity guideOracle database 12c sql worshop 2 activity guide
Oracle database 12c sql worshop 2 activity guide
 

Ähnlich wie PL/SQL Fundamentals I

Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 functiondipumaliy
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programmingRushdi Shams
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handlingSmitha Padmanabhan
 
Stored procedures
Stored proceduresStored procedures
Stored proceduresMuksNoor
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPTSujayaBiju
 
Oracle db subprograms
Oracle db subprogramsOracle db subprograms
Oracle db subprogramsSimon Huang
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingSteven Feuerstein
 

Ähnlich wie PL/SQL Fundamentals I (20)

Mis4200notes8 2
Mis4200notes8 2Mis4200notes8 2
Mis4200notes8 2
 
Pl sql
Pl sqlPl sql
Pl sql
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
plsql.ppt
plsql.pptplsql.ppt
plsql.ppt
 
Plsql guide 2
Plsql guide 2Plsql guide 2
Plsql guide 2
 
PL_SQL - II.pptx
PL_SQL - II.pptxPL_SQL - II.pptx
PL_SQL - II.pptx
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 function
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handling
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Oracle db subprograms
Oracle db subprogramsOracle db subprograms
Oracle db subprograms
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk Processing
 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
 

Kürzlich hochgeladen

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

PL/SQL Fundamentals I

  • 1. PL/SQL Fundamentals I Kontich, Belgium 14/10 – 15/10
  • 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. 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. The COMPANY database • Sample data model we’ll use during the course
  • 5. Setup software • Oracle Database Express Edition (XE) • Oracle SQL Developer
  • 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
  • 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. 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. 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 ...
  • 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. 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;
  • 32. Simple case case expression when result1 then … when result2 then … when result3 then … else … end case;
  • 33. Searched case case when expression1 then … when expression2 then … when expression3 then … else … end case;
  • 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;
  • 38. System-defined exceptions • Common system-defined exception names – NO_DATA_FOUND – TOO_MANY_ROWS – CASE_NOT_FOUND – ZERO_DIVIDE – INVALID_NUMBER
  • 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
  • 55. 8. Declared subprograms • Enclose commonly used logic within callable subprograms • Procedure versus function • Parameterizable

Hinweis der Redaktion

  1. Portable: OS independentSGA = System Global Area
  2. CASE_NOT_FOUND exception
  3. CASE_NOT_FOUND exception