SlideShare a Scribd company logo
1 of 50
VISTA
Powered by
Institute of Computer Education
ORACLE PL / SQL
CHAPTER 2: PL / SQL PROGRAM
STRUCTURE
by Prabhat Kumar
Contents
 Conditional and Sequential Control:
- If Statements.
- CASE Statement and Expression.
- GOTO Statement.
- NULL Statement.
 Iterative Processing:
- The Simple Loop.
- The WHILE Loop.
- The Numeric FOR Loop.
- The Cursor FOR Loop.
- The CONTINUE Statement.
 Exception Handling:
- Define and Raise Exceptions.
- Handling Exceptions.
- Built- in Error Functions
 Practitioners Guide.
 Error Codes.
 A bit of an Advice.
VIC 3
Conditional and Sequential Control
These can be divided into following categories:
 IF Statements:
- implement conditional branching logic in a program.
- Business Logics such as below can be implemented with these:
- If the price is greater than $1000 than offer discount 10% else if price > $2000 then 15%
discount
else 20%.Lets give it a name, say BL_1.
- The IF Statement can be combined in three ways as:
- The IF-THEN Combination:
- implements if condition in a program.
- General Format:
IF condition
THEN
*** sequence of executable statements ***
END IF; VIC 4
- The IF Statement can be combined in three ways as:
- The IF-THEN Combination:
- implements if condition in a program.
- General Format:
IF condition
THEN
*** sequence of executable statements ***
END IF;
- the condition can be a constant, Boolean variable or an expression evaluating to
TRUE/FALSE/NULL.
- if condition is TRUE, the statements found between THEN keyword & matching END IF
statement are
executed.
- if condition is FALSE/NULL, these statements are not executed at all.
- Below code is a part of PL/SQL implementing conditional logic based on If Statement:
IF price > 1000
THEN
price := price - (( price * 10 ) / 100) ;-------10 % discount
END IF; VIC 5
- The IF-THEN-ELSE Combination:
- implements either/or condition in a program.
- General Format:
IF condition
THEN
*** sequence of executable statements when TRUE ***
ELSE
*** sequence of executable statements when FALSE/NULL ***
END IF;
- condition can be a constant, Boolean variable or an expression evaluating to TRUE/FALSE/NULL.
- IF condition is TRUE, the statements found between THEN keyword and ELSE keyword are executed.
- IF condition is FALSE/NULL, the statements found between ELSE keyword and matching END IF
statement
are executed.
- Below code is a part of PL/SQL implementing conditional logic based on IF-THEN-ELSE Statement:
IF price > 1000
THEN
price := price - (( price * 10 ) / 100) ;-------10 % discount
ELSE
price := price - (( price * 20 ) / 100) ;-------20 % discount
END IF;
VIC 6
- The IF-THEN-ELSIF Combination:
- implements logic having many alternatives.
- ELSIF is used to handle mutually exclusive alternatives.
- General Format:
IF condition-1
THEN
statements-1
ELSIF condition-N
THEN
statements-N
ELSE
else_statements
END IF;
- condition can be a constant, Boolean variable or an expression evaluating to
TRUE/FALSE/NULL.
- if condition-1 is TRUE, the statements found between THEN keyword and first ELSIF
keyword are
executed.
- if condition-1 is FALSE/NULL, then statements-N with condition-N resulting to TRUE will
be executed.
- if none of the condition results to TRUE, then, statements between ELSE keyword and
matching
VIC 7
VIC 8
- Nested IF Statements:
- IF statement can be nested within any other IF statement.
- Several Layered Nested IF Statements looks like:
IF condition1
THEN
IF condition2
THEN
statements2
ELSE
IF condition3
THEN
statements3
ELSIF condition4
THEN
statements4
END IF;
END IF;
END IF;
VIC 9
 CASE Statement and Expression:
- allows selection of one sequence of statements out of many possible sequences for
execution.
- types of CASE Statements:
1.Simple CASE statement:
- provides binding of one or more sequence of statements with a value.
- sequence of statements having value equal to the result of the expression are executed.
- General Format:
CASE expression
WHEN result1 THEN
statements1
WHEN result2 THEN
statements2
ELSE
statements_else
END CASE;
- expression is evaluated and result is compared with the values in WHEN clause(
result1,result2...).
- WHEN clauses are executed from top to bottom, hence, statements associated with first
expression
resulting to TRUE are executed.
- otherwise, statements_else is executed, written in ELSE condition(an optional part).
- Example for Simple CASE statement is shown below:
CASE discount
WHEN 10 THEN
price := price - (( price * 10 ) / 100) ;-------10 % discount
WHEN 20 THEN
price := price - (( price * 20 ) / 100) ;-------20 % discount
ELSE
price := price - (( price * 30 ) / 100) ;-------30 % discount
END CASE;
- this code implements discount logic as explained in IF Statements using CASE Statements.
VIC 10
2.Searched CASE Statements:
- evaluates Boolean expressions in the list.
- executes a sequence of statements associated with the expression resulting to TRUE.
- General Format:
CASE
WHEN expression1 THEN
statements1
WHEN expression2 THEN
statements2
ELSE
statements_else
END CASE;
- if expression1 is TRUE then, statements1 is executed else if expression2 is TRUE then
statements2 is executed.
- in case no expression results to TRUE then, statements_else is executed.
- Example of Searched CASE Statement is shown below:
CASE
WHEN discount = 10 THEN
price := price - (( price * 10 ) / 100) ;-------10 % discount
WHEN discount = 20 THEN
price := price - (( price * 20 ) / 100) ;-------20 % discount
ELSE
price := price - (( price * 30 ) / 100) ;-------30 % discount
END CASE;
VIC 11
- CASE Expressions:
- chooses an expression (not statements as done by CASE Statements) to be evaluated based on input
scalar value.
- General Format:
1.Simple CASE Expressions:
Simple_Case_Expression := CASE expression
WHEN result1 THEN
result_expression1
WHEN result2 THEN
result_expression2
...
ELSE
result_expression_else
END;
2.Searched CASE Expressions:
Searched_Case_Expression := CASE
WHEN expression1 THEN
result_expression1
WHEN expression2 THEN
result_expression2
...
ELSE
result_expression_else
END;
VIC 12
Example of CASE Expressions
DECLARE
price NUMBER(26, 2);
discount INTEGER:=10;
final_amount NUMBER(26,2);
BEGIN
price := 1000;
discount := 10;
final_amount :=
price -
CASE
WHEN discount > 0 AND discount <=
10 THEN ( price * 10 ) / 100
WHEN discount > 10 AND discount <=
20 THEN ( price * 20 ) / 100
ELSE ( price * 30 ) / 100
END;
dbms_output.put_line
('Final Price is '||final_amount||' with '||
discount||' % '||'discount Offered.');
END;
13
VIC
DECLARE
price NUMBER(26, 2);
discount INTEGER:=10;
final_amount NUMBER(26,2);
BEGIN
price := 1000;
discount := 10;
final_amount :=
price -
CASE discount > 0 AND discount <= 10
WHEN TRUE
THEN ( price * 10 ) / 100
WHEN FALSE
THEN ( price * 20 ) / 100
ELSE ( price * 30 ) / 100
END;
dbms_output.put_line
('Final Price is '||final_amount||' with '||
NVL(discount, 30)||' % '||'discount Offered.');
END;
 The GOTO Statements:
- allows unconditional branching to another executable statement in same execution section of a
PL/SQL block.
- General Format:
GOTO label_name;
- label_name is the name of a label identifying the target statement, defined as
<<label_name>>.
- once PL/SQL encounters GOTO, execution control goes to first executable statement following the
label.
- there must be at least one executable statement following the label.
- target statement must be in the same scope as the GOTO statement.
- target statement and the GOTO statement must be in the same scope.
 The NULL Statements:
- tells PL/SQL to do nothing.
- General Format:
NULL;
- Reserved keyword NULL followed by;(semicolon)
- it improves readability of code.
- helps in managing codes having the GOTO Statements.
VIC 14
VIC 15
Iterative Processing
- iterative processing in programming implies to executing same set of statement repeatedly.
- iterative control structures commonly known as loops helps in this type of programming.
- Business Logics such as below can be implemented with these:
- add 100 to a given value until that values becomes greater than 1000.Lets give it a name, say
BL_2.
- PL/SQL provides four major categories of looping structures , explained ahead:
1. The Simple Loop:
- starts with keyword LOOP and ends with END LOOP keyword.
- set of statements coded after keyword LOOP and before keyword END LOOP are executed
iteratively.
- termination of iteration can be achieved using EXIT(for unconditional exit) or EXIT WHEN(for
conditional exit).
- Exit condition can be placed anywhere inside the Loop, if the exit condition is last statement of loop,
then
at least one iteration will be done, provided no exception occurred.
- General Syntax:
LOOP
exit_condition;
executable_statements;
END LOOP;
In computer software, Business logic or domain logic is the part of the program unit that
encodes the
real- world business rules that determines how data can be created, stored and changed.
- logic BL_2 can be implemented using Simple Loop as(loop will iterate until total_value
<1000):
LOOP
EXIT WHEN total_value > 1000;
total_value := total_value + 100;
END LOOP;
2. The WHILE Loop:
- its a conditional loop that iterates as long as the defined Boolean condition results to
TRUE.
- General Syntax:
WHILE condition
LOOP
executable_statements;
END LOOP;
- condition can be a Boolean variable or expression evaluating to
TRUE/FALSE/NULL.
- executable_statements continues to be executed provided that condition that is
being
checked at start of each iteration evaluates to TRUE.
- logic BL_2 can be implemented using WHILE Loop as:
WHILE (total_value < 1000)
LOOP
total_value := total_value + 100;
END LOOP;
VIC 16
3. The Numeric FOR Loop:
- its a counted loop in which numbers of iterations is indentified at its start.
- Business Logics such as below can be implemented with these:
increase total_value by 100 fixed 10 number of times. Lets give it a name, say BL_3.
- General Syntax:
FOR index IN [REVERSE] lowest number..highest number
LOOP
executable statements
END LOOP;
- logic BL_2 can be implemented using Numeric FOR Loop as:
FOR I IN 1..10
LOOP
total_value := total_value + 100;
END LOOP;
- loop will iterate 10 times, adding 100 to total_value at each iteration.
VIC 17
 Do not declare loop index as PL/SQL declares it automatically with datatype INTEGER.
 Range scheme are evaluated once when the loop start and cannot be changed during
execution.
 REVERSE keyword is used to decrement the loop from upper bound to the lower bound. But
still, in
range specification, lowest number is less than the highest number.
4. The Cursor FOR Loop:
- this type of loop is associated either with explicit cursor or a SELECT statement within loop
boundaries.
- provides integration of procedural constructs with SQL.( Standard Query Language).
Business Logics such as below can be implemented with these:
give 10 % discount to all the products available in store. Lets give it a name, say BL_4.
- General Syntax:
FOR record IN { explicit_cursor_name | (SELECT statement) }
LOOP
executable statements
END LOOP;
- logic BL_4 can be implemented using Cursor FOR Loop as:
FOR I IN ( SELECT product_id, product_unicode
FROM product_tab )
LOOP
UPDATE product_price_tab A
SET A.product_price = A.product_price - ((A.product_price * 10) / 100)
WHERE A.product_id = I.product_id
AND A.product_unicode = I.product_unicode;
END LOOP;
- loop will iterate for all products in product_tab table
- each iteration will update price in product_price_tab for the product picked by
PL/SQL in
that iteration. VIC 18
5. The CONTINUE Statement:
- provides immediate escape from current iteration of loop & continue on to next iteration of
that loop.
- it can be conditional and non- conditional.
- CONTINUE keyword is used for non-conditional exit of current iteration and CONTINUE
WHEN is for
conditional one.
- General Syntax:
Un-conditional:
LOOP
EXIT WHEN condition;
executable statements
CONTINUE;
executable statements
END LOOP;
VIC 19
 Table product_price_tab is given Alias A that is used further in referencing table columns. The
columns or
variables when referenced by the table alias, the package/procedure/ nested block label
name is
known to be qualified.
 For more on SQL, study CHAPTERS on VISTA ORACLE SQL.
Conditional:
LOOP
EXIT WHEN condition;
executable statements
CONTINUE WHEN continue_condition;
executable statements
END LOOP;
Below example describes a NUMERIC FOR loop, in which, iteration is skipped if the current
value of index variable is an even number:
BEGIN
FOR I IN 1..50
LOOP
CONTINUE WHEN MOD( I,2) = 0;
DBMS_OUTPUT.PUT_LINE(‘Index Value is ’|| TO_CHAR(I));
END LOOP;
END;
/
VIC 20
 Try using un-conditional CONTINUE statement with IF conditional statement to get the same
