0% found this document useful (0 votes)
34 views25 pages

RDBMS Unit 4,5 Notes

The document provides an overview of PL/SQL, Oracle's procedural language extension to SQL, detailing its structure, including blocks, sections, and types of statements. It covers variable declaration, data types, control statements, and transaction control language (TCL) commands, emphasizing the integration of SQL within PL/SQL. Additionally, it explains arithmetic operators, comments, and the differences between anonymous and named blocks.

Uploaded by

ganesh8074c
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)
34 views25 pages

RDBMS Unit 4,5 Notes

The document provides an overview of PL/SQL, Oracle's procedural language extension to SQL, detailing its structure, including blocks, sections, and types of statements. It covers variable declaration, data types, control statements, and transaction control language (TCL) commands, emphasizing the integration of SQL within PL/SQL. Additionally, it explains arithmetic operators, comments, and the differences between anonymous and named blocks.

Uploaded by

ganesh8074c
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/ 25

RDBMS

III BCA
Unit IV
1.Fundamentals of PL/SQL:

PL/SQL is Oracle's procedural language extension to SQL. PL/SQL allows you to mix SQL
statements with procedural constructs.

In PL/SQL, All statements are classified into units that is called Blocks. PL/SQL blocks can
include variables, SQL statements, loops, constants, conditional statements and exception
handling. Blocks can also build a function or a procedure or a package.

The Declaration section: Code block start with a declaration section, in which
memory variables, constants, cursors and other oracle objects can be declared and if required
initialized.
The Begin section: Consist of set of SQL and PL/SQL statements, which describe processes
that have to be applied to table data. Actual data manipulation, retrieval, looping and branching
constructs are specified in this section.
The Exception section: This section deals with handling errors that arise during execution
data manipulation statements, which make up PL/SQL code block. Errors can arise due to
syntax, logic and/or validation rule.
The End section: This marks the end of a PL/SQL block.
Broadly, PL/SQL blocks are two types: Anonymous blocks and Named blocks are as follows:

i. Anonymous blocks: In PL/SQL, That’s blocks which is not have header are known as
anonymous blocks.
DECLARE

a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' || c);
END;
/
Output:
Maximum number in 10 and 100: 100

ii. Named blocks: That’s PL/SQL blocks which having header or labels are known as Named
blocks.

2.COMMENTS IN PL/SQL:

PL/SQL supports two comment styles: single-line and multi-line. A double hyphen ( - - )
anywhere on a line (except within a character literal) turns the rest of the line into a comment.
Multi-line comments begin with a slash-asterisk ( /* ) and end with an asterisk-slash ( */ ).

3.PL/SQL DataTypes:

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.

Large Object (LOB)


2 Pointers to large objects that are stored separately from other data items, such as text, graphic
images, video clips, and sound waveforms.
Composite
3 Data items that have internal components that can be accessed individually. For example,
collections and records.

Reference
4
Pointers to other data items.

PL/SQL Scalar Data Types and Subtypes

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

S.No Date Type & Description

Numeric
1
Numeric values on which arithmetic operations are performed.

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

Boolean
3
Logical values on which logical operations are performed.

Datetime
4
Dates and times.

PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype
called INTEGER. You can use the subtypes in your PL/SQL program to make the data types
compatible with data types in other programs while embedding the PL/SQL code in another
program, such as a Java program.

PL/SQL Numeric Data Types and Subtypes

Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −

S.No Data Type & Description

PLS_INTEGER
1
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

BINARY_INTEGER
2
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number

NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including)
1.0E126. A NUMBER variable can also represent 0

DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits

DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits

NUMERIC(pre, secale)
8
Floating type with maximum precision of 38 decimal digits

DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits (approximately
38 decimal digits)

FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)

INT
11
ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER
12
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

SMALLINT
13
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal
digits)

Following is a valid declaration −

DECLARE
num1 INTEGER;
num2 REAL;
num3 DOUBLE PRECISION;
BEGIN
null;
END;
/
PL/SQL procedure successfully completed

PL/SQL Character Data Types and Subtypes

Following is the detail of PL/SQL pre-defined character data types and their sub-types −

S.No Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by
PL/SQL

NCHAR
4
Fixed-length national character string with maximum size of 32,767 bytes

NVARCHAR2
5
Variable-length national character string with maximum size of 32,767 bytes

LONG
6
Variable-length character string with maximum size of 32,760 bytes

LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by
PL/SQL

ROWID
8
Physical row identifier, the address of a row in an ordinary table

UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)

PL/SQL Boolean Data Types

The BOOLEAN data type stores logical values that are used in logical operations. The logical
values are the Boolean values TRUE and FALSE and the value NULL.

PL/SQL Datetime and Interval Types


The DATE datatype is used to store fixed-length datetimes, which include the time of day in
seconds since midnight.

4.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.

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 either of the following −

 The DEFAULT keyword


 The assignment operator

Anchored Declaration in PL/SQL

PL/SQL supports anchored declarations, using %TYPE and %ROWTYPE . This lets PL/SQL
directly express the intention that a variable or formal parameter has the same data type as a table
column. Using anchored declarations ensures code clarity, reliability, and maintainability.

Assignment operator

Assignment operator for assigning a value. The value on the right is assigned to the variable on
left. Unlike the = operator, := can always be used to assign a value to a variable. This operator
works with both user-defined variables and local variables.

Bind variables

Bind variables are variables you create in SQL*Plus and then reference in PL/SQL. If you create
a bind variable in SQL*Plus, you can use the variable as you would a declared variable in your
PL/SQL subprogram and then access the variable from SQL*Plus.

Substitution variable:

Substitution variables, for repeated use in a single script by using the SQL*Plus DEFINE
command.

DEFINE L_NAME = "SMITH" (CHAR)

5.Arithmetic Operators in PL/SQL:


Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

Exponentiation operator, raises one operand to the power of A ** B will give


**
other 100000

Example

BEGIN
dbms_output.put_line( 10 + 5);
dbms_output.put_line( 10 - 5);
dbms_output.put_line( 10 * 5);
dbms_output.put_line( 10 / 5);
dbms_output.put_line( 10 ** 5);
END;
/

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

15
5
50
2
100000

PL/SQL procedure successfully completed.

6.PL/SQL Control Statements

PL/SQL has three categories of control statements: conditional selection statements, loop
statements and sequential control statements.

PL/SQL categories of control statements are:


 Conditional selection statements, which run different statements for different data
values.
The conditional selection statements are IF and CASE.
 Loop statements, which run the same statements with a series of different data values.
The loop statements are the basic LOOP, FOR LOOP, and WHILE LOOP.
The EXIT statement transfers control to the end of a loop. The CONTINUE statement
exits the current iteration of a loop and transfers control to the next iteration.
Both EXIT and CONTINUE have an optional WHEN clause, where you can specify a
condition.
 Sequential control statements, which are not crucial to PL/SQL programming.

Conditional Selection Statements


The conditional selection statements, IF and CASE, run different statements for different data
values.
The IF statement either runs or skips a sequence of one or more statements, depending on a
condition. The IF statement has these forms:
 IF THEN
 IF THEN ELSE
 IF THEN ELSIF
The CASE statement chooses from a sequence of conditions, and runs the corresponding
statement. The CASE statement has these forms:
 Simple, which evaluates a single expression and compares it to several potential values.
 Searched, which evaluates multiple conditions and chooses the first one that is true.
The CASE statement is appropriate when a different action is to be taken for each alternative.

Topics

 IF THEN Statement
 IF THEN ELSE Statement
 IF THEN ELSIF Statement
 Simple CASE Statement
 Searched CASE Statement

IF THEN Statement
The IF THEN statement either runs or skips a sequence of one or more statements, depending on
a condition.
The IF THEN statement has this structure:
Copy
IF condition THEN
statements
END IF;
IF-THEN-ELSE Statement

The second form of IF statement adds the keyword ELSE followed by an alternative sequence of
statements, as follows:

IF condition THEN
sequence_of_statements1
ELSE
sequence_of_statements2
END IF;

IF-THEN-ELSIF Statement

Sometimes you want to select an action from several mutually exclusive alternatives. The third
form of IF statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions,
as follows:

IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_statements3
END IF;

CASE Statement

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. (Recall from Chapter 2 that a selector is an expression whose value is used
to select one of several alternatives.) To compare the IF and CASE statements, consider the
following code that outputs descriptions of school grades:

IF grade = 'A' THEN


dbms_output.put_line('Excellent');
ELSIF grade = 'B' THEN
dbms_output.put_line('Very Good');
ELSIF grade = 'C' THEN
dbms_output.put_line('Good');
ELSIF grade = 'D' THEN
dbms_output. put_line('Fair');
ELSIF grade = 'F' THEN
dbms_output.put_line('Poor');
ELSE
dbms_output.put_line('No such grade');
END IF;

