RDBMS Unit 4,5 Notes
RDBMS Unit 4,5 Notes
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.
Scalar
1
Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.
Reference
4
Pointers to other data items.
PL/SQL Scalar Data Types and Subtypes come under the following categories −
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.
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −
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)
DECLARE
num1 INTEGER;
num2 REAL;
num3 DOUBLE PRECISION;
BEGIN
null;
END;
/
PL/SQL procedure successfully completed
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
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)
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.
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 −
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.
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 has three categories of control statements: conditional selection statements, loop
statements and sequential control statements.
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:
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
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:
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.
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
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
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
%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
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.
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 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 involves accessing one row at a time. For example, we will fetch rows from
the above-opened cursor as follows −
Closing the cursor means releasing the allocated memory. For example, we will close the above-
opened cursor as follows −
CLOSE c_customers;
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:
7.EXCEPTIONS IN PL/SQL
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
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!
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.
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when the
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 −
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
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.
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.
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:
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
PL/SQL provides a number of built-in functions for working with TABLE data types, including:
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
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
1 SQL 1 10
2 SQL 2 50
3 HTML5 10
DECLARE
course_name name;
BEGIN
LOOP
END LOOP;
END LOOP;
END;
/
Output