results.
VIC 21
Exception Handling
- errors of any kind are treated as exceptions.
- two general exceptions types:
- System exception:
- defined by Oracle and raised by PL/SQL runtime engine whenever error condition is detected.
- these have names, codes and descriptions. Examples are: TOO_MANY_ROWS, etc.
- Programmer-defined exception:
- these are application specific exceptions defined by the programmers.
- EXCEPTION_INIT pragma can be used to associate exception names with specific Oracle
errors.
- Concept of Exception Handling can be explained in three parts:
- Defining Exceptions:
- it involves two steps:
- naming exception by declaring it in declaration section of PL/SQL program.
- General Syntax:
exception_name EXCEPTION;
- associating Exception Names with Error Codes:
- Oracle has associated names to some of the exception like NO_DATA_FOUND, that can
be handled by name itself.
- this association can also be made by programmer using EXCEPTION_INIT pragma.
Table 1. Predefined Exceptions
Name Oracle
Error
SQLCOD
E
Raised When
TOO_MANY_ROWS ORA-01403 +100 execution of SELECET INTO statement(implicit cursor) returns more
than one row.
NO_DATA_FOUND ORA-01422 -1422 execution of SELECET INTO statement(implicit cursor) returns no rows or
when read command is executed past end-of-file with UTL_FILE package or
when uninitialized row in a local associative array is reference
VALUE_ERROR ORA-06502 -6502 conversion, truncation, or invalid constraining of numeric and character data
error. INVALID_NUMBER exception is raised when same error occurs
within PL/SQL Block.
ZERO_DIVIDE ORA-01476 -1476 program tried to divide a value by zero.
INVALID_NUMBER ORA-01722 -1722 SQL statement is executed that cannot convert a character string
successfully to a number.
INVALID_CURSOR ORA-01001 -1001 cursor not in existence is referenced( usually raise while FETCH or CLOSE
without opening cursor).
CURSOR_ALREADY_O
PEN
ORA-6511 –6511 attempt is made to open a cursor that is already opened.
DUP_VAL_ON_INDEX ORA-00001 -1 INSERT/UPDATE attempts to store column/columns in a row that are
restricted by unique constraint.
LOGIN_DENIED ORA-01017 -1017 program tries to log into the database with an invalid username/password
combination.
PROGRAM_ERROR ORA-06501 -6501 PL/SQL encounters an internal problem. The message text is generally
meant to Contact Oracle Support.
VIC 22
- Raising Exceptions:
- There are three different ways that exception can be raised in an application:
a. database itself raises an exception whenever it detects an error:
- all the executable statements will be skipped and control goes to Exception section
where that
exception is handled. In case no exception section is there program execution
terminates.
b. user can raise an exception using RAISE statement:
- this statement is used to raise named exceptions ( system or programmer defined).
- General Syntax:
RAISE exception_name;
or RAISE package_name.exception_name;
or RAISE;
c. RAISE_APPLICATION_ERROR procedure:
- used to raise application-specific errors in an application.
- error message can also be associated with an error number using this procedure.
- General Syntax: RAISE_APPLICATION_ERROR (num binary_integer, msg varchar2,VIC 23
where, num is the error number with valid value between -20,999 and -20,000.
msg is the error message with maximum of 2,000 characters.
keeperrorstack indicates whether you want to add the error to any error already on
the stack (TRUE) or replace the existing errors (FALSE).
-Handling Exceptions:
- to handle exceptions raised by names in a programme, a PL/SQL block must have an
Exception
Handling Block with one or more exception handlers:
- General Syntax for an exception handler is:
WHEN exception_name [ OR exception_name1 ... ]
THEN executable statements
- exception handlers handle exceptions by name only. Exception got handled when its
name matches
name of the exception in WHEN clause of exception handler.
- When a match is found, statements written in that WHEN clause are executed and then
control goes
out of the current PL/SQL block.
- When no match is found, WHEN OTHERS exception handler is executed(if present).
VIC 24
 Use WHEN OTHERS to handle other unhandled exceptions.
 Use SQLCODE and DBMS_UTILITY.FORMAT_ERROR_STACK to get information about the
error occurred.
VIC 25
- Built- in Error Functions:
- Oracle provide some very useful built-in functions to identify, analyze and handle errors in PL/SQL program
, like:
a.SQLCODE:
- it returns the error code of the most recent exception raised in a block.
- returns 0 in case of no error or when called from outside an exception handler.
b.SQLERRM:
- it returns error message for a particular error code with maximum length of 512 characters.
- in case no error code is passed in call to sqlerrm, error message associated with the value of
SQLCODE is
returned.
- if SQLCODE is 0 , SQLERRM return "ORA-0000: normal, successful completion".
c.DBMS_UTILITY.FORMAT_ERROR_STACK:
- it works like SQLERRM except that maximum length string returned by this function is of 1899
characters.
- it also does not take error code as argument so it can only be called inside an exception handler.
d.DBMS_UTILITY.FORMAT_ERROR_BACKTRACE:
- it returns a formatted string that contains stack of programs and line numbers leading back to the line
where
the error raised first.
e.DBMS_UTILITY.FORMAT_CALL_STACK:
- it returns formatted string displaying execution call stack inside a PL/SQL application.
Practitioners Guide
Slides ahead contains PL/SQL programs for
complete understanding of theories just
explained.Programs are designed in a way to
demonstrate the important and critical aspects of
PL/SQL programming in a unified manner.
VIC 27
In this, we will be making understanding of PL/SQL concepts explained in this
chapter by some application specific examples. Schools have certain processes
that are
followed to manage things and one of them are creating results for students
having
exams. Results are derived based on marks obtained by students in different
subjects
and based on some pre-defined criteria of schools, grades are given to students
based
on their marks obtained. Here, we will be developing a functionality(PL/SQL
program)
that will check for possible results of the students based on the marks obtained
by those
student. Result generating PL/SQL program of our SCHOOL MANGEMENT
SYSTEM(SMS) has following decision making conditions:
 Code will take student id, its current standard, exam year, exam code basically
subject
code and marks obtained by that student in that subject.
 If marks obtained is less than 30, then grace of 3 marks will be given.
 If marks is greater than 85, grade obtained is ‘A+’, between 70 and 84 grade ‘A’
and so on.
If marks is less than 30, grade obtained is ‘D-’.
If calculated grade for any student is ‘D-’ even after applying grace marks, then
 Below are the Oracle tables created for storing results of students appeared in the exam:
1. student_rexam_tab : This table will store details of students that are calculated to be eligible for Rexam
by SMS:
/* student_rexam_tab */
CREATE TABLE SMS.student_rexam_tab
(student_id VARCHAR2(50),
student_standard VARCHAR2(20),
exam_year INTEGER,
exam_code VARCHAR2(50),
marks_obtained NUMBER(26,6),
is_grace CHAR(1),
grace_val INTEGER,
grade_obtained VARCHAR2(50));
2. student_pass_tab : This table will store details of students that are calculated to be passed by SMS:
/* student_pass_tab */
CREATE TABLE SMS.student_pass_tab
(student_id VARCHAR2(50),
student_standard VARCHAR2(20),
exam_year INTEGER,
exam_code VARCHAR2(50),
marks_obtained NUMBER(26,6),
is_grace CHAR(1) DEFAULT 'N',
grade_obtained VARCHAR2(50),
is_gold_medal CHAR(1),
is_silver_medal CHAR(1),
is_bronze_medal CHAR(1));
VIC 28
SMS is our SCHOOL MANAGEMENT SYSTEM.
VIC 29
PLS_1: CREATE OR REPLACE PROCEDURE SMS.get_student_result_demo_if ( student_id_in VARCHAR2,
student_standard_in VARCHAR2, exam_year_in INTEGER, exam_code_in
VARCHAR2, marks_obtained_in NUMBER) IS
total_marks NUMBER(3):= 100;
grace_val CONSTANT SIMPLE_INTEGER:= 3;
student_grade VARCHAR2(5);
grace_applied_chk CHAR VARYING(1):= 'N';
student_pass_chk CHAR(1):='N';
gold_medal_chk CHAR(1):='N';
silver_medal_chk CHAR(1):='N';
bronze_medal_chk CHAR(1):='N';
marks_obtained NUMBER(26,3):=marks_obtained_in;
BEGIN
IF marks_obtained < 30
THEN
marks_obtained := marks_obtained + grace_val; /*Grace of three marks is given in case marks is less than
30*/
grace_applied_chk := 'Y';
END IF;
/* Obtaining grade for obtained marks after applying Grace. */
IF marks_obtained >= 85
THEN
student_grade := 'A+';
ELSIF marks_obtained >= 70 AND marks_obtained < 85
THEN
student_grade := 'A';
ELSIF marks_obtained >= 60 AND marks_obtained < 70
THEN
student_grade := 'B';
ELSIF marks_obtained >= 45 AND marks_obtained < 60
THEN
student_grade := 'C‘;
/*****to be continued on next slide*****/
ELSIF marks_obtained >= 30 AND marks_obtained < 45
THEN
student_grade := 'D';
ELSE
student_grade := 'D-';
END IF;
/* Managing Records for re-examination of Students not able to pass exam
|| even after grace being applied. */
IF grace_applied_chk = 'Y' AND student_grade = 'D-'
THEN
INSERT INTO SMS.student_rexam_tab(student_id, student_standard, exam_year, exam_code, marks_obtained,
is_grace, grace_val, grade_obtained)
VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in,
marks_obtained_in, grace_applied_chk, grace_val, student_grade);
RETURN;
ELSE
student_pass_chk := 'Y';
END IF;
/* Categorizing Students for Gold/ Silver/ Bronze Medal
||based on their actual marks.*/
IF student_pass_chk = 'Y' AND student_grade = 'A+' THEN
IF marks_obtained >= 95
THEN
gold_medal_chk := 'Y';
ELSE
IF marks_obtained >= 90 AND marks_obtained < 95
THEN
silver_medal_chk := 'Y';
ELSE
bronze_medal_chk := 'Y';
END IF;
END IF;
END IF;
VIC 30
/*Managing Records of Students applicable for Next Standard.*/
INSERT INTO SMS.student_pass_tab(student_id, student_standard, exam_year, exam_code, marks_obtained,
grade_obtained, is_grace, is_gold_medal, is_silver_medal, is_bronze_medal)
VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in,
marks_obtained_in,
student_grade, grace_applied_chk, gold_medal_chk, silver_medal_chk,
bronze_medal_chk);
END;
/
Above code PLS_1 named “SMS.get_student_result_demo_if” is a procedure that takes student
details , subject and marks obtained in that subject and produces the result based of defined logic
written inside the procedure as given by the School management to generate results of the students.
This procedure is based on conditional IF statements and its variances as described in this chapter
earlier. Most of the code is written with comment describing the logic behind that code. Firstly, it is
checked whether to apply grace or not, after that Grade is determined based on the obtained
marks(plus grace marks, if applicable).After determining grade, it is checked whether the student is
passed or need to have re-exam. For students eligible for Rexam, details are inserted in
student_rexam_tab table. If student is passed, it is checked whether that student is applicable
for Gold/Silver/Bronze medal. After, determining these details, data of students passing the
exam is inserted in student_pass_tab.
The very same functionality can be achieved through CASE statements and CASE
expressions. PL/SQL
code PLS_2 named “SMS.get_student_result_demo_case” is coded to get the same output
as above but using CASE statements and expressions.
Notice use of CASE expressions, GOTO statements, NULL statements and Nested CASE
statements (comments written against each one).
VIC 31
PLS_2:
CREATE OR REPLACE PROCEDURE SMS.get_student_result_demo_case ( student_id_in VARCHAR2,
student_standard_in VARCHAR2,
exam_year_in INTEGER, exam_code_in
VARCHAR2, marks_obtained_in NUMBER) IS
total_marks NUMBER(3):= 100;
grace_val CONSTANT SIMPLE_INTEGER:= 3;
student_grade VARCHAR2(5);
grace_applied_chk CHAR VARYING(1):= 'N';
student_pass_chk CHAR(1):='N';
medal_applicable BOOLEAN:=FALSE;
gold_medal_chk CHAR(1):='N';
silver_medal_chk CHAR(1):='N';
bronze_medal_chk CHAR(1):='N';
marks_obtained NUMBER(26,3):=marks_obtained_in;
BEGIN
/*Grace of three marks is given in case marks is less than 30*/
CASE marks_obtained < 30
WHEN TRUE
THEN
marks_obtained := marks_obtained + grace_val;
grace_applied_chk := 'Y';
ELSE
grace_applied_chk := 'N';
/*Need to add ELSE condition Otherwise CASE_NOT_FOUND exception will be raised
|| for students with marks_obtained > 30.*/
END CASE; --Simple Case Statement
/*****to be continued on next slide*****/
VIC 32
/*||Obtaining grade for obtained marks
|| after applying Grace.
*/
CASE
WHEN marks_obtained >= 85 THEN
student_grade := 'A+';
WHEN marks_obtained >= 70 AND marks_obtained < 85 THEN
student_grade := 'A';
WHEN marks_obtained >= 60 AND marks_obtained < 70 THEN
student_grade := 'B';
WHEN marks_obtained >= 45 AND marks_obtained < 60 THEN
student_grade := 'C';
WHEN marks_obtained >= 30 AND marks_obtained < 45 THEN
student_grade := 'D';
ELSE
student_grade := 'D-';
END CASE; --Searched Case Statement
/*Managing Records for re-examination of Students not able to pass exam
|| even after grace being applied.
*/
CASE
WHEN (grace_applied_chk = 'Y' AND student_grade = 'D-') = TRUE THEN
INSERT INTO SMS.student_rexam_tab(student_id, student_standard, exam_year, exam_code,
marks_obtained, is_grace, grace_val, grade_obtained)
VALUES(student_id_in, student_standard_in, exam_year_in,
exam_code_in, marks_obtained_in, grace_applied_chk,
grace_val, student_grade);
GOTO end_of_code;------GOTO Statement.
ELSE
student_pass_chk := 'Y';
END CASE;
/*****to be continued on next slide*****/
VIC 33
/*Determining Applicability for Gold/ Silver/ Bronze Medal*/
medal_applicable := CASE
WHEN student_pass_chk = 'Y' AND student_grade = 'A+' THEN
TRUE
ELSE
FALSE
END; -----Searched CASE Expressions -----CASE Expressions does not end with END
CASE;
/*Categorizing Students for Gold/ Silver/ Bronze Medal based on their actual marks. */
CASE
WHEN medal_applicable THEN
CASE WHEN marks_obtained >= 95 THEN
gold_medal_chk := 'Y';
ELSE
CASE
WHEN marks_obtained >= 90 AND marks_obtained < 95 THEN
silver_medal_chk := 'Y';
ELSE
bronze_medal_chk := 'Y';
END CASE;
END CASE;
ELSE
NULL;-------------NULL Statement.
END CASE;----------Nested Case Statement (mix of Simple and Searched CASE statements.)
/*Managing Records of Students applicable for Next Standard.*/
INSERT INTO SMS.student_pass_tab(student_id, student_standard, exam_year, exam_code,
marks_obtained, grade_obtained, is_grace,
is_gold_medal, is_silver_medal, is_bronze_medal)
VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in,
marks_obtained_in, student_grade, grace_applied_chk,
gold_medal_chk, silver_medal_chk, bronze_medal_chk);
<<end_of_code>>
NULL;
END;
VIC 34
To Test the code for various cases of student marks basically to get different result for different marks obtained by
students, try executing below scripts(you can try creating your own test cases):
/* Execution Script */
EXEC SMS.get_student_result_demo_if('S_01', '12', 2018, 'IT_01', 96);
EXEC SMS.get_student_result_demo_if('S_02', '12', 2018, 'IT_01', 92);
EXEC SMS.get_student_result_demo_if('S_03', '12', 2018, 'IT_01', 86);
EXEC SMS.get_student_result_demo_if('S_04', '12', 2018, 'IT_01', 66);
EXEC SMS.get_student_result_demo_if('S_05', '12', 2018, 'IT_01', 76);
EXEC SMS.get_student_result_demo_if('S_06', '12', 2018, 'IT_01', 46);
EXEC SMS.get_student_result_demo_if('S_07', '12', 2018, 'IT_01', 36);
EXEC SMS.get_student_result_demo_if('S_08', '12', 2018, 'IT_01', 28);
EXEC SMS.get_student_result_demo_if('S_09', '12', 2018, 'IT_01', 26);
EXEC SMS.get_student_result_demo_if('S_10', '12', 2018, 'IT_01', 22);
Same manner SMS.get_student_result_demo_case() can be executed using below scripts:
/* Execution Script */
EXEC SMS.get_student_result_demo_case('S_01', '12', 2018, 'IT_01', 96);
EXEC SMS.get_student_result_demo_case('S_02', '12', 2018, 'IT_01', 92);
EXEC SMS.get_student_result_demo_case('S_03', '12', 2018, 'IT_01', 86);
EXEC SMS.get_student_result_demo_case('S_04', '12', 2018, 'IT_01', 66);
EXEC SMS.get_student_result_demo_case('S_05', '12', 2018, 'IT_01', 76);
EXEC SMS.get_student_result_demo_case('S_06', '12', 2018, 'IT_01', 46);
EXEC SMS.get_student_result_demo_case('S_07', '12', 2018, 'IT_01', 36);
EXEC SMS.get_student_result_demo_case('S_08', '12', 2018, 'IT_01', 28);
EXEC SMS.get_student_result_demo_case('S_09', '12', 2018, 'IT_01', 26);
EXEC SMS.get_student_result_demo_case('S_10', '12', 2018, 'IT_01', 22);
VIC 35
PLS_3 is an Anonymous Block demonstrating WHILE Loop and Numeric FOR Loop in a PL/SQL
programming. Outermost WHILE loop iterates to two times increasing value of variable T with each
iteration. Inner while loops are placed to create the pattern as shown in the next slide with Numeric
FOR loops printing ‘*’ to required number of times.
PLS_3:
SQL> DECLARE
2 O NUMBER:=10;
3 L NUMBER:=1;
4 M NUMBER;
5 P NUMBER;
6 T NUMBER:=1;
7 BEGIN
8 LOOP
9 EXIT WHEN T = 3;
10 T := T+1;
11 DBMS_OUTPUT.PUT('Pattern Number '|| to_char(T-1));
12 DBMS_OUTPUT.NEW_LINE;
13 WHILE L < O
14 LOOP
15 M := 1;
16 WHILE M < O - L
17 LOOP
18 DBMS_OUTPUT.PUT(' ');
19 M := M + 2;
20 END LOOP;
21
22 FOR P IN 1..L
23 LOOP
24 DBMS_OUTPUT.PUT('*');
25 END LOOP;
VIC 36
26
27 DBMS_OUTPUT.NEW_LINE;
28 L:= L + 2;
29 END LOOP;
30 L := 7;
31 WHILE L >= 1
32 LOOP
33 M := 9;
34 WHILE M > L
35 LOOP
36 DBMS_OUTPUT.PUT(' ');
37 M := M - 2;
38 END LOOP;
39
40 FOR P IN 1..L
41 LOOP
42 DBMS_OUTPUT.PUT('*');
43 END LOOP;
44 DBMS_OUTPUT.NEW_LINE;
45 L := L - 2;
46 END LOOP;
47 END LOOP;
48 END;
49 /
VIC 37
 Use of to_char() function at Line 11 is to convert calculated value of T-1( result is of number type)
