0% found this document useful (0 votes)
9 views33 pages

Unit V - RDBMS

This document is a comprehensive guide on PL/SQL, covering its structure, language elements, operators, control structures, and more. It details the components of a PL/SQL block, including declaration, execution, and exception handling sections, as well as various data types and operators used in PL/SQL programming. Additionally, it explains control structures like decision-making and iterative statements, providing examples and syntax for better understanding.
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)
9 views33 pages

Unit V - RDBMS

This document is a comprehensive guide on PL/SQL, covering its structure, language elements, operators, control structures, and more. It details the components of a PL/SQL block, including declaration, execution, and exception handling sections, as well as various data types and operators used in PL/SQL programming. Additionally, it explains control structures like decision-making and iterative statements, providing examples and syntax for better understanding.
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/ 33

III BCA

RDBMS

UNIT V
Prepared By
Mrs. S. Radhika
Department of Computer Applications,
Thiruthangal Nadar College,
Selavayal, Chennai – 51.
RDBMS – UNIT V

CONTENTS
1. PL/SQL: Structure
2. PL/SQL Language Elements
3. Operators Control Structure
4. Iterative Control
5. Cursors
6. Procedure
7. Function
8. Packages
9. Exceptional Handling
10. Triggers.
UNIT V – PL/SQL
PL/SQL Block Structure
PL/SQL stands for Procedural
Language/Structured Query
Language.
It is extension of SQL.
PL/SQL program units
[DECLARE] organize the code into blocks.
Syntax for PL/SQL Block
Declaration section; BEGIN
Structure
Execution section; [EXCEPTION]
Exception section;
END;
/

 A block consists of three sections, namely:


 Declaration section (optional).
 Execution section (mandatory).
 Exception handling section (optional).

1. Declaration Section
 It starts with DECLARE keyword.
 It is used to declare the variables, constants, records and cursors etc.
 It is an optional section.

2. Execution Section
 Execution section starts with BEGIN keyword and ends with END
keyword.
 This can contain both PL/SQL code and SQL code.
 It is used to write the program logic.
 It is a mandatory section.

3. Exception Section
 This section starts with the EXCEPTION keyword.
 It contains exception(s) that handle errors in the program.
 This section allows the user to define his/her own error messages.
 This section executes only when an error occurs. It is an optional
section.
 It is an optional section.

4. End Section
 This section indicates the end of PL/SQL block.

3
UNIT V - RDBMS
Example :
SQL> SET SERVEROUTPUT ON;

SQL> BEGIN
DBMS_OUTPUT.PUT_LINE(“Hello World”)
END;
/ Output:
Hello World

PL/SQL procedure successfully completed.


-----------------------------------------------------------------------------------------------------------------
PL/SQL Language Elements

Various language elements of PL/SQL are,

Character
sets Lexical
Units
Delimiters
Identifiers
Literals
Comments
Character Set
A PL/SQL program consists of text having specific set of characters.
Character set may include the following characters:
 Alphabets, both in upper case [A–Z] and lower case [a–z]
 Numeric digits [0–9]
Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , # $ & | { } ? [ ]
 Blank spaces, tabs, new line, and carriage returns.
PL/SQL is not case sensitive, so lower case letters are equivalent to corresponding upper case
letters except within string and character literals.

Lexical Units
A line of PL/SQL program contains groups of characters known as lexical units, which can be
classified as
follows:
Delimiter
s
Identifiers
Literals
Commen
ts
4
UNIT V - RDBMS
1. Delimiters
 A delimiter is a simple or compound symbol that has a special meaning to PL/SQL.
 Simple symbol consists of one character, while compound symbol consists of more than
one character.

Simple
SymbolDelimiters Compound
Meaning Delimites Symbol Meaning
+ addition operator := assignment operator
- Subtraction operator => association operator
* Multiplication operator || concatenation operator
/ Division operator ** exponentiation operator
% attribute indicator << label delimiter (begin)
' character string delimiter >> label delimiter (end)
. component selector /* multi-line comment delimiter (begin)
( expression or list */ multi-line comment delimiter (end)
delimiter <> relational operator
) expression or list
delimiter != relational operator
: host variable indicator ~= relational operator
, item separator ^= relational operator
" quoted identifier delimiter <= relational operator
= relational operator >= relational operator
< relational operator -- single-line comment indicator
> relational operator
@ remote access indicator
; statement terminator
2. Identifiers