Searched CASE Statement

PL/SQL also provides a searched CASE statement, which has the form:

[<<label_name>>]
CASE
WHEN search_condition1 THEN sequence_of_statements1;
WHEN search_condition2 THEN sequence_of_statements2;
...
WHEN search_conditionN THEN sequence_of_statementsN;
[ELSE sequence_of_statementsN+1;]
END CASE [label_name];

7.LOOPING STATEMENTS

LOOP statements let you execute a sequence of statements multiple times. There are three forms
of LOOP statements: LOOP, WHILE-LOOP, and FOR-LOOP.

LOOP

The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a sequence
of statements between the keywords LOOP and END LOOP, as follows:

LOOP
sequence_of_statements
END LOOP;

EXIT

The EXIT statement forces a loop to complete unconditionally. When an EXIT statement is
encountered, the loop completes immediately and control passes to the next statement. An
example follows:

LOOP
...
IF credit_rating < 3 THEN
...
EXIT; -- exit loop immediately
END IF;
END LOOP;
WHILE-LOOP

The WHILE-LOOP statement associates a condition with a sequence of statements enclosed by


the keywords LOOP and END LOOP, as follows:

WHILE condition LOOP


sequence_of_statements
END LOOP;

FOR-LOOP

Whereas the number of iterations through a WHILE loop is unknown until the loop completes,
the number of iterations through a FOR loop is known before the loop is entered. FOR loops
iterate over a specified range of integers. The range is part of an iteration scheme, which is
enclosed by the keywords FOR and LOOP. A double dot (..) serves as the range operator. The
syntax follows:

FOR counter IN [REVERSE] lower_bound..higher_bound LOOP


sequence_of_statements
END LOOP;

GOTO Statement

The GOTO statement branches to a label unconditionally. The label must be unique within its
scope and must precede an executable statement or a PL/SQL block. When executed,
the GOTO statement transfers control to the labeled statement or block. In the following
example, you go to an executable statement farther down in a sequence of statements:

BEGIN
...
GOTO insert_row;
...
<<insert_row>>
INSERT INTO emp VALUES ...
END;

8.SQL IN PL/SQL:

PL/SQL is a procedural language designed specifically to embrace SQL statements within its
syntax. PL/SQL program units are compiled by the Oracle Database server and stored inside the
database. And at run-time, both PL/SQL and SQL run within the same server process, bringing
optimal efficiency.

9.DML IN PL/SQL

From within any PL/SQL block of code you can execute DML statements (INSERTs,
UPDATEs, DELETEs, and MERGEs) against any and all tables and views to which you have
access.

 INSERT Statement
The INSERT statement inserts rows into an existing table.
 UPDATE Statement
The UPDATE statement updates (changes the values of) a set of existing table rows.
 DELETE Statement
The DELETE statement deletes rows from a table.

10.Transaction Control Statements(TCL):

Transaction Control Language (TCL) is a critical component of SQL used to manage


transactions and ensure data integrity in relational databases. By using TCL commands, we
can control how changes to the database are committed or reverted, maintaining consistency
across multiple operations.

In PL/SQL, Transaction Control Language (TCL) statements are used to manage changes made
by Data Manipulation Language (DML) statements. Here are the main TCL statements:

1. COMMIT: Saves all the changes made during the current transaction to the database.
2. ROLLBACK: Undoes all the changes made during the current transaction.
3. SAVEPOINT: Sets a point within a transaction to which you can later roll back.
4. ROLLBACK TO: Rolls back the transaction to a specified savepoint.
5. SET TRANSACTION: Sets the properties of the current transaction, such as isolation level.
UNIT V

PL/SQL CURSORS & EXCEPTIONS:

1.Cursors in PL/SQL
A cursor in PL/SQL is a pointer to a context area that stores the result set of a query. Cursors
allow you to retrieve data one row at a time from the result set, unlike other SQL commands that
operate on all rows at once

Types of Cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed.
These cursors are managed internally by Oracle and are associated with DML statements like
INSERT, UPDATE, and DELETE. Implicit cursors are simpler to code but offer less control
over the execution cycle

