SlideShare una empresa de Scribd logo
1 de 34
More Advanced PL/SQL
Programming
Lesson B Objectives
After completing this lesson, you should be able
to:
• Create PL/SQL decision control structures
• Use SQL queries in PL/SQL programs
• Create loops in PL/SQL programs
• Create PL/SQL tables and tables of records
• Use cursors to retrieve database data into
PL/SQL programs
• Use the exception section to handle errors in
PL/SQL programs

2
IF/THEN
•

•

•

Decision control structures
– Alter order in which statements execute
– Based on values of certain variables
Syntax:
IF condition THEN
commands that execute if condition is TRUE;
END IF;
Condition
– Expression evaluates to TRUE or FALSE
– If TRUE commands execute

3
• Question: What two lines do you need to change to make the
program display Today is not Friday when the current
day is different than Friday?
4
• Syntax:

IF/THEN/ELSE

IF condition THEN
commands that execute if condition is TRUE;
ELSE
commands that execute if condition is FALSE;
END IF;

• Evaluates ELSE command if condition FALSE

Nested IF/THEN/ELSE
• Placing one or more IF/THEN/ELSE statements
within program statements that execute after IF or
ELSE command
• Important to properly indent program lines

5
IF/THEN/ELSE
Nested IF/THEN/ELSE
IF/ELSIF

8
Logical Operators AND, OR, and NOT
• Create complex expressions for decision control structure
condition
• AND: Expressions on both sides of operator must be true
for combined expression to be TRUE
• OR: Expressions on either side of operator must be true
for combined expression to be TRUE
• Order of evaluation (precedence):
– NOT
– AND
– OR

• Parentheses can be used to override precedence and force the
program to evaluate the OR first

9
Using SQL Queries in PL/SQL Programs
• Use SQL action query
– Put query or command in PL/SQL program
– Use same syntax as the syntax used to execute query or
command in SQL*Plus
– Can use variables instead of literal values like ‘Tammy’

• To specify data values

INSERT INTO Student (s_first)
VALUES (curr_first_name);

WHERE s_first = curr_first_name;

10
Changing the values
one by one and
adding them to the
table requires a lot of
coding. What is the
best way of
handling this kind
of repetitive job in
programming?
Loops
• Systematically executes program statements
• Periodically evaluates exit condition to
determine if loop should repeat or exit
• Pretest loop
– Evaluates exit condition before any program
commands execute

• Posttest loop
– Executes program commands before loop
evaluates exit condition for first time

• PL/SQL has 5 types of loop structures:
– LOOP…EXIT
- WHILE…LOOP
– LOOP…EXIT WHEN - Numeric FOR loop
– Cursor FOR loop
12
The LOOP...EXIT Loop
SQL statement
CREATE TABLE count_table
(counter NUMBER(2));

• Pretest or posttest
• Syntax:

Syntax

LOOP
[program statements]
IF condition THEN
EXIT;
END IF;
[additional program
statements]
END LOOP;
The LOOP...EXIT WHEN Loop
Syntax (posttest loop)

LOOP
program statements
EXIT WHEN condition;
END LOOP;
The WHILE...LOOP
Syntax

• WHILE…LOOP is
a Pretest loop

Q: Why the
SELECT * FROM
count_table shows
only counter 6 to 10?

WHILE condition LOOP
program statements
END LOOP;
The Numeric FOR Loop
• Does not require explicit counter increment

Syntax
FOR counter_variable IN start_value .. end_value
LOOP
program statements
END LOOP;
Cursor
• A pointer to memory location on database
server
• Used to:
– Retrieve and manipulate database data in
PL/SQL programs

