Unit 5
Unit 5
Unit 5
– Data Types – Other Data Types – Variable Declaration – Assignment operation –Arithmetic
operators. Control Structures and Embedded SQL: Control Structures – Nested Blocks –
SQL in PL/SQL – Data Manipulation – Transaction Control statements. PL/SQL Cursors
and Exceptions: Cursors – Implicit Cursors, Explicit Cursors and Attributes – Cursor FOR
loops – SELECT…FOR UPDATE – WHERE CURRENT OF clause – Cursor with
Parameters – Cursor Variables – Exceptions – Types of Exception
PL/SQL
Combines SQL and Procedural Logic: PL/SQL allows you to write complex database
applications by integrating SQL with procedural programming constructs like loops and
conditionals.
Block Structure: PL/SQL code is organized into blocks, which can contain declarations,
executable commands, and exception handling, improving readability and manageability.
Variables and Data Types: It supports variables and allows for the use of different data
types, enabling developers to store and manipulate data effectively.
Error Handling: PL/SQL provides robust error handling through exception blocks, allowing
developers to manage runtime errors gracefully.
Stored Procedures and Functions: You can create reusable code in the form of stored
procedures and functions, enhancing modularity and efficiency in database operations.
HISTORY OF PL/SQL:
Purpose: It was developed to allow developers to write more complex and efficient
database applications by integrating SQL with procedural programming features.
Evolution: Over the years, PL/SQL has evolved with each Oracle Database release,
introducing new features such as object-oriented programming, improved performance, and
enhanced error handling.
Standardization: PL/SQL became widely adopted, leading to its use in various Oracle-
based applications and systems, establishing it as a standard for database programming.
Block Structure: PL/SQL programs are organized into blocks, which consist of a declarative
section (for defining variables), an executable section (for logic and SQL statements), and an
exception-handling section (for error management).
Variables and Data Types: PL/SQL supports various data types, including scalar types (like
NUMBER, VARCHAR2) and composite types (like RECORD and TABLE), allowing for
efficient data manipulation.
Control Structures: It includes control structures such as loops (FOR, WHILE), conditionals
(IF, CASE), and branching statements (GOTO), enabling structured and flexible
programming.
Procedures and Functions: PL/SQL allows the creation of stored procedures and functions,
promoting code reusability, modularity, and better organization of business logic within the
database
A PL/SQL block consists of three main sections: the Declaration section, the Executable
section, and the Exception handling section.
Declaration Section: This is where you define variables, constants, and cursors. It starts with
the keyword DECLARE and allows for data type specifications.
Executable Section: This section contains the actual PL/SQL code that executes SQL
statements and procedural logic. It starts with the keyword BEGIN.
Exception Handling Section: This section handles errors that occur during execution. It
starts with the keyword EXCEPTION and allows for the specification of error handling
routines.
COMMENTS
Comments in PL/SQL are used to annotate code and improve readability. Here are two key
points:
Types of Comments: PL/SQL supports two types of comments: single-line comments (using
--) and multi-line comments (enclosed between /* and */), allowing developers to provide
explanations or notes within the code.
Purpose: Comments are essential for documenting the code, clarifying complex logic, and
helping other developers understand the intent and functionality without affecting the code’s
execution.
DATA TYPE
A data type in PL/SQL defines the kind of data that a variable can hold. It specifies the nature
of the data (e.g., numeric, character, date) and determines how much storage space it requires
and the operations that can be performed on it.
RECORD: A collection of fields, each with its own data type, similar to a structured record.
REF CURSOR: A pointer to a cursor that can be used to fetch multiple rows of data
dynamically.
BLOB: For binary large objects, used to store unstructured binary data (e.g., images).
CLOB: For character large objects, used to store large text data.
User-defined types
OBJECT: Allows the creation of complex data types that can contain multiple attributes and
methods, supporting object-oriented programming concepts.
In addition to the commonly used data types in PL/SQL, here are some other data types you
may encounter:
NVARCHAR2: For variable-length national character set strings, useful for multilingual
data.
INTERVAL:
INTERVAL DAY TO SECOND: Represents a period of time in days, hours, minutes, and
seconds.
XML Type:
Used to store XML data and allows for XML-specific operations and queries.
BFILE:
A data type for storing binary files located outside the database, enabling access to large files
stored in the filesystem.
PL/SQL COLLECTIONS:
These additional data types enhance the capability of PL/SQL for handling diverse data
scenarios.
VARIABLE DECLARATION
In PL/SQL, variable declaration is essential for defining variables that store data. Here’s how
it works:
Basic Syntax: A variable is declared in the declarative part of a PL/SQL block using the
following syntax:
DECLARE
ASSIGNMENT OPERATIONS
In PL/SQL, assignment operations are used to assign values to variables. Here are the key
points:
Basic Syntax: The assignment operation uses the := operator. For example:
V_variable := value;
DECLARE
V_emp_id NUMBER;
V_emp_name VARCHAR2(50);
BEGIN
END;
ARITHMETIC OPERATORS
In PL/SQL, arithmetic operators are used to perform mathematical calculations. Here are the
key arithmetic operators:
Subtraction (-): Subtracts the second numeric value from the first.
Example Usage:
DECLARE
V_b NUMBER := 3;
V_sum NUMBER;
V_diff NUMBER;
V_prod NUMBER;
V_quot NUMBER;
V_rem NUMBER;
BEGIN
END;
Control Structures
PL/SQL control structures allow you to control the flow of execution in your programs. Here
are the main types of control structures in PL/SQL, along with their syntax and examples:
1.Conditional Statements
IF Statement
Syntax
IF condition THEN
Statements;
ELSIF another_condition THEN
Statements;
ELSE
Statements;
END IF;
Example:
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Grade: A’);
DBMS_OUTPUT.PUT_LINE(‘Grade: B’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘Grade: C’);
END IF;
END;
CASE Statement
Syntax:
CASE expression
Statements;
WHEN value2 THEN
Statements;
ELSE
Statements;
END CASE;
Example:
DECLARE
V_day NUMBER := 3;
BEGIN
CASE v_day
END CASE;
END;
LOOPING STATEMENTS
LOOP Statement
The LOOP statement repeats a block of code indefinitely until an explicit EXIT statement is
reached.
Syntax
LOOP
Statements;
EXIT WHEN condition;
END LOOP;
Example:
DECLARE
V_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(‘Counter: ‘ || v_counter);
V_counter := v_counter + 1;
END LOOP;
END;
WHILE Loop
Syntax:
Statements;
END LOOP;
Example:
DECLARE
V_counter NUMBER := 1;
BEGIN
V_counter := v_counter + 1;
END LOOP;
END;
FOR Loop
Syntax:
Statements;
END LOOP;
Example:
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Counter: ‘ || v_counter);
END LOOP;
END;
Exception Handling
EXCEPTION BLOCK
The EXCEPTION block is used to handle errors that occur during execution.
Syntax:
BEGIN
Statements;
EXCEPTION
END;
Example
DECLARE
V_number NUMBER := 0;
V_result NUMBER;
BEGIN
EXCEPTION
END;
NESTED BLOCKS
In PL/SQL, nested blocks allow you to define a block of code within another block. This can
help organize your code, manage scope, and improve readability. Here’s a detailed
explanation along with examples.
Syntax of Nested Blocks
The syntax for a nested block is straightforward. A block can contain another block defined
within it.
DECLARE
BEGIN
DECLARE
BEGIN
END;
END;
DECLARE
BEGIN
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Inner Variable: ‘ || v_inner_var);
END;
END;
Explanation
Inner Block: Declares v_inner_var, accesses the outer variable, performs a calculation, and
prints the results.
Variable Scope: The inner block can access variables declared in the outer block, but the
reverse is not true.
In PL/SQL, transaction control statements are used to manage the changes made by Data
Manipulation Language (DML) operations like INSERT, UPDATE, and DELETE. These
statements ensure data integrity and control the behavior of transactions in the database. Here
are the key transaction control statements in PL/SQL:
COMMIT
The COMMIT statement saves all the changes made during the current transaction to the
database. Once a commit is performed, the changes cannot be rolled back.
Syntax:
COMMIT;
Example:
BEGIN
INSERT INTO employees (id, name, salary) VALUES (1, ‘John Doe’, 50000);
COMMIT; -- Saves the changes
END;
ROLLBACK
The ROLLBACK statement undoes all the changes made during the current transaction. This
is useful if an error occurs or if you want to discard changes.
Syntax:
ROLLBACK;
Example:
BEGIN
END;
SAVEPOINT
A SAVEPOINT allows you to set a point within a transaction to which you can later roll
back. This provides more granular control compared to rolling back the entire transaction.
Syntax:
SAVEPOINT savepoint_name;
Example:
BEGIN
INSERT INTO employees (id, name, salary) VALUES (1, ‘John Doe’, 50000);
SAVEPOINT before_update;
Changes after the savepoint will be undone, but previous changes will be kept
COMMIT; -- Commit the changes before the savepoint
END;
In PL/SQL, a cursor is a database object that allows you to retrieve, manipulate, and manage
data row by row. Cursors are particularly useful when dealing with multiple rows returned by
a query. There are two types of cursors: implicit cursors and explicit cursors.
Implicit Cursors
Implicit cursors are automatically created by PL/SQL when a SQL statement is executed. You
do not need to explicitly define them.
Example
DECLARE
V_emp_name employees.name%TYPE;
BEGIN
INSERT INTO employees (id, name, salary) VALUES (1, ‘John Doe’, 50000);
END;
Explicit Cursors
Explicit cursors provide more control over the context and allow you to fetch multiple rows.
You must define them explicitly.
Declare the Cursor: Define the SQL query that the cursor will execute.
Open the Cursor: Establish the context for the cursor and execute the query.
Fetch the Rows: Retrieve rows one at a time from the cursor.
Example
DECLARE
CURSOR emp_cursor IS
V_emp_name employees.name%TYPE;
V_emp_salary employees.salary%TYPE;
BEGIN
LOOP
END LOOP;
END;
Cursor Attributes:
%NOTFOUND: Returns TRUE if the last fetch failed (no more rows).
You can simplify cursor handling by using a FOR loop, which automatically opens, fetches,
and closes the cursor.
BEGIN
FOR emp_record IN (SELECT name, salary FROM employees WHERE salary > 40000)
LOOP
END LOOP;
END;