Explicit Cursors
Explicit cursors are defined by the programmer in the declaration section of a PL/SQL block.
They are created on a SELECT statement that returns more than one row. Explicit cursors
provide more control over the execution cycle, allowing you to open, fetch, and close the cursor
explicitly

Using Explicit Cursors

To use an explicit cursor, follow these steps:


1. Declare the Cursor: Define the cursor with a name and the associated SELECT
statement. CURSOR cursor_name IS select_statement;
2. Open the Cursor: Allocate memory for the cursor and make it ready for fetching
rows. OPEN cursor_name;
3. Fetch the Cursor: Retrieve data from the cursor into PL/SQL variables or records. FETCH
cursor_name INTO variables;
4. Close the Cursor: Release the allocated memory. CLOSE cursor_name;

Cursor Attributes

Cursors have several attributes that provide information about the state of the cursor:
 %ISOPEN: Returns TRUE if the cursor is open.
 %FOUND: Returns TRUE if the last fetch returned a row.
 %NOTFOUND: Returns TRUE if the last fetch did not return a row.
 %ROWCOUNT: Returns the number of rows fetched

2.Implicit Cursors

S.No Attribute & Description

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

%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE,
2
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.

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 |
+----+----------+-----+-----------+----------+
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;
/
6 customers selected

PL/SQL procedure successfully completed.

3.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.

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;

4.Cursor FOR LOOP


The cursor FOR LOOP statement implicitly declares its loop index as a record variable of the
row type that a specified cursor returns, and then opens a cursor.
With each iteration, the cursor FOR LOOP statement fetches a row from the result set into the
record. When there are no more rows to fetch, the cursor FOR LOOP statement closes the cursor.
The cursor also closes if a statement inside the loop transfers control outside the loop or raises an
exception.

cursor_for_loop_statement
record
Name for the loop index that the cursor FOR LOOP statement implicitly declares as
a %ROWTYPE record variable of the type that cursor or select_statement returns.

cursor
Name of an explicit cursor (not a cursor variable) that is not open when the cursor FOR LOOP is
entered.

actual_cursor_parameter
Actual parameter that corresponds to a formal parameter of cursor.

select_statement
SQL SELECT statement (not PL/SQL SELECT INTO statement). For select_statement, PL/SQL
declares, opens, fetches from, and closes an implicit cursor.
5.SELECT FOR UPDATE:
The syntax for the SELECT FOR UPDATE statement in Oracle/PLSQL is:

CURSOR cursor_name IS select_statement FOR UPDATE [OF column_list] [NOWAIT];

6.WHERE CURRENT OF CLAUSE:

If you plan on updating or deleting records that have been referenced by a


SELECT FOR UPDATE statement, you can use the WHERE CURRENT OF statement. Syntax
The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either: UPDATE
table_name SET set_clause WHERE CURRENT OF cursor_name; OR DELETE FROM
table_name

7.EXCEPTIONS IN PL/SQL

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

The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others
THEN −

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

Example

Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −

DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

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

No such customer!

PL/SQL procedure successfully completed.

The above program displays the name and address of a customer whose ID is given. Since there

is no customer with ID value 8 in our database, the program raises the run-time
exception NO_DATA_FOUND, which is captured in the EXCEPTION block.

Raising Exceptions

Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

You can use the above syntax in raising the Oracle standard exception or any user-defined
exception. In the next section, we will give you an example on raising a user-defined exception.
You can raise the Oracle standard exceptions in a similar way.

User-defined Exceptions

PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

The syntax for declaring an exception is −

DECLARE
my-exception EXCEPTION;

Example

The following example illustrates the concept. This program asks for a customer ID, when the

user enters an invalid ID, the exception invalid_id is raised.

DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

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