Identifiers are used in the PL/SQL programs to name the items as constants, variables,
cursors, cursor variables, subprograms, etc.
 Identifiers can consists of alphabets, numerals, dollar signs, underscores, and number
signs only.
 Any other characters like hyphens, slashes, blank spaces, etc. are illegal.
 It must begin with an alphabetic letter optionally followed by one or more characters
(permissible in identifier).
 It cannot contain more than 30 characters.
Example
o Some of the valid identifiers are as follows:
Name1 A1
Student_id
o Some of the Invalid identifiers:
mine&yours debit-amount on/off

5
UNIT V - RDBMS
3. Literals
A literal is an explicitly defined numeric, character, string, or Boolean value, which is not represented by an
identifier.
i. Numeric Literals
 A numeric literal is an integer or a real value.
 An integer literal may be a positive, negative, or unsigned whole number without a decimal point.
Examples:
030 6 -14 0 +32767
 A real literal is a positive, negative, or unsigned whole or fractional number with a decimal point.
Examples:
6.6667 0.0 -12.0 3.14159 +8300.00 .5 25

 Numeric literals can also contain exponential numbers (an optionally signed number suffix with an E
(or e) followed by an optionally signed integer).
Examples:
2E5 1.0E-7 3.14159e0 -1E38 -9.5e-3

where, E stands for “times ten to the power of.”

• Character Literals
 A character literal is an individual character enclosed by single quotes (‘).
 Character literals include all the printable characters in the PL/SQL character set: letters, numerals,
spaces, and special symbols.
Examples:
'Z' '%' '7' ' ' 'z' '('
 PL/SQL is case sensitive within character literals.
For example, PL/SQL considers the literals “A” and “a” to be different.

iv.String Literals
 A character string can be represented by an identifier or explicitly written as a string literal.
 A string literal is enclosed within single quotes and may consist of one or more characters. Some
examples of string literals are as follows:
“Good Morning!”
“TATA INFOTECH LTD” “04-MAY-00”
“$15,000,000”
 All string literals are of character data type.
 PL/SQL is case sensitive within string literals.
For example, PL/SQL considers the following literals to be different:
“HUMAN”
“Human”

• Boolean Literals
 Boolean literals are the predefined values TRUE, FALSE, and NULL.
 Boolean literals are values, not strings.
For example a condition:
If (x = 10) is TRUE only for the value of x equal to 10, for any other value of x it is FALSE and for no value of x
it is NULL.

6
UNIT V - RDBMS
4. Comments
 Comments are used in the PL/SQL program to improve the readability and understandability of a
program.
 A comment can appear anywhere in the program code.
 The compiler ignores comments.
 Generally, comments are used to describe the purpose and use of each code segment.
 A PL/SQL comment may be a single-line or multiline.
Single-Line Comments
o Single-line comments begin with a double hyphen (–) anywhere on a line and extend to the end
of the line.
Example
– start calculations
Multiline Comments
o Multiline comments begin with a slash-asterisk (/*) and end with an asterisk slash(*/)
Example
/* Hello World! This is an example of multiline comments in PL/SQL */
----------------------------------------------------------------------------------------------------------------------------------

Variables and Constants


 Variables and constants can be used within PL/SQL block, in procedural statements and in SQL
statements.
 These are used to store the values.
 As the program executes, the values of variables can change, but the values of constants cannot.
 However, it is must to declare the variables and constants, before using these in executable portion of
PL/SQL.
Declaration
 Variables and constants are declared in the Declaration section of PL/SQL block.
 These can be any of the SQL data type like CHAR, NUMBER, DATE, etc.
 The syntax for declaring a variable is as follows:
Identifier_name datatype; Example
Name VARCHAR2(10);
Age NUMBER(2);
Joining date DATE;

Initializing the Variable


 By default variables are initialized to NULL at the time of declaration. If we want to initialize the
variable by some other value
 Syntax would be as follows:
Identifier datatype := value;
(Or)
Identifier datatype DEFAULT value; Example
Joining date DATE := 01-JULY-99;
(or)
Joining date DATE DEFAULT 01-JULY-99;
Constraining a Variable
 Variables can be NOT NULL constrained at the time of declaring these.
Example
Joining date DATE NOT NULL: = 01-JULY-99;

Declaring Constants 7
UNIT V - RDBMS
 Declaration of constant is similar to declaration of variable, except the keyword CONSTANT precedes
the datatype
 It must be initialized by some value.
 The syntax for declaring a constant is as follows:
Identifier_Name CONSTANT datatype := value; Example
Age_limit CONSTANT NUMBER := 30;
 A list of variables that have the same data type cannot be declared in the same row
Example
A, B, C NUMBER (4,2); – illegal
It should be declared in separate lines as follows: A NUMBER (4,2);
B NUMBER (4,2);
C NUMBER (4,2);
-------------------------------------------------------------------------------------------------------------------------------

Operators
PL/SQL language is rich in built-in operators and provides the following types of operators −

 Arithmetic operators
 Relational operators
 Comparison operators
 Logical operators
 String operators

1. Arithmetic Operators
Let us assume variable A = 10 and variable B = 5

Operator Description Example


+ Adds two operands A + B will give 15
- Subtracts second operand from the A - B will give 5
* first Multiplies both operands A * B will give 50
/ Divides numerator by de-numerator A / B will give 2
** Exponentiation operator A ** B will give
100000
2. Relational Operators
Relational operators compare two expressions or values and return a
Boolean result. Let us assume variable A = 10 and variable B = 20

Operator Descriptio Exampl


= Checks if the values ofntwo operands are equal (A =e B) is not
or not, true.
8
UNIT V - RDBMS
if yes then condition becomes true.
!= (A != B) is true.
Checks if the values of two operands are equal or not, if
<> values are not equal then condition becomes true.
~=
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes
< true. (A < B) is true.
Checks if the value of left operand is less than the value
>= of right operand, if yes then condition becomes true. (A >= B) is not true.
Checks if the value of left operand is greater than or
<= equal to the value of right operand, if yes then (A <= B) is true
condition becomes true.
Checks if the value of left operand is less than or equal
3. ComparisontoOperators
the value of right operand, if yes then condition
becomes true.
Comparison operators are used for comparing one expression to another. The result is always
either TRUE, FALSE or NULL.
Operator Description Example
LIKE The LIKE operator compares a character, If 'Zara Ali' like 'Z% A_i' returns a
string, or CLOB value to a pattern and returns Boolean true, whereas, 'Nuha Ali' like
TRUE if the value matches the pattern and 'Z% A_i' returns a Boolean false.
FALSE if it does not.
BETWEEN If x = 10 then, x between 5 and 20
The BETWEEN operator tests whether a value
returns true, x between 5 and 10
lies in a specified range. x BETWEEN a AND b
returns true, but x between 11 and 20
means that x >= a and x <= b.
returns false.
IN If x = 'm' then, x in ('a', 'b', 'c') returns
The IN operator tests set membership. x IN
Boolean false but x in ('m', 'n', 'o')
(set) means that x is equal to any member of
returns Boolean true.
set.
IS NULL If x = 'm', then 'x is null' returns
The IS NULL operator returns the BOOLEAN Boolean false.
value TRUE if its operand is NULL or FALSE if
it is not NULL. Comparisons involving NULL
values always yield NULL.

4. Logical
Operators
9
UNIT V - RDBMS
Let us assume variable A holds true and variable B holds false,
then
Example
Operator Description
an Called the logical AND operator. If both the operands are true then (A sand B) is
d condition becomes true. false.
or Called the logical OR Operator. If any of the two operands is true then (A or B) is true.
condition becomes true.
no Called the logical NOT Operator. Used to reverse the logical state of its not (A and B)
t operand. If a condition is true then Logical NOT operator will make it is true.
false.
PL/SQL Operator Precedence
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN,
IN.
--------------------------------------------------------------------------------------------------------------------------------

CONTROL STRUCTURES
It can be categorized into
1.Decision Making Statements
2.Looping or Iterative Statement

3.Decision Making Statements


 IF Statement
 CASE Statement

i.IF Statement
 The IF statement executes a sequence of statements depending on the value of
a condition.
 There are three forms of IF statements:
 IF-THEN
 IF-THEN-ELSE
IF-THEN-ELSIF

IF-THEN statement
10
UNIT V - RDBMS
 The simplest form of IF statement
 It associates a condition with a sequence of statements enclosed by the keywords THEN
and END IF.
 Syntax:
IF condition THEN
Statement body
END IF;

 Flow
Chart:

Example code :

SET SERVEROUTPUT ON; DECLARE


x int:=10; y int:=80;
BEGIN
IF(y>x) THEN
DBMS_OUTPUT.PUT_LINE('Result: ' ||y|| ' is greater than ' ||x); END IF;
END;

OUTPUT:
Result: 80 is greater than 10
PL/SQL procedure successfully completed.