to
character value so that it can by concatenated to prefixed string.
 Use command SET SERVEROUT ON in SQLPLUS to get output on screen.
 DBMS_OUTPUT.NEW_LINE is a procedure that puts an end-of-line marker.
Pattern Number 1
*
***
*****
*******
*********
*******
*****
***
*
Pattern Number 2
*
***
*****
*******
*********
*******
*****
***
*
PL/SQL procedure successfully completed.
VIC 38
PLS_4 is an anonymous block which identifies a given number to be an Armstrong number.
A number is said to be an Armstrong number if sum of its digits raised to the power n is equal to
number itself, where n is total digits in number.
For example : 407 is Armstrong number as 43 + 03 + 73 = 64 + 0 + 343 = 407.
PLS_4:
SQL> DECLARE
2 N NUMBER:=407;
3 S NUMBER:=0;
4 R NUMBER;
5 LEN_N NUMBER;
6 M NUMBER;
7 BEGIN
8 M:=N;
9 LEN_N := LENGTH(TO_CHAR(N));
10 WHILE N>0
11 LOOP
12 R := MOD(N,10);
13 S := S+POWER( R, LEN_N);
14 N := TRUNC(N/10);
15 END LOOP;
16
17 IF M = S THEN
18 DBMS_OUTPUT.PUT_LINE('Armstrong Number.');
19 ELSE
20 DBMS_OUTPUT.PUT_LINE('Not an Armstrong Number.');
21 END IF;
22 END;
23 /
Output:
Armstrong Number.
PL/SQL procedure successfully completed.
VIC 39
PLS_5 is an anonymous block which identifies a given number to be a palindrome number.
A number is called palindrome number if its reverse is equal to itself.
For example : 12321 is palindrome while 123 is not palindrome.
PLS_5:
SQL> DECLARE
2 N NUMBER;
3 M NUMBER;
4 REV_N NUMBER:=0;
5 R NUMBER;
6 BEGIN
7 N := 12321;
8 M := N;
9 WHILE N > 0
10 LOOP
11 R := MOD( N,10);
12 REV_N := ( REV_N*10)+R;
13 N := TRUNC( N/10);
14 END LOOP;
15
16 IF M = REV_N THEN
17 DBMS_OUTPUT.PUT_LINE('Given number is palindrome.');
18 ELSE
19 DBMS_OUTPUT.PUT_LINE('Given number is not palindrome.');
20 END IF;
21 END;
22 /
Output:
Given number is palindrome.
PL/SQL procedure successfully completed.
VIC 40
PLS_6 is a stored procedure named "SMS.get_exam_result" with one formal parameter named
exam_year_in. The main task of this procedure is to generate the result of all the student in a school
for the exam year passed as actual parameter to this procedure. It takes all the student details from
student master table named "SMS.student_tab" and generate grades achieved by students in each
subject as per the marks obtained by that student that is stored in "SMS.student_marks_tab".
Table "SMS.subject_exam_code_tab" stores the exam codes for each subject code.
The main PL/SQL concept used in this procedure is CURSOR FOR Loop:
1.Cursor FOR Loop at Line 3 fetches students from "SMS.student_tab" one by one.
2.Cursor FOR Loop at Line 6 fetches exam_code and marks obtained by the student fetched by for
loop at
line 3.(Look into the Joins between the tables in SELECT statement).
3.Inside the loop, procedure "SMS.get_student_result_demo_if" is called for each subject of the
student
fetched by outermost cursor for loop. Call to this procedure stores the grade obtained and other
details such
as Pass/ Rexam of a student subject-wise.(See explanation to PLS_1 for more details).
4.Call to this procedure is coded in a block that is also having a exception handling section.
5.Main Exception handling section raises the exception occurred to the calling environment of the
procedure
"SMS.get_exam_result".
VIC 41
/*SMS.STUDENT_TAB: Table for all the students in a school*/
CREATE TABLE SMS.STUDENT_TAB
(
STUDENT_ID VARCHAR2(100 BYTE),
ADMISON_YEAR NUMBER,
STUDENT_STANDARD VARCHAR2(50 BYTE),
STUDENT_AGE NUMBER
);
/*SMS.STUDENT_SUBJECT_TAB: Table for all the subjects opted by students in a school*/
CREATE TABLE SMS.STUDENT_SUBJECT_TAB
(
STUDENT_ID VARCHAR2(100 BYTE),
STUDENT_STANDARD VARCHAR2(50 BYTE),
STUDENT_SUBJECT_CODE VARCHAR2(50 BYTE)
);
/*SMS.SUBJECT_EXAM_CODE_TAB: Table for Subject code and exam code linking for each standard in a school.*/
CREATE TABLE SMS.SUBJECT_EXAM_CODE_TAB
(
STANDARD NUMBER,
SUBJECT_CODE VARCHAR2(50 BYTE),
EXAM_YEAR NUMBER,
EXAM_CODE VARCHAR2(50 BYTE)
);
/*SMS.STUDENT_MARKS_TAB: Table for subject-wise marks obtained by all the students in a school.*/
CREATE TABLE SMS.STUDENT_MARKS_TAB
(
STUDENT_ID VARCHAR2(100 BYTE),
STUDENT_STANDARD VARCHAR2(50 BYTE),
STUDENT_SUBJECT_CODE VARCHAR2(50 BYTE),
EXAM_YEAR NUMBER,
STUDENT_MARKS NUMBER(26,6)
);
VIC 42
PLS_6: SQL> CREATE OR REPLACE PROCEDURE SMS.get_exam_result(exam_year_in NUMBER) IS
2 BEGIN
3 FOR I IN ( SELECT A.student_id, A.student_standard
4 FROM SMS.student_tab A)
5 LOOP
6 FOR J IN ( SELECT C.exam_code, D.student_marks
7 FROM SMS.student_subject_tab B, SMS.subject_exam_code_tab C,
8 SMS.student_marks_tab D
9 WHERE B.student_id = I.student_id
10 AND B.student_id = D.student_id
11 AND B.student_standard = D.student_standard
12 AND B.student_subject_code = D.student_subject_code
13 AND D.student_standard = C.standard
14 AND D.student_subject_code = C.subject_code
15 AND D.exam_year = C.exam_year)
16 LOOP
17 BEGIN
18 SMS.get_student_result_demo_if(I.student_id, I.student_standard, exam_year_in,
19 J.exam_code, J.student_marks);
20 EXCEPTION
21 WHEN OTHERS
22 THEN RAISE_APPLICATION_ERROR(-20001, SQLERRM, TRUE);
23 END;
24 END LOOP;
25 END LOOP;
26 EXCEPTION
27 WHEN OTHERS
28 THEN NULL;
29 END;
30 /
Procedure created.
VIC 43
Try to Generate Result of all the student in a school for Exam year 2018 with PLS_6.Run below
script first the insert required data for students, subjects details and marks obtained by students in
subjects for year 2018:
TRUNCATE TABLE SMS.STUDENT_REXAM_TAB;
TRUNCATE TABLE SMS.STUDENT_PASS_TAB;
TRUNCATE TABLE SMS.STUDENT_TAB;
TRUNCATE TABLE SMS.STUDENT_SUBJECT_TAB;
TRUNCATE TABLE SMS.SUBJECT_EXAM_CODE_TAB;
TRUNCATE TABLE SMS.STUDENT_MARKS_TAB;
INSERT INTO SMS.STUDENT_TAB (STUDENT_ID, ADMISON_YEAR, STUDENT_STANDARD, STUDENT_AGE)
VALUES('S_01', 2017, '12', 17);
INSERT INTO SMS.STUDENT_TAB (STUDENT_ID, ADMISON_YEAR, STUDENT_STANDARD, STUDENT_AGE)
VALUES('S_02', 2014, '12', 17);
INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE)
VALUES('S_01', '12', 'IT_01');
INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE)
VALUES('S_01', '12', 'MT_01');
INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE)
VALUES('S_02', '12', 'MT_01');
INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE)
VALUES('S_02', '12', 'IT_01');
INSERT INTO SMS.SUBJECT_EXAM_CODE_TAB(STANDARD, SUBJECT_CODE, EXAM_YEAR, EXAM_CODE)
VALUES(12, 'IT_01', 2018, 'EX_IT_01');
INSERT INTO SMS.SUBJECT_EXAM_CODE_TAB(STANDARD, SUBJECT_CODE, EXAM_YEAR, EXAM_CODE)
VALUES(12, 'MT_01', 2018, 'EX_MT_01');
INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE,
EXAM_YEAR, STUDENT_MARKS)
VALUES('S_01', '12', 'IT_01', 2018, 96);
INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE,
EXAM_YEAR, STUDENT_MARKS)
VALUES('S_01', '12', 'MT_01', 2018, 92);
INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE,
EXAM_YEAR, STUDENT_MARKS)
VALUES('S_02', '12', 'IT_01', 2018, 83);
INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE,
EXAM_YEAR, STUDENT_MARKS) VIC 44
PLS_7 is an anonymous block explaining concepts of Exception Handling in PL/SQL programming.
1. PL/SQL block compares the values of max_val and chk_val and raise an exception named
"invalid_val_exception"
whenever value chk_val is greater than max_val.
2. "invalid_val_exception" is a user-defined exception declared in Declaration section of main block(Line 4)
and associated with error number -3434 using pragma name EXCEPTION_INIT(Line 5).
3. Nested Block at starting at Line 10 has another nested block starting at Line 10.Inside this nested block IF
condition
compares chk_val with max_val and raise exception named if condition results to TRUE.
4. The exception raised is handled by exception handler of the very same Nested block which re-raises exception
using
raise_application_error with error code -20101 and error message 'Invalid check value.'.
5. The Outer Nested block also has an Exception Handling section that also uses raise_application_error with
error code –
20201 and error message SQLERRM that gives the same error message as that of -20101.
6. The Main Block also has an Exception Handling section that also does the same task and thus the exception is
re-raised to
the calling environment. Thus, with current PL/SQL code, we get the error message as shown in the Output ofVIC 45
 This process of raising an exception by the inner(nested) blocks that is being re-raised by outer