Enter value for cc_id: -6 (let's enter a value -6)


old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

Pre-defined Exceptions

PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised
when a SELECT INTO statement returns no rows. The following table lists few of the important
pre-defined exceptions −

Oracle
Exception SQLCODE Description
Error

It is raised when a null object is


ACCESS_INTO_NULL 06530 -6530
automatically assigned a value.

It is raised when none of the


choices in the WHEN clause of
CASE_NOT_FOUND 06592 -6592
a CASE statement is selected,
and there is no ELSE clause.
It is raised when a program
attempts to apply collection
methods other than EXISTS to
an uninitialized nested table or
COLLECTION_IS_NULL 06531 -6531
varray, or the program attempts
to assign values to the elements
of an uninitialized nested table
or varray.

It is raised when duplicate


values are attempted to be
DUP_VAL_ON_INDEX 00001 -1
stored in a column with unique
index.

It is raised when attempts are


made to make a cursor
INVALID_CURSOR 01001 -1001 operation that is not allowed,
such as closing an unopened
cursor.

8.PL/SQL Record

A PL/SQL record is a composite data structure that consists of multiple fields; each has its own
value. The following picture shows an example record that includes first name, last name, email,
and phone number:

PL/SQL record helps you simplify your code by shifting from field-level to record-level
operations.

PL/SQL has three types of records: table-based, cursor-based, and programmer-defined. Before
using a record, you must declare it.

What is a PL/SQL Record


A PL/SQL record is a composite data structure that is a group of related data stored
in fields. Each field in the PL/SQL record has its own name and data type.

Declaring a PL/SQL Record

PL/SQL provides three ways to declare a record: table-based record, cursor-based


record and programmer-defined records.

Declaring Table-based Record

To declare a table-based record you use a table name with %ROWTYPE attribute. The fields of

the PL/SQL record has the same name and data type as the column of the table.

The following illustrates table-based record declaration:

DECLARE
table_based_record table_name%ROWTYPE;Code language: SQL (Structured Query
Language) (sql)

After having the table-based record, you can use it in various ways, for example in SQL
SELECT statement as follows:

SET SERVEROUTPUT ON SIZE 1000000;


DECLARE
r_emp employees%ROWTYPE;
n_emp_id employees.employee_id%TYPE := 200;
BEGIN
SELECT *
INTO r_emp
FROM employees
WHERE employee_id = n_emp_id;
-- print out the employee's first name
DBMS_OUTPUT.PUT_LINE(r_emp.first_name);
END;
/Code language: SQL (Structured Query Language) (sql)

In the above example:

 First, we defined a record based on employees table in HR sample database.


 Second, we used the SELECT statement to retrieve the employee information of the
employee id 200 and populate the data into the r_emp record .
 Third, we print out the first name of the selected employee from the r_emp employee
record.
 Once you define the record type, you can declare a record based on the record type as
follows:
 record_name type_name;

9.PL/SQL TABLE

One of the powerful features of Oracle PL/SQL is the TABLE data type, which allows
developers to work with collections of data in a flexible and efficient way.

A TABLE data type in PL/SQL is essentially an array of values of the same data type. It can be
used to store data of any primitive data type, including numeric, character, Boolean, and
date/time data. Additionally, it can also be used to store composite data types, such as records or
objects.

Syntax

The syntax for defining a TABLE data type in PL/SQL is as follows:

TYPE table_name IS TABLE OF data_type;

PL/SQL provides a number of built-in functions for working with TABLE data types, including:

COUNT: Returns the number of elements in a TABLE


EXTEND: Adds one or more elements to the end of a TABLE
TRIM: Removes one or more elements from the end of a TABLE
EXISTS: Returns true if a specified element exists in a TABLE

10.PL/SQL Varrays

Oracle PL/SQL Varrays are variable-size arrays that can hold a fixed number of elements. Oracle
PL/SQL Varrays are a great way to store data in a fixed-size array. They are easy to create and
use, and offer a number of functions for adding, retrieving, and removing data.

Syntax

The syntax for creating a Varray is:

TYPE type_name IS VARRAY(size)

OF element_type [NOT NULL];

Creating a PL/SQL Varray is simple and only requires two steps. First, you need to create the
TYPE. This is done by using the TYPE keyword, followed by the name of the Varray, and then
the keyword IS VARRAY. Following this is the keyword OF, which specifies the data type of
the elements that will be stored in the Varray.

Example
Course table

COURSE_ID NAME PRICE

1 SQL 1 10

2 SQL 2 50

3 HTML5 10

Varrays (variable-size arrays)

DECLARE

TYPE name IS VARRAY(250) OF VARCHAR2(25);

course_name name;

BEGIN

course_name := name('SQL 1', 'SQL 2', 'HTML5');

FOR i IN 1 .. course_name.COUNT LOOP

FOR x IN (SELECT * FROM course WHERE name=course_name(i))

LOOP

dbms_output.put_line('ID: '||x.course_id||' - Name: '||x.name);

END LOOP;

END LOOP;

END;

/
Output

ID: 1 – Name: SQL 1

ID: 2 – Name: SQL 2

ID: 3 – Name: HTML5

You might also like