0% found this document useful (0 votes)
7 views38 pages

DMS Final CH 4

PL/SQL is a procedural extension of SQL developed by Oracle that combines SQL with programming features, offering advantages like portability, modularity, and security. The document outlines the structure of PL/SQL blocks, variable declarations, data types, control structures, and examples of conditional statements such as IF and CASE. It emphasizes the importance of comments, variable scope, and the use of constants in PL/SQL programming.

Uploaded by

ks3715650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views38 pages

DMS Final CH 4

PL/SQL is a procedural extension of SQL developed by Oracle that combines SQL with programming features, offering advantages like portability, modularity, and security. The document outlines the structure of PL/SQL blocks, variable declarations, data types, control structures, and examples of conditional statements such as IF and CASE. It emphasizes the importance of comments, variable scope, and the use of constants in PL/SQL programming.

Uploaded by

ks3715650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

UNIT 4

PL/SQL PROGRAMMING
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL.

 Advantages of PL/SQL

Q] State any two advantages of functions in PL/SQL. [W 18, W 19]


1. PL/SQL is portable and high transaction processing language.
2. PL/SQL is in fact procedural language but it also supports object oriented programming.
3. It allows user to write as well as access the functions and procedures from outside the programs.
4. It has got built in libraries of packages.
5. Work can be divided into smaller modules so that it can be manageable and also enhances the
readability of the code.
6. It promotes reusability.
7. It is secure, as the code is in the database and hides the internal database details from the user.
8. It improves performance against running SQL queries multiple times.

 PL/SQL Block Structure


Q] Explain PL/SQL block structure with the help of diagram. [S 19]
PL/SQL Block Strucure :

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


S.No Sections & Description

Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines
all variables, cursors, subprograms, and other elements to be used in the program.

Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
2
section. It consists of the executable PL/SQL statements of the program. It should
have at least one executable line of code.

Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.

Every PL/SQL statement ends with a semicolon (;).


PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END.

The 'Hello World' Example


DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block.
To run the code from the SQL command line, you may need to type / at the beginning of the
first blank line after the last line of the code.
When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL procedure successfully completed.

 input from the user


Here is the syntax of taking input from the user:
<variablename>:= :<variablename>;
declare
i integer;
j integer;
s integer;
begin
i:=:i; --This statement will take input of i through user.
j:=:j; --This statement will take input of j through user.
s:=i+j;
dbms_output.put_line('sum is '||s);
end;
Note: || operator is used for concatenation of strings.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


 The PL/SQL Comments
Program comments are explanatory statements that can be included in the PL/SQL code that
you write and helps anyone reading its source code. All programming languages allow some
form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any
comment are ignored by the PL/SQL compiler.
The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line
comments are enclosed by /* and */.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL procedure successfully completed.

 Data type
State any four PL/SQL data types. [S 19]
The PL/SQL variables, constants and parameters must have a valid data type, which specifies a
storage format, constraints, and a valid range of values.

S.No Category & Description

Scalar
1 Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.

Composite
2 Data items that have internal components that can be accessed individually.
For example, collections and records.

Reference
3
Pointers to other data items.

Large Object (LOB)


4 Pointers to large objects that are stored separately from other data items, such
as text, graphic images, video clips, and sound waveforms.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


PL/SQL Scalar Data Types
PL/SQL Scalar Data Types and Subtypes come under the following categories −

S.No Date Type & Description

1 Numeric
Numeric values on which arithmetic operations are performed.

2 Character
Alphanumeric values that represent single characters or strings of characters.

3 Boolean
Logical values on which logical operations are performed.

4 Datetime
Dates and times.

 Variable
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in PL/SQL has a specific data type, which determines the size and the layout of
the variable's memory; the range of values that can be stored within that memory and the set
of operations that can be applied to the variable.
The name of a PL/SQL variable consists of a letter optionally followed by more letters,
numerals, dollar signs, underscores, and number signs and should not exceed 30
characters. By default, variable names are not case-sensitive. You cannot use a reserved
PL/SQL keyword as a variable name.

 Variable Declaration in PL/SQL


PL/SQL variables must be declared in the declaration section or in a package as a global
variable.
When you declare a variable, PL/SQL allocates memory for the variable's value and the storage
location is identified by the variable name.