• Types:
– Implicit cursor
– Explicit cursor
Implicit Cursors
• Context area
– A memory location created by INSERT, UPDATE, DELETE, or
SELECT
– Contains information about query (# rows, etc.)

• Active set
– Set of data rows that query retrieves when a SELECT query
is issued

• Implicit cursor
– A pointer to the context area
– Called so, because you do not need to write code to
explicitly create the cursor or retrieve its values
– Used to assign output of SELECT query to PL/SQL program
variables when query will return only one record*
* Error occurs if query returns no records or more than one record
Implicit Cursors (continued)
• To retrieve data using implicit cursor in
PL/SQL, you add an INTO clause to the SELECT
query
• Syntax:
SELECT field1, field2, ...
INTO variable1, variable2, ...
FROM table1, table2, ...
WHERE join_conditions
AND search_condition_to_retrieve_1_record;

• Variables must be declared in Declaration
section
• Variables must have same data types as fields
• To avoid errors, %TYPE reference data type
should be used
Implicit Cursors (continued)
Explicit Cursors
• Retrieve and display data in PL/SQL programs
for query that might
– Retrieve multiple records
– Return no records at all

• Must explicitly write the code to
–
–
–
–

Declare cursor
Open cursor
Fetch data rows
Close cursor
Explicit Cursors (continued)
• Declare explicit cursor syntax:
– CURSOR cursor_name IS select_query;

• Open explicit cursor syntax:
– OPEN cursor_name;

• Fetch values using LOOP…EXIT WHEN loop:
LOOP
FETCH cursor_name INTO
variable_name(s);
EXIT WHEN cursor_name%NOTFOUND;

• Close cursor syntax:
– CLOSE cursor_name;
Note: When the cursor is declared, system doesn’t check syntax error in the
query. It creates the memory structure to store the active set. The PL/SQL
interpreter checks for error and interprets the query when opening the cursor
Q: At this point, what is the
value for current_bldg_code?
• Using %ROWTYPE variable to display
explicit cursor values

Using a cursor and a single variable to
retrieve multiple fields values
Handling Runtime Errors in PL/SQL
Programs

• Runtime errors

– Occur when an exception (unwanted event) is raised
– Cause program to fail during execution

• Possible causes (exceptions):
– Division by zero
– Constraint violation

- inserting incompatible data
- retrieving 0/several rows with implicit cursor

• Exception handling
– Programmers place commands in EXCEPTION section

• Handle exception options
– Correct error without notifying user of problem
– Inform user of error without taking corrective action

• After exception handler executes
– Program ends

DECLARE
variable declarations
BEGIN
program statements
EXCEPTION
error-handling statements
END;
•

Handling error procedure depends the type of exception:
– Predefined exception
– User-defined exception

- undefined exception
Predefined Exceptions
• Most common errors that occur in programs
• PL/SQL language:
– Assigns exception name
– Provides built-in exception handler for each predefined exception

• System automatically displays error message informing user of
nature of problem
Exception Handler Syntax
• Can create exception handlers to display alternate
error messages
Using the WHEN OTHERS exception
•
•

The SQLERRM built-in function is used to handle other exception
To use the SQLERRM function, you must
– Declare a VARCHAR2 variable
– Assign the declared variable the error’s text and code
Undefined Exceptions
• Less common errors
• Do not have predefined names
• Must explicitly declare exception in program’s
declaration section
• Associate new exception with specific Oracle
error code
• Create exception handler in exception section
– Using same syntax as for predefined exceptions
Example of undefined exception

Loc_id 60 doesn’t exist in LOCATION

• The ORA-02291 exception is not predefined.
• Need to explicitly declare the exception and write a handler
User-defined Exceptions
• Used to handle an exception that
– Does not raise Oracle runtime error
– But requires exception handling to
• Enforce business rules or
• Ensure integrity of database

• Example:
– Internal Northwoods’ rule is “Users can delete
row from the ENROLLMENT table only if s_grade
is NULL”
– Trying to delete a delete an ENROLLMENT row
where the s_grade is not NULL will raise an
exception that needs to be handled
Pl sql

Más contenido relacionado

La actualidad más candente

Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorialbunny0143
 
Ooabap notes with_programs
Ooabap notes with_programsOoabap notes with_programs
Ooabap notes with_programsKranthi Kumar
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesSmitha Padmanabhan
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Module-4_WTA_PHP Class & Error Handling
Module-4_WTA_PHP Class & Error HandlingModule-4_WTA_PHP Class & Error Handling
Module-4_WTA_PHP Class & Error HandlingSIVAKUMAR V
 
Abap course chapter 7 abap objects and bsp
Abap course   chapter 7 abap objects and bspAbap course   chapter 7 abap objects and bsp
Abap course chapter 7 abap objects and bspMilind Patil
 
0106 debugging
0106 debugging0106 debugging
0106 debuggingvkyecc1
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQLlubna19
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14Terry Yoast
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsGaruda Trainings
 

La actualidad más candente (20)

Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorial
 
Ooabap notes with_programs
Ooabap notes with_programsOoabap notes with_programs
Ooabap notes with_programs
 
Plsql
PlsqlPlsql
Plsql
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
 
Cursors
CursorsCursors
Cursors
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
Module-4_WTA_PHP Class & Error Handling
Module-4_WTA_PHP Class & Error HandlingModule-4_WTA_PHP Class & Error Handling
Module-4_WTA_PHP Class & Error Handling
 
Abap slides set1
Abap slides set1Abap slides set1
Abap slides set1
 
Project Report on SAP
Project Report on SAPProject Report on SAP
Project Report on SAP
 
Pl sql-ch2
Pl sql-ch2Pl sql-ch2
Pl sql-ch2
 
Abap course chapter 7 abap objects and bsp
Abap course   chapter 7 abap objects and bspAbap course   chapter 7 abap objects and bsp
Abap course chapter 7 abap objects and bsp
 
Cursors
CursorsCursors
Cursors
 
PL/SQL Part 1
PL/SQL Part 1PL/SQL Part 1
PL/SQL Part 1
 
Les14
Les14Les14
Les14
 
0106 debugging
0106 debugging0106 debugging
0106 debugging
 
Abap slide class3
Abap slide class3Abap slide class3
Abap slide class3
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
 

Destacado

Plan de negocios tonic life.
Plan de negocios tonic life.Plan de negocios tonic life.
Plan de negocios tonic life.inven2
 
Thermojetics Bebida InstantáNea
Thermojetics Bebida InstantáNeaThermojetics Bebida InstantáNea
Thermojetics Bebida InstantáNeasaludytriunfo
 
Plan de Compensación Tonic Life 2016 México
Plan de Compensación Tonic Life 2016 MéxicoPlan de Compensación Tonic Life 2016 México
Plan de Compensación Tonic Life 2016 MéxicoAlfonso Castro Flores
 
PERFORMANCE PROTEIN POWDER
PERFORMANCE PROTEIN POWDERPERFORMANCE PROTEIN POWDER
PERFORMANCE PROTEIN POWDERsaludytriunfo
 
Catálogo Tonic Life 2016 - México Versión Enero
Catálogo Tonic Life 2016 - México Versión EneroCatálogo Tonic Life 2016 - México Versión Enero
Catálogo Tonic Life 2016 - México Versión EneroAlfonso Castro Flores
 
Entorno economico 2015 2016 jjprado. pptx
Entorno economico 2015 2016 jjprado. pptxEntorno economico 2015 2016 jjprado. pptx
Entorno economico 2015 2016 jjprado. pptxJulio Jose Prado
 

Destacado (6)

Plan de negocios tonic life.
Plan de negocios tonic life.Plan de negocios tonic life.
Plan de negocios tonic life.
 
Thermojetics Bebida InstantáNea
Thermojetics Bebida InstantáNeaThermojetics Bebida InstantáNea
Thermojetics Bebida InstantáNea
 
Plan de Compensación Tonic Life 2016 México
Plan de Compensación Tonic Life 2016 MéxicoPlan de Compensación Tonic Life 2016 México
Plan de Compensación Tonic Life 2016 México
 
PERFORMANCE PROTEIN POWDER
PERFORMANCE PROTEIN POWDERPERFORMANCE PROTEIN POWDER
PERFORMANCE PROTEIN POWDER
 
Catálogo Tonic Life 2016 - México Versión Enero
Catálogo Tonic Life 2016 - México Versión EneroCatálogo Tonic Life 2016 - México Versión Enero
Catálogo Tonic Life 2016 - México Versión Enero
 
Entorno economico 2015 2016 jjprado. pptx
Entorno economico 2015 2016 jjprado. pptxEntorno economico 2015 2016 jjprado. pptx
Entorno economico 2015 2016 jjprado. pptx
 

Similar a Pl sql

Similar a Pl sql (20)

PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Mis4200notes8 2
Mis4200notes8 2Mis4200notes8 2
Mis4200notes8 2
 
PL_SQL - II.pptx
PL_SQL - II.pptxPL_SQL - II.pptx
PL_SQL - II.pptx
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handling
 
Plsql guide 2
Plsql guide 2Plsql guide 2
Plsql guide 2
 
4 cursors
4 cursors4 cursors
4 cursors
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
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
 
4. plsql
4. plsql4. plsql
4. plsql
 
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
 
Oracle forms les15
Oracle forms  les15Oracle forms  les15
Oracle forms les15
 
Store programs
Store programsStore programs
Store programs
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 function
 
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
 
PL/SQL CURSORES
PL/SQL CURSORESPL/SQL CURSORES
PL/SQL CURSORES
 
Lecture 2.3.26_Conditional Control Structure.pptx
Lecture 2.3.26_Conditional Control Structure.pptxLecture 2.3.26_Conditional Control Structure.pptx
Lecture 2.3.26_Conditional Control Structure.pptx
 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
 

Más de Hitesh Kumar Markam (18)

Concepts of Distributed Computing & Cloud Computing
Concepts of Distributed Computing & Cloud Computing Concepts of Distributed Computing & Cloud Computing
Concepts of Distributed Computing & Cloud Computing
 
Data guard
Data guardData guard
Data guard
 
Tunning overview
Tunning overviewTunning overview
Tunning overview
 
Resize sga
Resize sgaResize sga
Resize sga
 
Rman offline backup
Rman offline backupRman offline backup
Rman offline backup
 
Oracle shutdown
Oracle shutdownOracle shutdown
Oracle shutdown
 
Log miner in oracle.ppt
Log miner in oracle.pptLog miner in oracle.ppt
Log miner in oracle.ppt
 
Dba in 2 days unit no 9
Dba in 2 days unit no 9Dba in 2 days unit no 9
Dba in 2 days unit no 9
 
5 backuprecoveryw imp
5 backuprecoveryw imp5 backuprecoveryw imp
5 backuprecoveryw imp
 
Rmanpres
RmanpresRmanpres
Rmanpres
 
Oracle archi ppt
Oracle archi pptOracle archi ppt
Oracle archi ppt
 
Lecture2 oracle ppt
Lecture2 oracle pptLecture2 oracle ppt
Lecture2 oracle ppt
 
Dbms objective and subjective notes
Dbms objective and subjective notesDbms objective and subjective notes
Dbms objective and subjective notes
 
Dba in 2 days
Dba in 2 daysDba in 2 days
Dba in 2 days
 
Creating database
Creating databaseCreating database
Creating database
 
1 plsql introduction1
1 plsql introduction11 plsql introduction1
1 plsql introduction1
 
javascript code for mysql database connection
javascript code for mysql database connectionjavascript code for mysql database connection
javascript code for mysql database connection
 
Advanced Planning And Optimization
Advanced Planning And OptimizationAdvanced Planning And Optimization
Advanced Planning And Optimization
 

Último

IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 

Último (20)

IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 

Pl sql

  • 2. Lesson B Objectives After completing this lesson, you should be able to: • Create PL/SQL decision control structures • Use SQL queries in PL/SQL programs • Create loops in PL/SQL programs • Create PL/SQL tables and tables of records • Use cursors to retrieve database data into PL/SQL programs • Use the exception section to handle errors in PL/SQL programs 2
  • 3. IF/THEN • • • Decision control structures – Alter order in which statements execute – Based on values of certain variables Syntax: IF condition THEN commands that execute if condition is TRUE; END IF; Condition – Expression evaluates to TRUE or FALSE – If TRUE commands execute 3
  • 4. • Question: What two lines do you need to change to make the program display Today is not Friday when the current day is different than Friday? 4
  • 5. • Syntax: IF/THEN/ELSE IF condition THEN commands that execute if condition is TRUE; ELSE commands that execute if condition is FALSE; END IF; • Evaluates ELSE command if condition FALSE Nested IF/THEN/ELSE • Placing one or more IF/THEN/ELSE statements within program statements that execute after IF or ELSE command • Important to properly indent program lines 5
  • 9. Logical Operators AND, OR, and NOT • Create complex expressions for decision control structure condition • AND: Expressions on both sides of operator must be true for combined expression to be TRUE • OR: Expressions on either side of operator must be true for combined expression to be TRUE • Order of evaluation (precedence): – NOT – AND – OR • Parentheses can be used to override precedence and force the program to evaluate the OR first 9
  • 10. Using SQL Queries in PL/SQL Programs • Use SQL action query – Put query or command in PL/SQL program – Use same syntax as the syntax used to execute query or command in SQL*Plus – Can use variables instead of literal values like ‘Tammy’ • To specify data values INSERT INTO Student (s_first) VALUES (curr_first_name); WHERE s_first = curr_first_name; 10
  • 11. Changing the values one by one and adding them to the table requires a lot of coding. What is the best way of handling this kind of repetitive job in programming?
  • 12. Loops • Systematically executes program statements • Periodically evaluates exit condition to determine if loop should repeat or exit • Pretest loop – Evaluates exit condition before any program commands execute • Posttest loop – Executes program commands before loop evaluates exit condition for first time • PL/SQL has 5 types of loop structures: – LOOP…EXIT - WHILE…LOOP – LOOP…EXIT WHEN - Numeric FOR loop – Cursor FOR loop 12
  • 13. The LOOP...EXIT Loop SQL statement CREATE TABLE count_table (counter NUMBER(2)); • Pretest or posttest • Syntax: Syntax LOOP [program statements] IF condition THEN EXIT; END IF; [additional program statements] END LOOP;
  • 14. The LOOP...EXIT WHEN Loop Syntax (posttest loop) LOOP program statements EXIT WHEN condition; END LOOP;
  • 15. The WHILE...LOOP Syntax • WHILE…LOOP is a Pretest loop Q: Why the SELECT * FROM count_table shows only counter 6 to 10? WHILE condition LOOP program statements END LOOP;
  • 16. The Numeric FOR Loop • Does not require explicit counter increment Syntax FOR counter_variable IN start_value .. end_value LOOP program statements END LOOP;
  • 17. Cursor • A pointer to memory location on database server • Used to: – Retrieve and manipulate database data in PL/SQL programs • Types: – Implicit cursor – Explicit cursor
  • 18. Implicit Cursors • Context area – A memory location created by INSERT, UPDATE, DELETE, or SELECT – Contains information about query (# rows, etc.) • Active set – Set of data rows that query retrieves when a SELECT query is issued • Implicit cursor – A pointer to the context area – Called so, because you do not need to write code to explicitly create the cursor or retrieve its values – Used to assign output of SELECT query to PL/SQL program variables when query will return only one record* * Error occurs if query returns no records or more than one record
  • 19. Implicit Cursors (continued) • To retrieve data using implicit cursor in PL/SQL, you add an INTO clause to the SELECT query • Syntax: SELECT field1, field2, ... INTO variable1, variable2, ... FROM table1, table2, ... WHERE join_conditions AND search_condition_to_retrieve_1_record; • Variables must be declared in Declaration section • Variables must have same data types as fields • To avoid errors, %TYPE reference data type should be used
  • 21. Explicit Cursors • Retrieve and display data in PL/SQL programs for query that might – Retrieve multiple records – Return no records at all • Must explicitly write the code to – – – – Declare cursor Open cursor Fetch data rows Close cursor
  • 22. Explicit Cursors (continued) • Declare explicit cursor syntax: – CURSOR cursor_name IS select_query; • Open explicit cursor syntax: – OPEN cursor_name; • Fetch values using LOOP…EXIT WHEN loop: LOOP FETCH cursor_name INTO variable_name(s); EXIT WHEN cursor_name%NOTFOUND; • Close cursor syntax: – CLOSE cursor_name; Note: When the cursor is declared, system doesn’t check syntax error in the query. It creates the memory structure to store the active set. The PL/SQL interpreter checks for error and interprets the query when opening the cursor
  • 23. Q: At this point, what is the value for current_bldg_code?
  • 24. • Using %ROWTYPE variable to display explicit cursor values Using a cursor and a single variable to retrieve multiple fields values
  • 25. Handling Runtime Errors in PL/SQL Programs • Runtime errors – Occur when an exception (unwanted event) is raised – Cause program to fail during execution • Possible causes (exceptions): – Division by zero – Constraint violation - inserting incompatible data - retrieving 0/several rows with implicit cursor • Exception handling – Programmers place commands in EXCEPTION section • Handle exception options – Correct error without notifying user of problem – Inform user of error without taking corrective action • After exception handler executes – Program ends DECLARE variable declarations BEGIN program statements EXCEPTION error-handling statements END;
  • 26. • Handling error procedure depends the type of exception: – Predefined exception – User-defined exception - undefined exception
  • 27. Predefined Exceptions • Most common errors that occur in programs • PL/SQL language: – Assigns exception name – Provides built-in exception handler for each predefined exception • System automatically displays error message informing user of nature of problem
  • 28. Exception Handler Syntax • Can create exception handlers to display alternate error messages
  • 29.
  • 30. Using the WHEN OTHERS exception • • The SQLERRM built-in function is used to handle other exception To use the SQLERRM function, you must – Declare a VARCHAR2 variable – Assign the declared variable the error’s text and code
  • 31. Undefined Exceptions • Less common errors • Do not have predefined names • Must explicitly declare exception in program’s declaration section • Associate new exception with specific Oracle error code • Create exception handler in exception section – Using same syntax as for predefined exceptions
  • 32. Example of undefined exception Loc_id 60 doesn’t exist in LOCATION • The ORA-02291 exception is not predefined. • Need to explicitly declare the exception and write a handler
  • 33. User-defined Exceptions • Used to handle an exception that – Does not raise Oracle runtime error – But requires exception handling to • Enforce business rules or • Ensure integrity of database • Example: – Internal Northwoods’ rule is “Users can delete row from the ENROLLMENT table only if s_grade is NULL” – Trying to delete a delete an ENROLLMENT row where the s_grade is not NULL will raise an exception that needs to be handled