block to the
main blocks is called Propagation of exceptions.
STUDEN
T_ID
STUDENT_
STANDARD
EXAM_
YEAR
EXAM_
CODE
MARKS_
OBTAINE
D
IS_
GRAC
E
GRACE_
VAL
GRADE_
OBTAINED
S_02 12 2018 EX_MT_
01
25 Y 3 D-
STUDEN
T_ID
STUDENT_
STANDARD
EXAM_
YEAR
EXAM_
CODE
MARKS_
OBTAINED
IS_
GRAC
E
GRADE_
OBTAINED
IS_
GOLD_
MEDAL
IS_
SILVER_
MEDAL
IS_
BRONZE_
MEDAL
S_01 12 2018 EX_IT_01 96 N A+ Y N N
S_01 12 2018 EX_MT_0
1
92 N A+ N Y N
S_02 12 2018 EX_IT_01 83 N A N N N
PLS_7: SQL> DECLARE
2 max_val INTEGER;
3 chk_val INTEGER;
4 invalid_val_exception EXCEPTION;
5 PRAGMA EXCEPTION_INIT( invalid_val_exception, -3434);
6 BEGIN
7 max_val := 1000;
8 chk_val := 1001;
9 BEGIN
10 BEGIN
11 IF chk_val > max_val THEN
12 RAISE invalid_val_exception;
13 END IF;
14 EXCEPTION
15 WHEN invalid_val_exception
16 THEN RAISE_APPLICATION_ERROR(-20101, 'Invalid check value.');
17 END;
18 EXCEPTION
19 WHEN OTHERS
20 THEN RAISE_APPLICATION_ERROR(-20201, SQLERRM, TRUE);
21 END;
22 EXCEPTION
23 WHEN OTHERS
24 THEN RAISE_APPLICATION_ERROR(-20301, SQLERRM, TRUE); ----Use with TRUE/FALSE in reverse sequence
25 END;
26 /
Output: DECLARE
*
ERROR at line 1:
ORA-20301: ORA-20201: ORA-20101: Invalid check value.
ORA-20101: Invalid check value.
ORA-06512: at line 24
ORA-20201: ORA-20101: Invalid check value.
ORA-20101: Invalid check value.
VIC 46
Error Codes
 This slide describes certain errors that you may encounter while creating programs
related to the topics covered in this chapter.
 Purpose of this slide is to provide assistance while practicing PL/SQL.
 Following are the error codes, error messages, Cause and Actions for some
ORA/PLS errors:
 ORA-06592: CASE not found while executing CASE statement
Cause: A CASE statement must either list all possible cases or have an else clause.
Action: Add all missing cases or an else clause.
 PLS-00109: unknown exception name "string" in PRAGMA EXCEPTION_INIT
Cause: No declaration for the exception name referenced in an EXCEPTION_INIT
pragma was found within the scope of the pragma.
Action: Make sure the pragma follows the exception declaration and is within the same
scope.
 PLS-00484: redundant exceptions "string" and "string" must appear in same exception
handler
Cause: Using the EXCEPTION_INIT pragma, different exceptions were initialized
to the same Oracle error number; then, they were referenced in different
exception
handlers within the same exception-handling part. Such references conflict.VIC 47
 PLS-00700: PRAGMA EXCEPTION_INIT of string must follow declaration of its exception in
the same declarative part.
Cause: An EXCEPTION_INIT pragma was not declared in the same block as its exception.
They must be declared in the proper order in the same block, with the pragma declaration
following the exception declaration.
Action: Place the EXCEPTION_INIT pragma directly after the exception declaration referenced
by the
pragma.
 PLS-00702: second argument to PRAGMA EXCEPTION_INIT must be a numeric literal.
Cause: The second argument passed to an EXCEPTION_INIT pragma was something other
than a numeric literal (a variable, for example). The second argument must be a
numeric literal in the range -9999 .. -1 (excluding -100) for Oracle errors or in the
range -20000 .. -20999 for user-defined errors.
Action: Replace the second argument with a valid error number.
 ORA-32612: invalid use of FOR loop
Cause: The MODEL FOR loop was used where it is not allowed. FOR loops are not allowed in
complex dimensional predicates, on the right hand side of rules, or in the until
condition.
Action: Check the SQL statement and rewrite if necessary.
VIC 48
A bit of an Advice
 Conditional programming contains lot of branching and unconditional exits/return from any
loop or program unit. Indentation and labeling of block can be used to structure the code
making the program self explanatory. Comments can also be used to achieve this purpose.
 In programs containing loops like WHILE/NUMERIC FOR Loops, looping boundaries must
be decided properly based on the number of iteration required to avoid infinite loops.
 For User defined exceptions, error codes and error messages must be associated with
defined errors in a way that they can give proper detail of the source of exception, cause of
that exception and must be uniform throughout the application. User-defined package can
be used for this purpose. It is highly recommended that pragma EXCEPTION_INIT be used
in a predefined package giving names to all the anonymous system exceptions and
application-specific errors in a way that these can be used throughout the application with
any need to define them separately in individual progrma units that can cause ambiguity as
one error code can refer multiple error messages if not defined carefully which is itself a
tough task.
 Handle exception carefully in case of program structure with nested blocks deciding carefully
which category of exceptions are to be handled in current block and which are to be
propagated to outer block so that complete details of severe exceptions can be obtained.
 In Cursor FOR Loops, queries must be written with proper Join condition returning the result
set that does not contain any ambiguous data and multiple rows causing the loop to get
iterated un-necessarily as this type of loop has no user-defined boundaries.
VIC 49
Thanks for reading. We hope you have got some of what you were looking for in PL/SQL
programming fundamentals. Next chapters will be covering PL/SQL in depth explaining
further the PL/SQL program data and details of how SQL is used in PL/SQL with suitable
examples expanding our SCHOOL MANAGEMENT SYSTEM(SMS) further. So stay with
us.
THAT’S ALL FOLKS!

More Related Content

What's hot

PL/SQL & SQL CODING GUIDELINES – Part 7
PL/SQL & SQL CODING GUIDELINES – Part 7PL/SQL & SQL CODING GUIDELINES – Part 7
PL/SQL & SQL CODING GUIDELINES – Part 7Larry Nung
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C ProgrammingKamal Acharya
 
PLSQL Coding Guidelines - Part 6
PLSQL Coding Guidelines - Part 6PLSQL Coding Guidelines - Part 6
PLSQL Coding Guidelines - Part 6Larry Nung
 
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
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in CRAJ KUMAR
 
C language control statements
C language  control statementsC language  control statements
C language control statementssuman Aggarwal
 
Selection statements
Selection statementsSelection statements
Selection statementsHarsh Dabas
 
C programming decision making
C programming decision makingC programming decision making
C programming decision makingSENA
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in cvampugani
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Cse lecture-6-c control statement
Cse lecture-6-c control statementCse lecture-6-c control statement
Cse lecture-6-c control statementFarshidKhan
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlENGWAU TONNY
 
Exception
ExceptionException
Exceptionwork
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programmingPriyansh Thakar
 
Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 

What's hot (20)

PL/SQL & SQL CODING GUIDELINES – Part 7
PL/SQL & SQL CODING GUIDELINES – Part 7PL/SQL & SQL CODING GUIDELINES – Part 7
PL/SQL & SQL CODING GUIDELINES – Part 7
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
PLSQL Coding Guidelines - Part 6
PLSQL Coding Guidelines - Part 6PLSQL Coding Guidelines - Part 6
PLSQL Coding Guidelines - Part 6
 
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
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
C language control statements
C language  control statementsC language  control statements
C language control statements
 