IF-THEN-ELSE statement
IF statement adds the keyword ELSE followed by an alternative sequence of statement.
If the condition is false or NULL, then only the alternative sequence of statements get
executed.
It ensures that either of the sequence of statements is executed.

11
UNIT V - RDBMS
 Syntax:
IF <test_condition> THEN
statement1
ELSE
statement2 END IF;

Flow Chart:

Example code:
SET SERVEROUTPUT ON; DECLARE
x INT;
BEGIN
x := &x;
IF MOD(x,2) = 0 THEN
DBMS_OUTPUT.PUT_LINE('Even Number');
ELSE
DBMS_OUTPUT.PUT_LINE('Odd Number'); END IF;
END;

OUTPUT:
Enter value for x : 6
Even Number
PL/SQL procedure successfully completed.

12
UNIT V - RDBMS
IF-THEN-ELSIF statement
IF...THEN...ELSIF...ELSE statement is suitable in which all the conditions are tested one by one and
whichever condition is found to be TRUE, that block of code is executed. And if all the conditions result in
FALSE then the ELSE part is executed.
Syntax:

IF <test_condition1> THEN Body


of Statement1

ELSIF <test_condition2> THEN


Body of Statement2
ELSIF <test_condition3> THEN
Body of Statement3
...
...
... ELSE
Body of Else Code
END IF;

Example Code to find out greatest among three numbers:


SET SERVEROUTPUT ON;

DECLARE
A INT; B INT; C INT;
BEGIN
A := &A;
B := &B;
C := &C;
IF((A>B) AND (A>C)) THEN
DBMS_OUTPUT.PUT_LINE(‘A is greatest number’); ELSIF(B>C) THEN
DBMS_OUTPUT.PUT_LINE(‘B is greatest number’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘C is greatest number’); END IF;
END;
/

OUTPUT:
Enter value for A : 12
Enter value for B : 4 Enter value for C : 32

13
UNIT V - RDBMS
C is greatest number
PL/SQL procedure successfully
completed.

ii. CASE Statement

 It is a decision making statement that selects only one option out of the multiple
available options.
 If all the cases fail then the else case is executed.
 Syntax:
CASE selector
WHEN value1 THEN statement1;
WHEN value2 THEN statement2;
...
...
ELSE statement; END CASE;

Example code:

DECLARE
A INT; B INT;
BEGIN
A := &A;
B := MOD(A,2); CASE B
WHEN 0 THEN DBMS_OUTPUT.PUT_LINE('Even Number'); WHEN 1 THEN
DBMS_OUTPUT.PUT_LINE('Odd Number');
ELSE DBMS_OUTPUT.PUT_LINE('User entered wrong input'); END CASE;
END;
/

OUTPUT:

Enter the value for A : 7 Odd number


PL/SQL procedure successfully completed.

14
UNIT V - RDBMS
2. Looping or Iterative
Statements
LOOP chart

 In iterative control, a group of statements are executed repeatedly till certain condition is true,
and control exits from loop to next statement when the condition becomes false.
 There are mainly three types of loop statements:
i. LOOP
ii. WHILE-LOOP
iii. FOR-LOOP

i. LOOP statement
 It is basic loop structure encloses sequence of statements between the keywords
LOOP and END LOOP.
 With each iteration of the loop, the sequence of statements gets executed, then control
reaches at the top of the loop.
 The syntax for LOOP control :

LOOP
sequence of statements
END LOOP;

An EXIT or an EXIT-WHEN keyword is required to break the


loop.
Example code 1:
DECLARE
x number := 10; BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(x); x := x +
10;
IF x > 30 THEN
exit; END IF;
END LOOP;

15
UNIT V - RDBMS
DBMS_OUTPUT.PUT_LINE('After Exit, x is: ' || x); END;
/

OUTPUT: 10
20
30
After Exit, x is: 40

PL/SQL procedure successfully completed.

PL/SQL: While Loop


 It is an entry controlled loop
 Before entering in a while loop, first the condition is tested :
 if the condition is TRUE , the statement or a group of statements get
executed
 if the condition is FALSE the control will move out of the while loop.
 Syntax:

WHILE <test_condition> LOOP


Sequence of Statements
END LOOP;

 Example Code :
DECLARE
num int:=1; BEGIN
WHILE(num <= 10) LOOP
dbms_output.put_line(''|| num); num := num+2;
END LOOP;
END;
/ OUTPUT:
1
3
5
7
9
PL/SQL procedure successfully completed.