Syntax −
variable_name datatype [:=initial_value] ;
Example:
salary number(8);

 Initializing Variables in PL/SQL


Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to
initialize a variable with a value other than the NULL value, you can do so during the
declaration, using assignment operator.
For example −
a integer := 10;

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


DECLARE
a integer := 10;
b integer := 20;
c integer;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
END;
/
Output:
Value of c: 30

 Variable Scope in PL/SQL


PL/SQL allows the nesting of blocks, i.e., each program block may contain another inner block.
If a variable is declared within an inner block, it is not accessible to the outer block. However, if
a variable is declared and accessible to an outer block, it is also accessible to all nested inner
blocks.
There are two types of variable scope −
 Local variables − Variables declared in an inner block and not accessible to outer
blocks.
 Global variables − Variables declared in the outermost block or a package.
Following example shows the usage of Local and Global variables in its simple form −
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
When the above code is executed, it produces the following result −
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185
PL/SQL procedure successfully completed.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


 Constant
A constant holds a value that once declared, does not change in the program. A constant declaration
specifies its name, data type, and value, and allocates storage for it.

Declaring a Constant
A constant is declared using the CONSTANT keyword. It requires an initial value and does not
allow that value to be changed. For example −
PI CONSTANT NUMBER := 3.141592654;

CONTROL STRUCTURES
Q] Explain any one control structure in PL/SQL with example.
PL/SQL has three categories of control statements: conditional control statements, loop
statements and sequential control statements.

A] Conditional Control statements: IF and CASE Statements


The IF statement lets us execute a sequence of statements conditionally. That is, whether the
sequence is executed or not depends on the value of a condition. There are three forms of IF
statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF. The CASE statement is a compact
way to evaluate a single condition and choose between many alternative actions.

1. IF statement
It is the simplest form of the IF control statement, frequently used in decision-making and
changing the control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the
condition is FALSE or NULL, then the IF statement does nothing.

Syntax
IF condition
THEN
Statement;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement.
Following is an example of the IF-THEN statement −
IF (a <= 20) THEN
c:= c+1;
END IF;
If the Boolean expression condition evaluates to true, then the block of code inside the if
statement will be executed.
If the Boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing end if) will be executed.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Example

DECLARE
a number(2) := 10;
BEGIN
a:= 10;
IF( a < 20 ) THEN

dbms_output.put_line('a is less than 20 ' );


END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is less than 20
value of a is : 10
PL/SQL procedure successfully completed.

2. IF-THEN-ELSE
A sequence of IF-THEN statements can be followed by an optional sequence
of ELSE statements, which execute when the condition is FALSE.

Syntax
IF condition THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE
statements, when the test condition is TRUE, the statement S1 is executed and S2 is
skipped; when the test condition is FALSE, then S1 is bypassed and statement S2 is
executed.

Example
Let us try an example that will help you understand the concept −
DECLARE
a number(3) := 100;
BEGIN

IF( a < 20 ) THEN

dbms_output.put_line('a is less than 20 ' );


ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


When the above code is executed at the SQL prompt, it produces the following result −
a is not less than 20
value of a is : 100
PL/SQL procedure successfully completed.

IF-THEN-ELSIF
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSE statement.
The ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
 It's ELSIF, not ELSEIF.
 An IF-THEN statement can have zero or one ELSE's and it must come after any
ELSIF's.
 An IF-THEN statement can have zero to many ELSIF's and they must come before
the ELSE.
 Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.

Syntax
The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;

Example
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
None of the values is matching
Exact value of a is: 100

PL/SQL procedure successfully completed.

Nested IF-ELSE
It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means
you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s).

Syntax
IF( boolean_expression 1)THEN
-- executes when the boolean expression 1 is true
IF(boolean_expression 2) THEN
-- executes when the boolean expression 2 is true
sequence-of-statements;
END IF;
ELSE
-- executes when the boolean expression 1 is not true
else-statements;
END IF;

Example
DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

PL/SQL procedure successfully completed.

CASE statement
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression, the value of which is used to select one of
several alternatives.

Syntax
The syntax for the case statement in PL/SQL is −
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;

Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Excellent

PL/SQL procedure successfully completed.