Selection statements
Selection statementsSelection statements
Selection statements
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
C# conditional branching statement
C# conditional branching statementC# conditional branching statement
C# conditional branching statement
 
Control Statement programming
Control Statement programmingControl Statement programming
Control Statement programming
 
PL/SQL Introduction
PL/SQL IntroductionPL/SQL Introduction
PL/SQL Introduction
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Flow of control
Flow of controlFlow of control
Flow of control
 
Cse lecture-6-c control statement
Cse lecture-6-c control statementCse lecture-6-c control statement
Cse lecture-6-c control statement
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
 
Exception
ExceptionException
Exception
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
Control Structures
Control StructuresControl Structures
Control Structures
 

Similar to Pl sql chapter 2

Chapter05-Control Structures.pptx
Chapter05-Control Structures.pptxChapter05-Control Structures.pptx
Chapter05-Control Structures.pptxAdrianVANTOPINA
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsPrabu U
 
Decision making and looping - c programming by YEASIN NEWAJ
Decision making and looping -  c programming by YEASIN NEWAJDecision making and looping -  c programming by YEASIN NEWAJ
Decision making and looping - c programming by YEASIN NEWAJYeasinNewaj
 
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
 
BSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETBSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETUjwala Junghare
 
CONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VBCONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VBclassall
 
Control statements
Control statementsControl statements
Control statementsCutyChhaya
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrolsteach4uin
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition StructureShahzu2
 
C++ control structure
C++ control structureC++ control structure
C++ control structurebluejayjunior
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdfKirubelWondwoson1
 
03loop conditional statements
03loop conditional statements03loop conditional statements
03loop conditional statementsAbdul Samad
 
2nd year computer science chapter 12 notes
2nd year computer science chapter 12 notes2nd year computer science chapter 12 notes
2nd year computer science chapter 12 notesmuhammadFaheem656405
 

Similar to Pl sql chapter 2 (20)

Chapter05-Control Structures.pptx
Chapter05-Control Structures.pptxChapter05-Control Structures.pptx
Chapter05-Control Structures.pptx
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, Strings
 
Control structures
Control structuresControl structures
Control structures
 
Decision making and looping - c programming by YEASIN NEWAJ
Decision making and looping -  c programming by YEASIN NEWAJDecision making and looping -  c programming by YEASIN NEWAJ
Decision making and looping - c programming by YEASIN NEWAJ
 
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
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
BSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETBSc. III Unit iii VB.NET
BSc. III Unit iii VB.NET
 
CONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VBCONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VB
 
Control statements
Control statementsControl statements
Control statements
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrols
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition Structure
 
Final requirement
Final requirementFinal requirement
Final requirement
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdf
 
03loop conditional statements
03loop conditional statements03loop conditional statements
03loop conditional statements
 
2nd year computer science chapter 12 notes
2nd year computer science chapter 12 notes2nd year computer science chapter 12 notes
2nd year computer science chapter 12 notes
 

Recently uploaded

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 