16
UNIT V - RDBMS
For Loop (Iterative control)
This loop is used when some statements in PL/SQL code block are to be repeated for a fixed
number of times.
The for loop automatically increments the value of the counter variable by 1 at the end of each
loop cycle.
Syntax: FOR counter_variable IN start_value..end_value
LOOP
Sequence of statements
END LOOP;

 counter variable decides how many time the loop will be executed based on a start_value
and end_value provided at the beginning of the loop.
 Example code:

DECLARE
i number(2); BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE(i); END LOOP;
END;
/
OUTPUT: 1
2
3
4
5

PL/SQL procedure successfully completed.

Reverse FOR LOOP statement


 By default, iteration proceeds from the initial value to the final value, generally upward from
the lower bound to the higher bound.
 We can reverse this order by using the REVERSE keyword.
Example code :
DECLARE x NUMBER;
BEGIN
x:=5;
FOR x IN REVERSE 1..5 LOOP
DBMS_OUTPUT.PUT_LINE (x); END LOOP;
END;

17
UNIT V - RDBMS
/

OUTPUT:
5
4
3
2
1

PL/SQL procedure successfully


completed.

PL/SQL - Nested Loops


PL/SQL allows using one loop inside another loop.
The syntax for a nested basic LOOP statement is as follows:

LOOP
Sequence of statements1 LOOP
Sequence of statements2 END
LOOP;
END LOOP;

 The syntax for a nested FOR LOOP statement is as follows :

FOR counter1 IN start_value1 .. end_value1 LOOP


Sequence of statements1
FOR counter2 IN start_value2 .. end_value2 LOOP
Sequence of statements2
END LOOP; END LOOP;

 The syntax for a nested WHILE LOOP statement is as follows :

WHILE condition1 LOOP


Sequence of statements1
WHILE condition2 LOOP
Sequence of statements2 END
LOOP;
END LOOP;

18
UNIT V - RDBMS
Example Code for nested basic
loop:
DECLARE
i number(3); j number(3);
BEGIN
i := 2;
dbms_output.put_line(’ Prime Numbers'); LOOP
j:= 2; LOOP
exit WHEN ((mod(i, j) = 0) or (j = i)); j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i); END IF;
i := i + 1;
exit WHEN i = 20; END LOOP;
END;
/

OUTPUT:
Prime Numbers 2
3
5
7
11
13
17
19
PL/SQL procedure successfully completed.

-----------------------------------------------------------------------------------------------------------------------------------

CURSORS

Oracle creates a memory area, known as the context area, which contains all the information
needed for processing the statement.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.
A cursor holds the rows (one or more) returned by a SQL statement.
 The set of rows the cursor holds is referred to as the active set.
There are two types of cursors −

19
UNIT V - RDBMS
1. Implicit
cursors
2. Explicit
cursors

1. Implicit cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement.
Programmers cannot control the implicit cursors and the information in it.
PL/SQL implicitly declares a cursor for every SQL DML statement, such as INSERT, DELETE,
UPDATE, and SELECT statement

Cursor Attributes
In PL/SQL every cursor, implicit or explicit, has four attributes:
Cursor attributes Description

%FOUND 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 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.
%ROWCOUNT Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
%ISOPEN Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.

 These cursor attributes can be used in procedural statements (PL/SQL), but not in SQL
statements.

Implicit Cursor Example : Create customers table and have records:


ID NAME AGE SALARY

1 Ramesh 23 20000

2 Suresh 22 22000

3 Mahesh 24 24000

The following program to update the table and increase salary of each customer by
5000. Here, SQL%ROWCOUNT attribute is used to determine the number of rows
affected:

20
UNIT V - RDBMS
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
OUTPUT:
3 customers updated
PL/SQL procedure successfully completed.

Record details in customer table after executing above program:

ID NAME AGE SALARY

1 Ramesh 23 25000

2 Suresh 22 27000

3 Mahesh 24 29000

2. Explicit cursors
 An explicit cursor points to the current row in the active set (multiple
rows).
 This allows the program to process one row at a time.
 It is defined by the programmers to gain more control over the context
area.
 It is created on a SELECT statement which returns more than one row.
 Syntax of explicit cursor
CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps –


i. Declaring the cursor
ii. Opening the cursor
iii. Fetching the cursor
iv. Closing the cursor
i. Declaring the Cursor
21
 Declaring the cursor for initializing the memory