Searched CASE statement


Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
The searched CASE statement has no selector and the WHEN clauses of the statement
contain search conditions that give Boolean values.

Syntax
The syntax for the searched case statement in PL/SQL is −
CASE
WHEN selector = 'value1' THEN S1;
WHEN selector = 'value2' THEN S2;
WHEN selector = 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;

Example
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then dbms_output.put_line('Excellent');
when grade = 'B' then dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
end case;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Very good

PL/SQL procedure successfully completed.

B] Iterative Control / Loop Statements


Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
1. Basic Loop Statement
A loop statement allows us to execute a statement or group of statements multiple times.

Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and then control
resumes at the top of the loop.

Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT
statement or an EXIT WHEN statement is required to break the loop.

Example

DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60

You can use the EXIT WHEN statement instead of the EXIT statement −

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

2. WHILE LOOP
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target
statement as long as a given condition is true.

Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;

Before each iteration of the loop, the condition is evaluated. If the condition is true, the
sequence of statements is executed, then control resumes at the top of the loop.
If the condition is false or null, the loop is bypassed and control passes to the next statement.

Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

3. FOR LOOP
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.

Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Following is the flow of control in a For Loop −
 The initial step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
 Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the
body of the loop is executed. If it is FALSE, the body of the loop does not execute
and the flow of control jumps to the next statement just after the for loop.
 After the body of the for loop executes, the value of the counter variable is increased
or decreased.
 The condition is now evaluated again. If it is TRUE, the loop executes and the
process repeats itself (body of loop, then increment step, and then again condition).
After the condition becomes FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
 The initial_value and final_value of the loop variable or counter can be literals,
variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL raises
the predefined exception VALUE_ERROR.
 The initial_value need not be 1; however, the loop counter increment (or
decrement) must be 1.
 PL/SQL allows the determination of the loop range dynamically at run time.

Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
value of a: 19
value of a: 20

PL/SQL procedure successfully completed.

Reverse FOR LOOP Statement


By default, iteration proceeds from the initial value to the final value.
You can reverse this order by using the REVERSE keyword.
In such case, iteration proceeds the other way. After each iteration, the loop counter is
decremented.
However, you must write the range bounds in ascending (not descending) order. The
following program illustrates this −
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10

PL/SQL procedure successfully completed.

EXIT statement
The EXIT statement in PL/SQL programming language has the following two usages −
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
 When the EXIT statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
 If you are using nested loops (i.e., one loop inside another loop), the EXIT statement
will stop the execution of the innermost loop and start executing the next line of code
after the block.

Syntax
The syntax for an EXIT statement in PL/SQL is as follows −
EXIT;

Example
DECLARE
a number(2) := 10;
BEGIN
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a > 15 THEN
-- terminate the loop using the exit statement
EXIT;
END IF;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

PL/SQL procedure successfully completed.

The EXIT WHEN Statement

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. If the
condition is true, the loop completes and control passes to the statement immediately after
the END LOOP.
Following are the two important aspects for the EXIT WHEN statement −
 Until the condition is true, the EXIT-WHEN statement acts like a NULL statement,
except for evaluating the condition, and does not terminate the loop.
 A statement inside the loop must change the value of the condition.

Syntax
The syntax for an EXIT WHEN statement in PL/SQL is as follows −
EXIT WHEN condition;
The EXIT WHEN statement replaces a conditional statement like if-then used with the
EXIT statement.

Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is:60

PL/SQL procedure successfully completed.

CONTINUE
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
The CONTINUE statement causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating. In other words, it forces the next iteration
of the loop to take place, skipping any code in between.

Syntax
The syntax for a CONTINUE statement is as follows −
CONTINUE;

Example
DECLARE
a number(2) := 10;
BEGIN
-- while loop execution
WHILE a < 20 LOOP

a := a + 1;
IF a = 15 THEN
CONTINUE;
ELSE
dbms_output.put_line ('value of a: ' || a);
END IF;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

GOTO statement
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
A GOTO statement in PL/SQL programming language provides an unconditional jump from
the GOTO to a labeled statement in the same subprogram.
NOTE − The use of GOTO statement is not recommended in any programming language
because it makes it difficult to trace the control flow of a program, making the program hard
to understand and hard to modify. Any program that uses a GOTO can be rewritten so that
it doesn't need the GOTO.