Recently uploaded (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 

Pl sql chapter 2

  • 1. VISTA Powered by Institute of Computer Education
  • 2. ORACLE PL / SQL CHAPTER 2: PL / SQL PROGRAM STRUCTURE by Prabhat Kumar
  • 3. Contents  Conditional and Sequential Control: - If Statements. - CASE Statement and Expression. - GOTO Statement. - NULL Statement.  Iterative Processing: - The Simple Loop. - The WHILE Loop. - The Numeric FOR Loop. - The Cursor FOR Loop. - The CONTINUE Statement.  Exception Handling: - Define and Raise Exceptions. - Handling Exceptions. - Built- in Error Functions  Practitioners Guide.  Error Codes.  A bit of an Advice. VIC 3
  • 4. Conditional and Sequential Control These can be divided into following categories:  IF Statements: - implement conditional branching logic in a program. - Business Logics such as below can be implemented with these: - If the price is greater than $1000 than offer discount 10% else if price > $2000 then 15% discount else 20%.Lets give it a name, say BL_1. - The IF Statement can be combined in three ways as: - The IF-THEN Combination: - implements if condition in a program. - General Format: IF condition THEN *** sequence of executable statements *** END IF; VIC 4
  • 5. - The IF Statement can be combined in three ways as: - The IF-THEN Combination: - implements if condition in a program. - General Format: IF condition THEN *** sequence of executable statements *** END IF; - the condition can be a constant, Boolean variable or an expression evaluating to TRUE/FALSE/NULL. - if condition is TRUE, the statements found between THEN keyword & matching END IF statement are executed. - if condition is FALSE/NULL, these statements are not executed at all. - Below code is a part of PL/SQL implementing conditional logic based on If Statement: IF price > 1000 THEN price := price - (( price * 10 ) / 100) ;-------10 % discount END IF; VIC 5
  • 6. - The IF-THEN-ELSE Combination: - implements either/or condition in a program. - General Format: IF condition THEN *** sequence of executable statements when TRUE *** ELSE *** sequence of executable statements when FALSE/NULL *** END IF; - condition can be a constant, Boolean variable or an expression evaluating to TRUE/FALSE/NULL. - IF condition is TRUE, the statements found between THEN keyword and ELSE keyword are executed. - IF condition is FALSE/NULL, the statements found between ELSE keyword and matching END IF statement are executed. - Below code is a part of PL/SQL implementing conditional logic based on IF-THEN-ELSE Statement: IF price > 1000 THEN price := price - (( price * 10 ) / 100) ;-------10 % discount ELSE price := price - (( price * 20 ) / 100) ;-------20 % discount END IF; VIC 6
  • 7. - The IF-THEN-ELSIF Combination: - implements logic having many alternatives. - ELSIF is used to handle mutually exclusive alternatives. - General Format: IF condition-1 THEN statements-1 ELSIF condition-N THEN statements-N ELSE else_statements END IF; - condition can be a constant, Boolean variable or an expression evaluating to TRUE/FALSE/NULL. - if condition-1 is TRUE, the statements found between THEN keyword and first ELSIF keyword are executed. - if condition-1 is FALSE/NULL, then statements-N with condition-N resulting to TRUE will be executed. - if none of the condition results to TRUE, then, statements between ELSE keyword and matching VIC 7
  • 8. VIC 8 - Nested IF Statements: - IF statement can be nested within any other IF statement. - Several Layered Nested IF Statements looks like: IF condition1 THEN IF condition2 THEN statements2 ELSE IF condition3 THEN statements3 ELSIF condition4 THEN statements4 END IF; END IF; END IF;
  • 9. VIC 9  CASE Statement and Expression: - allows selection of one sequence of statements out of many possible sequences for execution. - types of CASE Statements: 1.Simple CASE statement: - provides binding of one or more sequence of statements with a value. - sequence of statements having value equal to the result of the expression are executed. - General Format: CASE expression WHEN result1 THEN statements1 WHEN result2 THEN statements2 ELSE statements_else END CASE; - expression is evaluated and result is compared with the values in WHEN clause( result1,result2...). - WHEN clauses are executed from top to bottom, hence, statements associated with first expression resulting to TRUE are executed.
  • 10. - otherwise, statements_else is executed, written in ELSE condition(an optional part). - Example for Simple CASE statement is shown below: CASE discount WHEN 10 THEN price := price - (( price * 10 ) / 100) ;-------10 % discount WHEN 20 THEN price := price - (( price * 20 ) / 100) ;-------20 % discount ELSE price := price - (( price * 30 ) / 100) ;-------30 % discount END CASE; - this code implements discount logic as explained in IF Statements using CASE Statements. VIC 10
  • 11. 2.Searched CASE Statements: - evaluates Boolean expressions in the list. - executes a sequence of statements associated with the expression resulting to TRUE. - General Format: CASE WHEN expression1 THEN statements1 WHEN expression2 THEN statements2 ELSE statements_else END CASE; - if expression1 is TRUE then, statements1 is executed else if expression2 is TRUE then statements2 is executed. - in case no expression results to TRUE then, statements_else is executed. - Example of Searched CASE Statement is shown below: CASE WHEN discount = 10 THEN price := price - (( price * 10 ) / 100) ;-------10 % discount WHEN discount = 20 THEN price := price - (( price * 20 ) / 100) ;-------20 % discount ELSE price := price - (( price * 30 ) / 100) ;-------30 % discount END CASE; VIC 11
  • 12. - CASE Expressions: - chooses an expression (not statements as done by CASE Statements) to be evaluated based on input scalar value. - General Format: 1.Simple CASE Expressions: Simple_Case_Expression := CASE expression WHEN result1 THEN result_expression1 WHEN result2 THEN result_expression2 ... ELSE result_expression_else END; 2.Searched CASE Expressions: Searched_Case_Expression := CASE WHEN expression1 THEN result_expression1 WHEN expression2 THEN result_expression2 ... ELSE result_expression_else END; VIC 12
  • 13. Example of CASE Expressions DECLARE price NUMBER(26, 2); discount INTEGER:=10; final_amount NUMBER(26,2); BEGIN price := 1000; discount := 10; final_amount := price - CASE WHEN discount > 0 AND discount <= 10 THEN ( price * 10 ) / 100 WHEN discount > 10 AND discount <= 20 THEN ( price * 20 ) / 100 ELSE ( price * 30 ) / 100 END; dbms_output.put_line ('Final Price is '||final_amount||' with '|| discount||' % '||'discount Offered.'); END; 13 VIC DECLARE price NUMBER(26, 2); discount INTEGER:=10; final_amount NUMBER(26,2); BEGIN price := 1000; discount := 10; final_amount := price - CASE discount > 0 AND discount <= 10 WHEN TRUE THEN ( price * 10 ) / 100 WHEN FALSE THEN ( price * 20 ) / 100 ELSE ( price * 30 ) / 100 END; dbms_output.put_line ('Final Price is '||final_amount||' with '|| NVL(discount, 30)||' % '||'discount Offered.'); END;
  • 14.  The GOTO Statements: - allows unconditional branching to another executable statement in same execution section of a PL/SQL block. - General Format: GOTO label_name; - label_name is the name of a label identifying the target statement, defined as <<label_name>>. - once PL/SQL encounters GOTO, execution control goes to first executable statement following the label. - there must be at least one executable statement following the label. - target statement must be in the same scope as the GOTO statement. - target statement and the GOTO statement must be in the same scope.  The NULL Statements: - tells PL/SQL to do nothing. - General Format: NULL; - Reserved keyword NULL followed by;(semicolon) - it improves readability of code. - helps in managing codes having the GOTO Statements. VIC 14
  • 15. VIC 15 Iterative Processing - iterative processing in programming implies to executing same set of statement repeatedly. - iterative control structures commonly known as loops helps in this type of programming. - Business Logics such as below can be implemented with these: - add 100 to a given value until that values becomes greater than 1000.Lets give it a name, say BL_2. - PL/SQL provides four major categories of looping structures , explained ahead: 1. The Simple Loop: - starts with keyword LOOP and ends with END LOOP keyword. - set of statements coded after keyword LOOP and before keyword END LOOP are executed iteratively. - termination of iteration can be achieved using EXIT(for unconditional exit) or EXIT WHEN(for conditional exit). - Exit condition can be placed anywhere inside the Loop, if the exit condition is last statement of loop, then at least one iteration will be done, provided no exception occurred. - General Syntax: LOOP exit_condition; executable_statements; END LOOP; In computer software, Business logic or domain logic is the part of the program unit that encodes the real- world business rules that determines how data can be created, stored and changed.
  • 16. - logic BL_2 can be implemented using Simple Loop as(loop will iterate until total_value <1000): LOOP EXIT WHEN total_value > 1000; total_value := total_value + 100; END LOOP; 2. The WHILE Loop: - its a conditional loop that iterates as long as the defined Boolean condition results to TRUE. - General Syntax: WHILE condition LOOP executable_statements; END LOOP; - condition can be a Boolean variable or expression evaluating to TRUE/FALSE/NULL. - executable_statements continues to be executed provided that condition that is being checked at start of each iteration evaluates to TRUE. - logic BL_2 can be implemented using WHILE Loop as: WHILE (total_value < 1000) LOOP total_value := total_value + 100; END LOOP; VIC 16
  • 17. 3. The Numeric FOR Loop: - its a counted loop in which numbers of iterations is indentified at its start. - Business Logics such as below can be implemented with these: increase total_value by 100 fixed 10 number of times. Lets give it a name, say BL_3. - General Syntax: FOR index IN [REVERSE] lowest number..highest number LOOP executable statements END LOOP; - logic BL_2 can be implemented using Numeric FOR Loop as: FOR I IN 1..10 LOOP total_value := total_value + 100; END LOOP; - loop will iterate 10 times, adding 100 to total_value at each iteration. VIC 17  Do not declare loop index as PL/SQL declares it automatically with datatype INTEGER.  Range scheme are evaluated once when the loop start and cannot be changed during execution.  REVERSE keyword is used to decrement the loop from upper bound to the lower bound. But still, in range specification, lowest number is less than the highest number.
  • 18. 4. The Cursor FOR Loop: - this type of loop is associated either with explicit cursor or a SELECT statement within loop boundaries. - provides integration of procedural constructs with SQL.( Standard Query Language). Business Logics such as below can be implemented with these: give 10 % discount to all the products available in store. Lets give it a name, say BL_4. - General Syntax: FOR record IN { explicit_cursor_name | (SELECT statement) } LOOP executable statements END LOOP; - logic BL_4 can be implemented using Cursor FOR Loop as: FOR I IN ( SELECT product_id, product_unicode FROM product_tab ) LOOP UPDATE product_price_tab A SET A.product_price = A.product_price - ((A.product_price * 10) / 100) WHERE A.product_id = I.product_id AND A.product_unicode = I.product_unicode; END LOOP; - loop will iterate for all products in product_tab table - each iteration will update price in product_price_tab for the product picked by PL/SQL in that iteration. VIC 18
  • 19. 5. The CONTINUE Statement: - provides immediate escape from current iteration of loop & continue on to next iteration of that loop. - it can be conditional and non- conditional. - CONTINUE keyword is used for non-conditional exit of current iteration and CONTINUE WHEN is for conditional one. - General Syntax: Un-conditional: LOOP EXIT WHEN condition; executable statements CONTINUE; executable statements END LOOP; VIC 19  Table product_price_tab is given Alias A that is used further in referencing table columns. The columns or variables when referenced by the table alias, the package/procedure/ nested block label name is known to be qualified.  For more on SQL, study CHAPTERS on VISTA ORACLE SQL.
  • 20. Conditional: LOOP EXIT WHEN condition; executable statements CONTINUE WHEN continue_condition; executable statements END LOOP; Below example describes a NUMERIC FOR loop, in which, iteration is skipped if the current value of index variable is an even number: BEGIN FOR I IN 1..50 LOOP CONTINUE WHEN MOD( I,2) = 0; DBMS_OUTPUT.PUT_LINE(‘Index Value is ’|| TO_CHAR(I)); END LOOP; END; / VIC 20  Try using un-conditional CONTINUE statement with IF conditional statement to get the same results.
  • 21. VIC 21 Exception Handling - errors of any kind are treated as exceptions. - two general exceptions types: - System exception: - defined by Oracle and raised by PL/SQL runtime engine whenever error condition is detected. - these have names, codes and descriptions. Examples are: TOO_MANY_ROWS, etc. - Programmer-defined exception: - these are application specific exceptions defined by the programmers. - EXCEPTION_INIT pragma can be used to associate exception names with specific Oracle errors. - Concept of Exception Handling can be explained in three parts: - Defining Exceptions: - it involves two steps: - naming exception by declaring it in declaration section of PL/SQL program. - General Syntax: exception_name EXCEPTION; - associating Exception Names with Error Codes: - Oracle has associated names to some of the exception like NO_DATA_FOUND, that can be handled by name itself. - this association can also be made by programmer using EXCEPTION_INIT pragma.
  • 22. Table 1. Predefined Exceptions Name Oracle Error SQLCOD E Raised When TOO_MANY_ROWS ORA-01403 +100 execution of SELECET INTO statement(implicit cursor) returns more than one row. NO_DATA_FOUND ORA-01422 -1422 execution of SELECET INTO statement(implicit cursor) returns no rows or when read command is executed past end-of-file with UTL_FILE package or when uninitialized row in a local associative array is reference VALUE_ERROR ORA-06502 -6502 conversion, truncation, or invalid constraining of numeric and character data error. INVALID_NUMBER exception is raised when same error occurs within PL/SQL Block. ZERO_DIVIDE ORA-01476 -1476 program tried to divide a value by zero. INVALID_NUMBER ORA-01722 -1722 SQL statement is executed that cannot convert a character string successfully to a number. INVALID_CURSOR ORA-01001 -1001 cursor not in existence is referenced( usually raise while FETCH or CLOSE without opening cursor). CURSOR_ALREADY_O PEN ORA-6511 –6511 attempt is made to open a cursor that is already opened. DUP_VAL_ON_INDEX ORA-00001 -1 INSERT/UPDATE attempts to store column/columns in a row that are restricted by unique constraint. LOGIN_DENIED ORA-01017 -1017 program tries to log into the database with an invalid username/password combination. PROGRAM_ERROR ORA-06501 -6501 PL/SQL encounters an internal problem. The message text is generally meant to Contact Oracle Support. VIC 22
  • 23. - Raising Exceptions: - There are three different ways that exception can be raised in an application: a. database itself raises an exception whenever it detects an error: - all the executable statements will be skipped and control goes to Exception section where that exception is handled. In case no exception section is there program execution terminates. b. user can raise an exception using RAISE statement: - this statement is used to raise named exceptions ( system or programmer defined). - General Syntax: RAISE exception_name; or RAISE package_name.exception_name; or RAISE; c. RAISE_APPLICATION_ERROR procedure: - used to raise application-specific errors in an application. - error message can also be associated with an error number using this procedure. - General Syntax: RAISE_APPLICATION_ERROR (num binary_integer, msg varchar2,VIC 23
  • 24. where, num is the error number with valid value between -20,999 and -20,000. msg is the error message with maximum of 2,000 characters. keeperrorstack indicates whether you want to add the error to any error already on the stack (TRUE) or replace the existing errors (FALSE). -Handling Exceptions: - to handle exceptions raised by names in a programme, a PL/SQL block must have an Exception Handling Block with one or more exception handlers: - General Syntax for an exception handler is: WHEN exception_name [ OR exception_name1 ... ] THEN executable statements - exception handlers handle exceptions by name only. Exception got handled when its name matches name of the exception in WHEN clause of exception handler. - When a match is found, statements written in that WHEN clause are executed and then control goes out of the current PL/SQL block. - When no match is found, WHEN OTHERS exception handler is executed(if present). VIC 24  Use WHEN OTHERS to handle other unhandled exceptions.  Use SQLCODE and DBMS_UTILITY.FORMAT_ERROR_STACK to get information about the error occurred.
  • 25. VIC 25 - Built- in Error Functions: - Oracle provide some very useful built-in functions to identify, analyze and handle errors in PL/SQL program , like: a.SQLCODE: - it returns the error code of the most recent exception raised in a block. - returns 0 in case of no error or when called from outside an exception handler. b.SQLERRM: - it returns error message for a particular error code with maximum length of 512 characters. - in case no error code is passed in call to sqlerrm, error message associated with the value of SQLCODE is returned. - if SQLCODE is 0 , SQLERRM return "ORA-0000: normal, successful completion". c.DBMS_UTILITY.FORMAT_ERROR_STACK: - it works like SQLERRM except that maximum length string returned by this function is of 1899 characters. - it also does not take error code as argument so it can only be called inside an exception handler. d.DBMS_UTILITY.FORMAT_ERROR_BACKTRACE: - it returns a formatted string that contains stack of programs and line numbers leading back to the line where the error raised first. e.DBMS_UTILITY.FORMAT_CALL_STACK: - it returns formatted string displaying execution call stack inside a PL/SQL application.
  • 26. Practitioners Guide Slides ahead contains PL/SQL programs for complete understanding of theories just explained.Programs are designed in a way to demonstrate the important and critical aspects of PL/SQL programming in a unified manner.
  • 27. VIC 27 In this, we will be making understanding of PL/SQL concepts explained in this chapter by some application specific examples. Schools have certain processes that are followed to manage things and one of them are creating results for students having exams. Results are derived based on marks obtained by students in different subjects and based on some pre-defined criteria of schools, grades are given to students based on their marks obtained. Here, we will be developing a functionality(PL/SQL program) that will check for possible results of the students based on the marks obtained by those student. Result generating PL/SQL program of our SCHOOL MANGEMENT SYSTEM(SMS) has following decision making conditions:  Code will take student id, its current standard, exam year, exam code basically subject code and marks obtained by that student in that subject.  If marks obtained is less than 30, then grace of 3 marks will be given.  If marks is greater than 85, grade obtained is ‘A+’, between 70 and 84 grade ‘A’ and so on. If marks is less than 30, grade obtained is ‘D-’. If calculated grade for any student is ‘D-’ even after applying grace marks, then
  • 28.  Below are the Oracle tables created for storing results of students appeared in the exam: 1. student_rexam_tab : This table will store details of students that are calculated to be eligible for Rexam by SMS: /* student_rexam_tab */ CREATE TABLE SMS.student_rexam_tab (student_id VARCHAR2(50), student_standard VARCHAR2(20), exam_year INTEGER, exam_code VARCHAR2(50), marks_obtained NUMBER(26,6), is_grace CHAR(1), grace_val INTEGER, grade_obtained VARCHAR2(50)); 2. student_pass_tab : This table will store details of students that are calculated to be passed by SMS: /* student_pass_tab */ CREATE TABLE SMS.student_pass_tab (student_id VARCHAR2(50), student_standard VARCHAR2(20), exam_year INTEGER, exam_code VARCHAR2(50), marks_obtained NUMBER(26,6), is_grace CHAR(1) DEFAULT 'N', grade_obtained VARCHAR2(50), is_gold_medal CHAR(1), is_silver_medal CHAR(1), is_bronze_medal CHAR(1)); VIC 28 SMS is our SCHOOL MANAGEMENT SYSTEM.
  • 29. VIC 29 PLS_1: CREATE OR REPLACE PROCEDURE SMS.get_student_result_demo_if ( student_id_in VARCHAR2, student_standard_in VARCHAR2, exam_year_in INTEGER, exam_code_in VARCHAR2, marks_obtained_in NUMBER) IS total_marks NUMBER(3):= 100; grace_val CONSTANT SIMPLE_INTEGER:= 3; student_grade VARCHAR2(5); grace_applied_chk CHAR VARYING(1):= 'N'; student_pass_chk CHAR(1):='N'; gold_medal_chk CHAR(1):='N'; silver_medal_chk CHAR(1):='N'; bronze_medal_chk CHAR(1):='N'; marks_obtained NUMBER(26,3):=marks_obtained_in; BEGIN IF marks_obtained < 30 THEN marks_obtained := marks_obtained + grace_val; /*Grace of three marks is given in case marks is less than 30*/ grace_applied_chk := 'Y'; END IF; /* Obtaining grade for obtained marks after applying Grace. */ IF marks_obtained >= 85 THEN student_grade := 'A+'; ELSIF marks_obtained >= 70 AND marks_obtained < 85 THEN student_grade := 'A'; ELSIF marks_obtained >= 60 AND marks_obtained < 70 THEN student_grade := 'B'; ELSIF marks_obtained >= 45 AND marks_obtained < 60 THEN student_grade := 'C‘; /*****to be continued on next slide*****/
  • 30. ELSIF marks_obtained >= 30 AND marks_obtained < 45 THEN student_grade := 'D'; ELSE student_grade := 'D-'; END IF; /* Managing Records for re-examination of Students not able to pass exam || even after grace being applied. */ IF grace_applied_chk = 'Y' AND student_grade = 'D-' THEN INSERT INTO SMS.student_rexam_tab(student_id, student_standard, exam_year, exam_code, marks_obtained, is_grace, grace_val, grade_obtained) VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in, marks_obtained_in, grace_applied_chk, grace_val, student_grade); RETURN; ELSE student_pass_chk := 'Y'; END IF; /* Categorizing Students for Gold/ Silver/ Bronze Medal ||based on their actual marks.*/ IF student_pass_chk = 'Y' AND student_grade = 'A+' THEN IF marks_obtained >= 95 THEN gold_medal_chk := 'Y'; ELSE IF marks_obtained >= 90 AND marks_obtained < 95 THEN silver_medal_chk := 'Y'; ELSE bronze_medal_chk := 'Y'; END IF; END IF; END IF; VIC 30
  • 31. /*Managing Records of Students applicable for Next Standard.*/ INSERT INTO SMS.student_pass_tab(student_id, student_standard, exam_year, exam_code, marks_obtained, grade_obtained, is_grace, is_gold_medal, is_silver_medal, is_bronze_medal) VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in, marks_obtained_in, student_grade, grace_applied_chk, gold_medal_chk, silver_medal_chk, bronze_medal_chk); END; / Above code PLS_1 named “SMS.get_student_result_demo_if” is a procedure that takes student details , subject and marks obtained in that subject and produces the result based of defined logic written inside the procedure as given by the School management to generate results of the students. This procedure is based on conditional IF statements and its variances as described in this chapter earlier. Most of the code is written with comment describing the logic behind that code. Firstly, it is checked whether to apply grace or not, after that Grade is determined based on the obtained marks(plus grace marks, if applicable).After determining grade, it is checked whether the student is passed or need to have re-exam. For students eligible for Rexam, details are inserted in student_rexam_tab table. If student is passed, it is checked whether that student is applicable for Gold/Silver/Bronze medal. After, determining these details, data of students passing the exam is inserted in student_pass_tab. The very same functionality can be achieved through CASE statements and CASE expressions. PL/SQL code PLS_2 named “SMS.get_student_result_demo_case” is coded to get the same output as above but using CASE statements and expressions. Notice use of CASE expressions, GOTO statements, NULL statements and Nested CASE statements (comments written against each one). VIC 31
  • 32. PLS_2: CREATE OR REPLACE PROCEDURE SMS.get_student_result_demo_case ( student_id_in VARCHAR2, student_standard_in VARCHAR2, exam_year_in INTEGER, exam_code_in VARCHAR2, marks_obtained_in NUMBER) IS total_marks NUMBER(3):= 100; grace_val CONSTANT SIMPLE_INTEGER:= 3; student_grade VARCHAR2(5); grace_applied_chk CHAR VARYING(1):= 'N'; student_pass_chk CHAR(1):='N'; medal_applicable BOOLEAN:=FALSE; gold_medal_chk CHAR(1):='N'; silver_medal_chk CHAR(1):='N'; bronze_medal_chk CHAR(1):='N'; marks_obtained NUMBER(26,3):=marks_obtained_in; BEGIN /*Grace of three marks is given in case marks is less than 30*/ CASE marks_obtained < 30 WHEN TRUE THEN marks_obtained := marks_obtained + grace_val; grace_applied_chk := 'Y'; ELSE grace_applied_chk := 'N'; /*Need to add ELSE condition Otherwise CASE_NOT_FOUND exception will be raised || for students with marks_obtained > 30.*/ END CASE; --Simple Case Statement /*****to be continued on next slide*****/ VIC 32
  • 33. /*||Obtaining grade for obtained marks || after applying Grace. */ CASE WHEN marks_obtained >= 85 THEN student_grade := 'A+'; WHEN marks_obtained >= 70 AND marks_obtained < 85 THEN student_grade := 'A'; WHEN marks_obtained >= 60 AND marks_obtained < 70 THEN student_grade := 'B'; WHEN marks_obtained >= 45 AND marks_obtained < 60 THEN student_grade := 'C'; WHEN marks_obtained >= 30 AND marks_obtained < 45 THEN student_grade := 'D'; ELSE student_grade := 'D-'; END CASE; --Searched Case Statement /*Managing Records for re-examination of Students not able to pass exam || even after grace being applied. */ CASE WHEN (grace_applied_chk = 'Y' AND student_grade = 'D-') = TRUE THEN INSERT INTO SMS.student_rexam_tab(student_id, student_standard, exam_year, exam_code, marks_obtained, is_grace, grace_val, grade_obtained) VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in, marks_obtained_in, grace_applied_chk, grace_val, student_grade); GOTO end_of_code;------GOTO Statement. ELSE student_pass_chk := 'Y'; END CASE; /*****to be continued on next slide*****/ VIC 33
  • 34. /*Determining Applicability for Gold/ Silver/ Bronze Medal*/ medal_applicable := CASE WHEN student_pass_chk = 'Y' AND student_grade = 'A+' THEN TRUE ELSE FALSE END; -----Searched CASE Expressions -----CASE Expressions does not end with END CASE; /*Categorizing Students for Gold/ Silver/ Bronze Medal based on their actual marks. */ CASE WHEN medal_applicable THEN CASE WHEN marks_obtained >= 95 THEN gold_medal_chk := 'Y'; ELSE CASE WHEN marks_obtained >= 90 AND marks_obtained < 95 THEN silver_medal_chk := 'Y'; ELSE bronze_medal_chk := 'Y'; END CASE; END CASE; ELSE NULL;-------------NULL Statement. END CASE;----------Nested Case Statement (mix of Simple and Searched CASE statements.) /*Managing Records of Students applicable for Next Standard.*/ INSERT INTO SMS.student_pass_tab(student_id, student_standard, exam_year, exam_code, marks_obtained, grade_obtained, is_grace, is_gold_medal, is_silver_medal, is_bronze_medal) VALUES(student_id_in, student_standard_in, exam_year_in, exam_code_in, marks_obtained_in, student_grade, grace_applied_chk, gold_medal_chk, silver_medal_chk, bronze_medal_chk); <<end_of_code>> NULL; END; VIC 34
  • 35. To Test the code for various cases of student marks basically to get different result for different marks obtained by students, try executing below scripts(you can try creating your own test cases): /* Execution Script */ EXEC SMS.get_student_result_demo_if('S_01', '12', 2018, 'IT_01', 96); EXEC SMS.get_student_result_demo_if('S_02', '12', 2018, 'IT_01', 92); EXEC SMS.get_student_result_demo_if('S_03', '12', 2018, 'IT_01', 86); EXEC SMS.get_student_result_demo_if('S_04', '12', 2018, 'IT_01', 66); EXEC SMS.get_student_result_demo_if('S_05', '12', 2018, 'IT_01', 76); EXEC SMS.get_student_result_demo_if('S_06', '12', 2018, 'IT_01', 46); EXEC SMS.get_student_result_demo_if('S_07', '12', 2018, 'IT_01', 36); EXEC SMS.get_student_result_demo_if('S_08', '12', 2018, 'IT_01', 28); EXEC SMS.get_student_result_demo_if('S_09', '12', 2018, 'IT_01', 26); EXEC SMS.get_student_result_demo_if('S_10', '12', 2018, 'IT_01', 22); Same manner SMS.get_student_result_demo_case() can be executed using below scripts: /* Execution Script */ EXEC SMS.get_student_result_demo_case('S_01', '12', 2018, 'IT_01', 96); EXEC SMS.get_student_result_demo_case('S_02', '12', 2018, 'IT_01', 92); EXEC SMS.get_student_result_demo_case('S_03', '12', 2018, 'IT_01', 86); EXEC SMS.get_student_result_demo_case('S_04', '12', 2018, 'IT_01', 66); EXEC SMS.get_student_result_demo_case('S_05', '12', 2018, 'IT_01', 76); EXEC SMS.get_student_result_demo_case('S_06', '12', 2018, 'IT_01', 46); EXEC SMS.get_student_result_demo_case('S_07', '12', 2018, 'IT_01', 36); EXEC SMS.get_student_result_demo_case('S_08', '12', 2018, 'IT_01', 28); EXEC SMS.get_student_result_demo_case('S_09', '12', 2018, 'IT_01', 26); EXEC SMS.get_student_result_demo_case('S_10', '12', 2018, 'IT_01', 22); VIC 35
  • 36. PLS_3 is an Anonymous Block demonstrating WHILE Loop and Numeric FOR Loop in a PL/SQL programming. Outermost WHILE loop iterates to two times increasing value of variable T with each iteration. Inner while loops are placed to create the pattern as shown in the next slide with Numeric FOR loops printing ‘*’ to required number of times. PLS_3: SQL> DECLARE 2 O NUMBER:=10; 3 L NUMBER:=1; 4 M NUMBER; 5 P NUMBER; 6 T NUMBER:=1; 7 BEGIN 8 LOOP 9 EXIT WHEN T = 3; 10 T := T+1; 11 DBMS_OUTPUT.PUT('Pattern Number '|| to_char(T-1)); 12 DBMS_OUTPUT.NEW_LINE; 13 WHILE L < O 14 LOOP 15 M := 1; 16 WHILE M < O - L 17 LOOP 18 DBMS_OUTPUT.PUT(' '); 19 M := M + 2; 20 END LOOP; 21 22 FOR P IN 1..L 23 LOOP 24 DBMS_OUTPUT.PUT('*'); 25 END LOOP; VIC 36
  • 37. 26 27 DBMS_OUTPUT.NEW_LINE; 28 L:= L + 2; 29 END LOOP; 30 L := 7; 31 WHILE L >= 1 32 LOOP 33 M := 9; 34 WHILE M > L 35 LOOP 36 DBMS_OUTPUT.PUT(' '); 37 M := M - 2; 38 END LOOP; 39 40 FOR P IN 1..L 41 LOOP 42 DBMS_OUTPUT.PUT('*'); 43 END LOOP; 44 DBMS_OUTPUT.NEW_LINE; 45 L := L - 2; 46 END LOOP; 47 END LOOP; 48 END; 49 / VIC 37  Use of to_char() function at Line 11 is to convert calculated value of T-1( result is of number type) to character value so that it can by concatenated to prefixed string.  Use command SET SERVEROUT ON in SQLPLUS to get output on screen.  DBMS_OUTPUT.NEW_LINE is a procedure that puts an end-of-line marker.
  • 38. Pattern Number 1 * *** ***** ******* ********* ******* ***** *** * Pattern Number 2 * *** ***** ******* ********* ******* ***** *** * PL/SQL procedure successfully completed. VIC 38
  • 39. PLS_4 is an anonymous block which identifies a given number to be an Armstrong number. A number is said to be an Armstrong number if sum of its digits raised to the power n is equal to number itself, where n is total digits in number. For example : 407 is Armstrong number as 43 + 03 + 73 = 64 + 0 + 343 = 407. PLS_4: SQL> DECLARE 2 N NUMBER:=407; 3 S NUMBER:=0; 4 R NUMBER; 5 LEN_N NUMBER; 6 M NUMBER; 7 BEGIN 8 M:=N; 9 LEN_N := LENGTH(TO_CHAR(N)); 10 WHILE N>0 11 LOOP 12 R := MOD(N,10); 13 S := S+POWER( R, LEN_N); 14 N := TRUNC(N/10); 15 END LOOP; 16 17 IF M = S THEN 18 DBMS_OUTPUT.PUT_LINE('Armstrong Number.'); 19 ELSE 20 DBMS_OUTPUT.PUT_LINE('Not an Armstrong Number.'); 21 END IF; 22 END; 23 / Output: Armstrong Number. PL/SQL procedure successfully completed. VIC 39
  • 40. PLS_5 is an anonymous block which identifies a given number to be a palindrome number. A number is called palindrome number if its reverse is equal to itself. For example : 12321 is palindrome while 123 is not palindrome. PLS_5: SQL> DECLARE 2 N NUMBER; 3 M NUMBER; 4 REV_N NUMBER:=0; 5 R NUMBER; 6 BEGIN 7 N := 12321; 8 M := N; 9 WHILE N > 0 10 LOOP 11 R := MOD( N,10); 12 REV_N := ( REV_N*10)+R; 13 N := TRUNC( N/10); 14 END LOOP; 15 16 IF M = REV_N THEN 17 DBMS_OUTPUT.PUT_LINE('Given number is palindrome.'); 18 ELSE 19 DBMS_OUTPUT.PUT_LINE('Given number is not palindrome.'); 20 END IF; 21 END; 22 / Output: Given number is palindrome. PL/SQL procedure successfully completed. VIC 40
  • 41. PLS_6 is a stored procedure named "SMS.get_exam_result" with one formal parameter named exam_year_in. The main task of this procedure is to generate the result of all the student in a school for the exam year passed as actual parameter to this procedure. It takes all the student details from student master table named "SMS.student_tab" and generate grades achieved by students in each subject as per the marks obtained by that student that is stored in "SMS.student_marks_tab". Table "SMS.subject_exam_code_tab" stores the exam codes for each subject code. The main PL/SQL concept used in this procedure is CURSOR FOR Loop: 1.Cursor FOR Loop at Line 3 fetches students from "SMS.student_tab" one by one. 2.Cursor FOR Loop at Line 6 fetches exam_code and marks obtained by the student fetched by for loop at line 3.(Look into the Joins between the tables in SELECT statement). 3.Inside the loop, procedure "SMS.get_student_result_demo_if" is called for each subject of the student fetched by outermost cursor for loop. Call to this procedure stores the grade obtained and other details such as Pass/ Rexam of a student subject-wise.(See explanation to PLS_1 for more details). 4.Call to this procedure is coded in a block that is also having a exception handling section. 5.Main Exception handling section raises the exception occurred to the calling environment of the procedure "SMS.get_exam_result". VIC 41
  • 42. /*SMS.STUDENT_TAB: Table for all the students in a school*/ CREATE TABLE SMS.STUDENT_TAB ( STUDENT_ID VARCHAR2(100 BYTE), ADMISON_YEAR NUMBER, STUDENT_STANDARD VARCHAR2(50 BYTE), STUDENT_AGE NUMBER ); /*SMS.STUDENT_SUBJECT_TAB: Table for all the subjects opted by students in a school*/ CREATE TABLE SMS.STUDENT_SUBJECT_TAB ( STUDENT_ID VARCHAR2(100 BYTE), STUDENT_STANDARD VARCHAR2(50 BYTE), STUDENT_SUBJECT_CODE VARCHAR2(50 BYTE) ); /*SMS.SUBJECT_EXAM_CODE_TAB: Table for Subject code and exam code linking for each standard in a school.*/ CREATE TABLE SMS.SUBJECT_EXAM_CODE_TAB ( STANDARD NUMBER, SUBJECT_CODE VARCHAR2(50 BYTE), EXAM_YEAR NUMBER, EXAM_CODE VARCHAR2(50 BYTE) ); /*SMS.STUDENT_MARKS_TAB: Table for subject-wise marks obtained by all the students in a school.*/ CREATE TABLE SMS.STUDENT_MARKS_TAB ( STUDENT_ID VARCHAR2(100 BYTE), STUDENT_STANDARD VARCHAR2(50 BYTE), STUDENT_SUBJECT_CODE VARCHAR2(50 BYTE), EXAM_YEAR NUMBER, STUDENT_MARKS NUMBER(26,6) ); VIC 42
  • 43. PLS_6: SQL> CREATE OR REPLACE PROCEDURE SMS.get_exam_result(exam_year_in NUMBER) IS 2 BEGIN 3 FOR I IN ( SELECT A.student_id, A.student_standard 4 FROM SMS.student_tab A) 5 LOOP 6 FOR J IN ( SELECT C.exam_code, D.student_marks 7 FROM SMS.student_subject_tab B, SMS.subject_exam_code_tab C, 8 SMS.student_marks_tab D 9 WHERE B.student_id = I.student_id 10 AND B.student_id = D.student_id 11 AND B.student_standard = D.student_standard 12 AND B.student_subject_code = D.student_subject_code 13 AND D.student_standard = C.standard 14 AND D.student_subject_code = C.subject_code 15 AND D.exam_year = C.exam_year) 16 LOOP 17 BEGIN 18 SMS.get_student_result_demo_if(I.student_id, I.student_standard, exam_year_in, 19 J.exam_code, J.student_marks); 20 EXCEPTION 21 WHEN OTHERS 22 THEN RAISE_APPLICATION_ERROR(-20001, SQLERRM, TRUE); 23 END; 24 END LOOP; 25 END LOOP; 26 EXCEPTION 27 WHEN OTHERS 28 THEN NULL; 29 END; 30 / Procedure created. VIC 43
  • 44. Try to Generate Result of all the student in a school for Exam year 2018 with PLS_6.Run below script first the insert required data for students, subjects details and marks obtained by students in subjects for year 2018: TRUNCATE TABLE SMS.STUDENT_REXAM_TAB; TRUNCATE TABLE SMS.STUDENT_PASS_TAB; TRUNCATE TABLE SMS.STUDENT_TAB; TRUNCATE TABLE SMS.STUDENT_SUBJECT_TAB; TRUNCATE TABLE SMS.SUBJECT_EXAM_CODE_TAB; TRUNCATE TABLE SMS.STUDENT_MARKS_TAB; INSERT INTO SMS.STUDENT_TAB (STUDENT_ID, ADMISON_YEAR, STUDENT_STANDARD, STUDENT_AGE) VALUES('S_01', 2017, '12', 17); INSERT INTO SMS.STUDENT_TAB (STUDENT_ID, ADMISON_YEAR, STUDENT_STANDARD, STUDENT_AGE) VALUES('S_02', 2014, '12', 17); INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE) VALUES('S_01', '12', 'IT_01'); INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE) VALUES('S_01', '12', 'MT_01'); INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE) VALUES('S_02', '12', 'MT_01'); INSERT INTO SMS.STUDENT_SUBJECT_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE) VALUES('S_02', '12', 'IT_01'); INSERT INTO SMS.SUBJECT_EXAM_CODE_TAB(STANDARD, SUBJECT_CODE, EXAM_YEAR, EXAM_CODE) VALUES(12, 'IT_01', 2018, 'EX_IT_01'); INSERT INTO SMS.SUBJECT_EXAM_CODE_TAB(STANDARD, SUBJECT_CODE, EXAM_YEAR, EXAM_CODE) VALUES(12, 'MT_01', 2018, 'EX_MT_01'); INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE, EXAM_YEAR, STUDENT_MARKS) VALUES('S_01', '12', 'IT_01', 2018, 96); INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE, EXAM_YEAR, STUDENT_MARKS) VALUES('S_01', '12', 'MT_01', 2018, 92); INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE, EXAM_YEAR, STUDENT_MARKS) VALUES('S_02', '12', 'IT_01', 2018, 83); INSERT INTO SMS.STUDENT_MARKS_TAB(STUDENT_ID, STUDENT_STANDARD, STUDENT_SUBJECT_CODE, EXAM_YEAR, STUDENT_MARKS) VIC 44
  • 45. PLS_7 is an anonymous block explaining concepts of Exception Handling in PL/SQL programming. 1. PL/SQL block compares the values of max_val and chk_val and raise an exception named "invalid_val_exception" whenever value chk_val is greater than max_val. 2. "invalid_val_exception" is a user-defined exception declared in Declaration section of main block(Line 4) and associated with error number -3434 using pragma name EXCEPTION_INIT(Line 5). 3. Nested Block at starting at Line 10 has another nested block starting at Line 10.Inside this nested block IF condition compares chk_val with max_val and raise exception named if condition results to TRUE. 4. The exception raised is handled by exception handler of the very same Nested block which re-raises exception using raise_application_error with error code -20101 and error message 'Invalid check value.'. 5. The Outer Nested block also has an Exception Handling section that also uses raise_application_error with error code – 20201 and error message SQLERRM that gives the same error message as that of -20101. 6. The Main Block also has an Exception Handling section that also does the same task and thus the exception is re-raised to the calling environment. Thus, with current PL/SQL code, we get the error message as shown in the Output ofVIC 45  This process of raising an exception by the inner(nested) blocks that is being re-raised by outer block to the main blocks is called Propagation of exceptions. STUDEN T_ID STUDENT_ STANDARD EXAM_ YEAR EXAM_ CODE MARKS_ OBTAINE D IS_ GRAC E GRACE_ VAL GRADE_ OBTAINED S_02 12 2018 EX_MT_ 01 25 Y 3 D- STUDEN T_ID STUDENT_ STANDARD EXAM_ YEAR EXAM_ CODE MARKS_ OBTAINED IS_ GRAC E GRADE_ OBTAINED IS_ GOLD_ MEDAL IS_ SILVER_ MEDAL IS_ BRONZE_ MEDAL S_01 12 2018 EX_IT_01 96 N A+ Y N N S_01 12 2018 EX_MT_0 1 92 N A+ N Y N S_02 12 2018 EX_IT_01 83 N A N N N
  • 46. PLS_7: SQL> DECLARE 2 max_val INTEGER; 3 chk_val INTEGER; 4 invalid_val_exception EXCEPTION; 5 PRAGMA EXCEPTION_INIT( invalid_val_exception, -3434); 6 BEGIN 7 max_val := 1000; 8 chk_val := 1001; 9 BEGIN 10 BEGIN 11 IF chk_val > max_val THEN 12 RAISE invalid_val_exception; 13 END IF; 14 EXCEPTION 15 WHEN invalid_val_exception 16 THEN RAISE_APPLICATION_ERROR(-20101, 'Invalid check value.'); 17 END; 18 EXCEPTION 19 WHEN OTHERS 20 THEN RAISE_APPLICATION_ERROR(-20201, SQLERRM, TRUE); 21 END; 22 EXCEPTION 23 WHEN OTHERS 24 THEN RAISE_APPLICATION_ERROR(-20301, SQLERRM, TRUE); ----Use with TRUE/FALSE in reverse sequence 25 END; 26 / Output: DECLARE * ERROR at line 1: ORA-20301: ORA-20201: ORA-20101: Invalid check value. ORA-20101: Invalid check value. ORA-06512: at line 24 ORA-20201: ORA-20101: Invalid check value. ORA-20101: Invalid check value. VIC 46
  • 47. Error Codes  This slide describes certain errors that you may encounter while creating programs related to the topics covered in this chapter.  Purpose of this slide is to provide assistance while practicing PL/SQL.  Following are the error codes, error messages, Cause and Actions for some ORA/PLS errors:  ORA-06592: CASE not found while executing CASE statement Cause: A CASE statement must either list all possible cases or have an else clause. Action: Add all missing cases or an else clause.  PLS-00109: unknown exception name "string" in PRAGMA EXCEPTION_INIT Cause: No declaration for the exception name referenced in an EXCEPTION_INIT pragma was found within the scope of the pragma. Action: Make sure the pragma follows the exception declaration and is within the same scope.  PLS-00484: redundant exceptions "string" and "string" must appear in same exception handler Cause: Using the EXCEPTION_INIT pragma, different exceptions were initialized to the same Oracle error number; then, they were referenced in different exception handlers within the same exception-handling part. Such references conflict.VIC 47
  • 48.  PLS-00700: PRAGMA EXCEPTION_INIT of string must follow declaration of its exception in the same declarative part. Cause: An EXCEPTION_INIT pragma was not declared in the same block as its exception. They must be declared in the proper order in the same block, with the pragma declaration following the exception declaration. Action: Place the EXCEPTION_INIT pragma directly after the exception declaration referenced by the pragma.  PLS-00702: second argument to PRAGMA EXCEPTION_INIT must be a numeric literal. Cause: The second argument passed to an EXCEPTION_INIT pragma was something other than a numeric literal (a variable, for example). The second argument must be a numeric literal in the range -9999 .. -1 (excluding -100) for Oracle errors or in the range -20000 .. -20999 for user-defined errors. Action: Replace the second argument with a valid error number.  ORA-32612: invalid use of FOR loop Cause: The MODEL FOR loop was used where it is not allowed. FOR loops are not allowed in complex dimensional predicates, on the right hand side of rules, or in the until condition. Action: Check the SQL statement and rewrite if necessary. VIC 48
  • 49. A bit of an Advice  Conditional programming contains lot of branching and unconditional exits/return from any loop or program unit. Indentation and labeling of block can be used to structure the code making the program self explanatory. Comments can also be used to achieve this purpose.  In programs containing loops like WHILE/NUMERIC FOR Loops, looping boundaries must be decided properly based on the number of iteration required to avoid infinite loops.  For User defined exceptions, error codes and error messages must be associated with defined errors in a way that they can give proper detail of the source of exception, cause of that exception and must be uniform throughout the application. User-defined package can be used for this purpose. It is highly recommended that pragma EXCEPTION_INIT be used in a predefined package giving names to all the anonymous system exceptions and application-specific errors in a way that these can be used throughout the application with any need to define them separately in individual progrma units that can cause ambiguity as one error code can refer multiple error messages if not defined carefully which is itself a tough task.  Handle exception carefully in case of program structure with nested blocks deciding carefully which category of exceptions are to be handled in current block and which are to be propagated to outer block so that complete details of severe exceptions can be obtained.  In Cursor FOR Loops, queries must be written with proper Join condition returning the result set that does not contain any ambiguous data and multiple rows causing the loop to get iterated un-necessarily as this type of loop has no user-defined boundaries. VIC 49
  • 50. Thanks for reading. We hope you have got some of what you were looking for in PL/SQL programming fundamentals. Next chapters will be covering PL/SQL in depth explaining further the PL/SQL program data and details of how SQL is used in PL/SQL with suitable examples expanding our SCHOOL MANAGEMENT SYSTEM(SMS) further. So stay with us. THAT’S ALL FOLKS!

Editor's Notes

  1. ABDC
  2. Red colored text is all code written in sqlplus.