UNIT V - RDBMS
 It defines the cursor with a name and the associated
SELECT statement.
 Syntax for explicit cursor declaration: CURSOR name IS
SELECT statement;

For example :-
CURSOR c_customers IS
SELECT id, name, address FROM customers;
ii. Opening the cursor
Opening the cursor for allocating the memory

Make it easy to fetch the rows returned by the SQL statements

into it.
 Syntax for cursor open:
OPEN cursor_name;

For example :-
OPEN c_customers;
iii. Fetching the cursor
Fetching the cursor for retrieving the data
It is used to access one row at a time.
Syntax for cursor fetch:
FETCH cursor_name INTO variable_list;

For example :-
FETCH c_customers INTO c_id, c_name, c_addr;
iv.Closing the cursor
 Closing the cursor to release the allocated memory
 Syntax for cursor close:
Close cursor_name; For example :-
CLOSE c_customers;
Following is a complete example program for
explicit cursor:
DECLARE
c_id customers.id%type; c_name customers.name%type;
c_salary customers.salary%type; CURSOR c_customers is
SELECT id, name, salary FROM customers;
BEGIN
OPEN c_customers; LOOP
FETCH c_customers INTO c_id, c_name, c_salary;

22
UNIT V - RDBMS
EXIT WHEN c_customers%NOTFOUND;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_salary); END LOOP;
CLOSE c_customers; END;
/

OUTPUT:

1 Ramesh 25000

2 Suresh 27000

3 Mahesh 29000

-----------------------------------------------------------------------------------

PL/SQL procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
Syntax of creating a procedure in PL/SQL:
CREATE [OR REPLACE ] PROCEDURE procedure_name (parameter_list)
IS
[declaration statements]
BEGIN
[execution statements]
EXCEPTION
[exception handler]
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 the types of the parameters. Each
parameter can be in either IN, OUT, or INOUT mode.
 IN parameters: This parameter is used for giving input to the subprograms. It is read-
only. Its value will be passed from outside.
23
UNIT V - RDBMS
 OUT parameters: An OUT parameter will be used to return a value outside of the
procedure. It is write-only.
 INOUT parameters: An INOUT parameter is both readable and writable. ie) The
procedure can read and modify it.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone
procedure.

Example code:

CREATE OR REPLACE PROCEDURE display_msg(p_name IN VARCHAR2) IS


BEGIN
dbms_output.put_line(’Hello '|| p_name ||’ Welcome to BCA Dept ');
END;
/

 There are two ways to call above procedure


1. EXEC display_msg(’’);

OR
2. BEGIN
display_msg('DAVID');
END;
/

OUTPUT:
Hello DAVID Welcome to BCA Dept PL/SQL procedure successfully completed.
--------------------------------------------------------------------------------------------------------------------------

FUNCTIONS
 A function is same as a procedure except that it returns a value.
 Creating a Function (Called function)
 A standalone function is created using the CREATE FUNCTION statement.
 The simplified syntax for the CREATE OR REPLACE PROCEDURE statement:-

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. 24
UNIT V - RDBMS
 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and the types of the parameters. Each
parameter can be in either IN, OUT, or INOUT mode.
 IN parameters: This parameter is used for giving input to the subprograms. It is read-
only. Its value will be passed from outside.
 OUT parameters: An OUT parameter will be used to return a value outside of the
function. It is write-only.
 INOUT parameters: An INOUT parameter is both readable and writable. ie) The
function can read and modify it.
 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.

Calling a Function
 When a main 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.
 Syntax to call a function :
function_name(parameter_list) Example:
K = sum(15,12);
Example :

ID NAME AGE SALARY

1 Ramesh 23 25000

2 Suresh 22 27000

3 Mahesh 24 29000

-- Called function coding:


CREATE OR REPLACE FUNCTION totalCustomers RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total FROM customers;

RETURN total;
END;
/

Function created.

25
UNIT V - RDBMS
--Calling function
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/

OUTPUT:
Total no. of Customers : 3
PL/SQL procedure successfully completed.
--------------------------------------------------------------------------------------------------------

PL/SQL PACKAGES
Packages are schema objects that groups logically related PL/SQL types, variables, and
subprograms.
A package will have two mandatory parts −

• Package specification
• Package body or definition

•Package specification:
 The specification is the interface to the package.
 It just DECLARES the types, variables, constants, exceptions, cursors, and
subprograms that can be referenced from outside the package. ( ie, it contains all
information about the content of the package)
 All objects placed in the specification are called public objects. is visible everywhere