Syntax
The syntax for a GOTO statement in PL/SQL is as follows −
GOTO label;
..
..
<< label >>
statement;

Example
DECLARE
a number(2) := 10;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 15 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

Write a PL/SQL program to print n even numbers using For Loop.


Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
declare
num number;
n number:=&n;
begin
for num in 1..n loop
if(mod(num,2)=0) then
dbms_output.put_line(‘Even no are :’||num);
end if;
end loop;
end;

Write a PL/SQL program to calculate factorial of a given number. 6M

Ans
DECLARE
num number:=&num;
fact number:=1;
BEGIN
while num!=0
loop
fact:=fact*num;
num:=num-1
end loop;
dbms_output.put_line(‘Factorial =’||fact);
END;
/

Write a PL/SQL code to print reverse of a number. 4 M

declare
n number;
i number;
rev number:=0;
r number;
begin
n:=&n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is '||rev);
end;

Procedures and Functions


Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of subprograms −
 Functions − These subprograms return a single value; mainly used to compute and
return a value.
 Procedures − These subprograms do not return a value directly; mainly used to
perform an action.

A] Procedure
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Where,
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone procedure.

Example
The following example creates a simple procedure that displays the string 'Hello World!' on
the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result

Procedure created.

Executing a Standalone Procedure

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


A standalone procedure can be called in two ways −
 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World

The procedure can also be called from another PL/SQL block −


BEGIN
greetings;
END;
/
The above call will display −
Hello World

Deleting a Standalone Procedure


A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting
a procedure is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
DROP PROCEDURE greetings;

Parameter Modes in PL/SQL Subprograms


The following table lists out the parameter modes in PL/SQL subprograms −

S.No Parameter Mode & Description

IN
1 An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot
be assigned a value.. It is the default mode of parameter passing.

OUT
2
An OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable. You can change its value .

IN OUT
3
An IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller. It can be assigned a value and the value can be read.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


IN & OUT Mode Example:
This program finds the minimum of two values. Here, the procedure takes two numbers using
the IN mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
CREATE PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.

Function
Function is a logically grouped set of SQL and Pl/SQL statements that perform a specific task. A
function is same as a procedure except that it returns a value.

Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Where,
 function-name specifies the name of the function.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the procedure.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the
function.
 function-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone function.

Example
The following example illustrates how to create and call a standalone function. This
function returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we have already created.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result

Function created.

Calling a Function
While creating a function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program
calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or
when the last end statement is reached, it returns the program control back to the main
program.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


To call a function, you simply need to pass the required parameters along with the function
name and if the function returns a value, then you can store the returned value. Following
program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6

Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c:= findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45

PL/SQL procedure successfully completed.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


CURSOR
A cursor is a temporary work area created in system memory when an SQL statement is
executed. A cursor holds the rows (one or more) returned by a SQL statement, with a pointer
that identifies a current row. The set of rows the cursor holds is referred to as the active set.
There are two types of cursors −

 Implicit cursors
 Explicit cursors

Implicit Cursors
Implicit cursors are automatically generated and used by the system during the
manipulation of a DML query. Programmers cannot control the implicit cursors and the
information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to
be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.

S.No Attribute & Description

%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or
more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.

%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned
no rows. Otherwise, it returns FALSE.

%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.

%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.

Example
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/

When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected

PL/SQL procedure successfully completed.


If you check the records in customers table, you will find that the rows have been updated −

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor

Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor

Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined
cursor as follows −
OPEN c_customers;

Fetching the Cursor

Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor

Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers;

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Example
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;

CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Triggers
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the following
events −
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.

Benefits of Triggers
Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating Triggers
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,

 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with
the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The
INSTEAD OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the trigger.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various
DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected. Otherwise the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would fire. This
clause is valid only for row-level triggers.

Example

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger
will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE
ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Triggering a Trigger

Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above created


trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null. Let
us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement
will update an existing record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;

When a record is updated in the CUSTOMERS table, the above create


trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500

To delete a trigger:

DROP TRIGGER trigger_name.


Example:
Drop trigger display_salary _Changes

Q] Write a trigger which invokes on deletion of record on emp table. [W 22] 4M

create or replace trigger trg1 before delete on emp


declare
begin
dbms_output.pu_line(‘Please Do not delete the record');
end;

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


EXCEPTION HANDLING
An exception is an error condition during a program execution.
PL/SQL supports programmers to catch such conditions using EXCEPTION block in the
program and an appropriate action is taken against the error condition.
There are two types of exceptions −

 System-defined exceptions
 User-defined exceptions

Syntax for Exception Handling

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exceptionn-handling-statements
END;

Note:
When other keyword should be used only at the end of the exception handling block as no
exception handling part present later will get executed as the control will exit from the block
after executing the WHEN OTHERS.

A] System defined exceptions/ Built In Exceptions:


These exceptions are predefined in PL/SQL which get raised WHEN certain database rule is
violated. Example: NO_DATA_FOUND, ZERO_DIVIDE

Lets create a table student.


create table student(g_id int , g_name varchar(20), marks int);
insert into student values(1, 'Suraj',100);
insert into student values(2, 'Praveen',97);
insert into student values(3, 'Jessie', 99);

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


1. NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows.

DECLARE
temp varchar(20);
BEGIN
SELECT g_id into temp from student where g_name='Arrow';
Exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR there is no name as Arrow in student table');
end;

Output:
ERROR there is no name as Arrow in student table

2. ZERO_DIVIDE = raises exception WHEN dividing with zero.

DECLARE
a int:=10;
b int:=0;
answer int;
BEGIN
answer:=a/b;
dbms_output.put_line('the result after division is'||answer);
Exception
WHEN zero_divide THEN
dbms_output.put_line('dividing by zero please check the values again');
dbms_output.put_line('the value of a is '||a);
dbms_output.put_line('the value of b is '||b);
END;

Output:
dividing by zero please check the values again
the value of a is 10
the value of b is 0

B] User defined exceptions:


PL/SQL allow us to define our own exception according to the need of our program.

A user defined exception must be declared and then raised explicitly by the programmer by
using the command RAISE.

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Syntax for User defined Exception:

DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

Q] Write a PL/SQL program which accepts the customer_ID from the user. If the user
enters an invalid ID then the exception invalid_id is raised using exception handling.

DECLARE
customer_id number(10);
invalid_id Exception;
BEGIN
customer_id:=& customer_id;
if(customer_id <0) then
raise invalid_id;
end if;
EXCEPTION
WHEN invalid_id THEN
dbms_output.put_line(‘Id can not be negative’);
END;

Q] Write a PL/SQL program which accepts the age from the user. If the user enters an age
<18 then the exception invalid_age is raised using exception handling.

Declare
age number(3);
invalid_age Exception;
Begin
age:=&age;
if age<18 then
raise invalid_age;
end if;
Exception
when invalid_age then
dbms_output.put_line(“Age should be greater than or equal to 18”)
End

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


Example:
Divide non-negative integer x by y such that the result is greater than or equal to 1.
From the given question we can conclude that there exist two exceptions
- Division be zero.
- If result is greater than or equal to 1 means y is less than or equal to x.

DECLARE
x int:=&x; /*taking value at run time*/
y int:=&y;
div_r float;
exp1 EXCEPTION;
exp2 EXCEPTION;

BEGIN
IF y=0 then
raise exp1;

ELSIF y > x then


raise exp2;

ELSE
div_r:= x / y;
dbms_output.put_line('the result is '||div_r);
END IF;

EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('division by zero not allowed');

WHEN exp2 THEN


dbms_output.put_line('Error');
dbms_output.put_line('y is greater than x please check the input');
END;

Input 1:
x = 20
y = 10
Output: the result is 2

Input 2:
x = 20
y=0
Output:
Error

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)


division by zero not allowed

Input 3:
x=20
y = 30
Output:
Error
y is greater than x please check the input

Write a PL/SQL code to check whether specified employee is present in Emp table or not.
Accept empno from user. If employee does not exist display message using exception
handling.

declare
no emp.empno%type;
begin
no:=&no;
select empno into no from emp where empno=no;
dbms_output.put_line('Empno is present: '||no);
exception
when no_data_found then
dbms_output.put_line('Empno not present');
end;

Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)

You might also like