in the schema.
 Any subprogram not in the package specification but coded in the package body is
called a
private object.
Syntax for creating package
CREATE [OR specification:
REPLACE] PACKAGE <package_name> IS
<sub_program and public element declaration>
.
.
.

END <package name>

2. Package Body

 It consists of the definition of all the elements that are present in the package
specification.
 It can also have a definition of elements that are not declared in the specification,
these elements are called private elements and can be called only from inside the
26
package.
UNIT V - RDBMS
 syntax for creating package body
(Definition):
CREATE [OR REPLACE] PACKAGE BODY <package_name> IS
<global_declaration part>
<Private element definition>
<sub_program and public element definition>
.
<Package Initialization> END <package_name>

 Using the Package Elements


 The package elements (variables, procedures or functions) are
accessed with the following syntax :
package_name.element_name;

Example for Package:


customer table
EMPNO EMPNAME CITY
-------------------------------------------------------
100 KAVIYA CHENNAI
101 DAVID RAJ KOVAI
102 KAMALA CHENNAI
103 DHANA MADURAI
104 RANI NELLAI
---------------------------------------------------------

Package name : emp_package


1. Package Specification (Package Declaration):

CREATE OR REPLACE PACKAGE emp_package AS


PROCEDURE add_employee(eno employee.empno%TYPE, ename
employee.empname%TYPE,
ecity employee.city%TYPE, esalary employee.salary%TYPE);
END;
/
OUTPUT:

27
UNIT V - RDBMS
Package
created.

2. Package Body Creation (Package definition):

CREATE OR REPLACE PACKAGE BODY emp_package AS


PROCEDURE add_employee(eno employee.empno%TYPE, ename employee.
empname%TYPE,
ecity employee.city%TYPE, esalary employee.salary%TYPE) IS
BEGIN
INSERT INTO employee VALUES(eno,ename,ecity,esalary); END
add_employee;
END emp_package;
/
OUTPUT:
Package body created.

4.Using emp_package in PL/SQL Program:

DECLARE BEGIN
emp_package.add_employee(107,'PALANIVEL','KOVAI',1000);
END;
/

OUTPUT:
Inserted record successfully
PL/SQL procedure successfully completed

5.After using emp_package, Records in employee table:

EMPNO EMPNAME CITY


---------- -------------------- ---------------
100 KAVIYA CHENNAI
101 DAVID RAJ KOVAI
102 KAMALA CHENNAI
103 DHANA RANI MADURAI
104 NELLAI
10 PALANIVEL KOVAI
7
28
UNIT V - RDBMS
-----------------------------------------------------------------------------
Exception Handling
An exception is an error condition during a program execution.
PL/SQL provides a mechanism to handle such exceptions so that normal flow of the program
can be maintained.
Syntax for exception handling:
DECLARE
Exception_name EXCEPTION;
BEGIN
//Exception section
EXCEPTION
WHEN ex_name1 THEN
//Error handling statements
WHEN ex_name2 THEN
-Error handling statements

WHEN Others THEN
//Error handling statements
END;
/

 There are two types of exceptions :


 System-defined exceptions
 User-defined exceptions

System-defined exceptions
 Database server automatically raised the exceptions in case of any internal database
error.
 These exceptions have a unique exception name and error number. These exceptions
are already defined in the ‘STANDARD’ package.
 Examples of system- defined exceptions include ZERO_DIVIDE, NO_DATA_FOUND,
TOO_MANY_ROWS, and STORAGE_ERROR, etc.

Exceptio Oracle SQLCODE Descriptio


n Error n
0653 -653 It is raised when a null object is automatically
ACCESS_INTO_NULL assigned a value.
0 0
NO_DATA_FOUND It is raised when a SELECT INTO statement returns no
0140 +100 rows.
STORAGE_ERROR 3 It is raised when PL/SQL ran out of memory or memory
-650
0650 was corrupted
DUP_VAL_ON_INDEX 00001 -10
0 It is raised when duplicate values are attempted to be
stored in a column with unique index.
INVALID_CURSOR 0100 -100 It is raised when attempts are made to make a cursor
1 1 operation that is not allowed, such as closing an
unopened cursor.
29
UNIT V - RDBMS
TOO_MANY_ROWS It is raised when a SELECT INTO statement returns
01422
-1422 more than one row.

Example for system-defined exception handling:

DECLARE
s_rollNo students.rollNo%type := 10; s_name students.name%type;
s_address students.address%type; BEGIN
SELECT rollNo, name, address FROM students WHERE rollNo = s_rollNo;
dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' || s_address);
EXCEPTION

WHEN no_data_found THEN dbms_output. -- Exception


put_line('No such student!'); handling
WHEN others THEN --Exception
dbms_output.put_line('Error!'); handling
END;
/

OUTPUT:
No such student!

User-defined exceptions
The programmer can create their own exception and handle them.
They can be created at a subprogram level in the declaration part.
These exceptions are visible only in that subprogram.
The exception that is defined in the package specification is public exception,
and it is visible wherever the package is accessible.
Database exceptions can be raised explicitly by the programmer by using
RAISE command.
Syntax of raising an exception:
DECLARE
exception_name EXCEPTION; BEGIN
IF condition THEN
RAISE exception_name; END IF;
EXCEPTION
WHEN exception_name THEN statement;
END;
/

30
UNIT V - RDBMS
Example for user-defined exception handling:

DECLARE
s_rollNo students.rollNo%type := &ss_rollNo; s_name students.name%type;
s_address students.address%type;
-- user defined exception ex_invalid_rollNo EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_rollNo;
ELSE
SELECT rollNo, name, address FROM students WHERE rollNo = s_rollNo; dbms_output.put_line(s_rollNo || ' ' ||
s_name || ' ' || s_address);
END IF;
EXCEPTION
WHEN ex_invalid_rollNo THEN
dbms_output.put_line('rollNo must be greater than zero!');
WHEN no_data_found THEN dbms_output.put_line('No such student!');
WHEN others THEN dbms_output.put_line('Error!');
END;
/

Output:
(Enter a value less than 0 for rollNo): -12

rollNo must be greater than zero!

----------------------------------------------------------------------------------------------------------------------------

TRIGGERS
 Triggers are stored programs, which are automatically executed or fired when some events
occur.
 Triggers are 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 could 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

31
UNIT V - RDBMS
 Synchronous replication of
tables
 Imposing security
authorizations
 Preventing invalid
transactions
CREATE [OR REPLACE ] TRIGGER trigger_name
Creating a trigger {BEFORE | AFTER | INSTEAD OF }
Syntax for creating trigger:
{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;
/

Here,

CREATE [OR REPLACE] TRIGGER trigger_name - It creates or replaces an existing trigger with the
trigger_name.
{BEFORE | AFTER | INSTEAD OF} - This specifies when the trigger would 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 would be updated.
[ON table_name] - This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] - This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
[FOR EACH ROW] - This specifies a row level trigger, i.e., the trigger would 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 for Trigger:
bank_customer table
ACCNO CUSTNAME ACCTYPE BALANCEAMT
------ --------------- -------------------------------------------------- ----------
100 kamal savings 12500
101 David raj savings 20000
32
UNIT V - RDBMS
102 John current 85000
103 Backia savings 10500

------------------------------------------------------------------------------------

Trigger name : transaction_balance_check (Lab exercise)

CREATE OR REPLACE TRIGGER transaction_balance_check BEFORE INSERT ON


bank_transaction FOR EACH ROW
DECLARE
v_balance number(10); BEGIN
SELECT balanceamt INTO v_balance FROM bank_customer WHERE accno = :new.
accno;

IF(:new.transtype = 'debit') then


IF(v_balance < :new.transamt) THEN
RAISE_APPLICATION_ERROR(-20001,'----------Insufficient Balance!!-------------'); END IF;
v_balance := v_balance - :new.transamt;
ELSE
v_balance := v_balance + :new.transamt; END IF;
UPDATE bank_customer
SET balanceamt = v_balance WHERE accno = :new.accno;
END;
/

Insert Query after creating Trigger transaction_balance_check

INSERT INTO bank_transaction VALUES(15,103,to_date('11-09-2022','dd-mm-yyyy'),


'debit',12000);

OUTPUT:
INSERT INTO bank_transaction VALUES(15,103,to_date('11-09-2022','dd-mm-yyyy'),
'debit',12000)
*
ERROR at line 1:
ORA-20001: ----------Insufficient Balance!!-------------
ORA-06512: at "SYSTEM.TRANSACTION_BALANCE_CHECK", line 9
ORA-04088: error during execution of trigger 'SYSTEM.
TRANSACTION_BALANCE_CHECK‘

-----------------------UNIT V Completed -----------------------

UNIT V - RDBMS 33

You might also like