Unit 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

PL/SQL:A Programming Language: History – Fundamentals – Block Structure – Comments

– 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

PL/SQL (Procedural Language/Structured Query Language) is Oracle’s procedural extension


for 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:

Introduction: PL/SQL was introduced by Oracle Corporation in 1991 as part of Oracle


Database Version 6 to enhance SQL with procedural capabilities.

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.

Current Status: Today, PL/SQL remains a critical component of Oracle databases,


supporting enterprise applications and data management tasks.

FUNDAMENTAL POINTS ABOUT PL/SQL:

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.

Exception Handling: PL/SQL provides a robust mechanism for handling exceptions,


allowing developers to manage errors gracefully with predefined and user-defined exceptions.

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

BLOCK STRUCTURE OF PL/SQL:

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.

In PL/SQL, data types can be categorized into several types:

Scalar Data Types:

NUMBER: For numeric values, including integers and decimals.

VARCHAR2: For variable-length character strings.

CHAR: For fixed-length character strings.


DATE: For date and time values.

BOOLEAN: For true/false values (only usable in PL/SQL, not SQL).

Composite data types:

RECORD: A collection of fields, each with its own data type, similar to a structured record.

TABLE: An indexed collection of elements, allowing for dynamic array-like structures

Reference data types:

REF CURSOR: A pointer to a cursor that can be used to fetch multiple rows of data
dynamically.

Lob Data Types:

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.

OTHER DATA TYPES

In addition to the commonly used data types in PL/SQL, here are some other data types you
may encounter:

NCHAR and NVARCHAR2:

NCHAR: For fixed-length national character set strings.

NVARCHAR2: For variable-length national character set strings, useful for multilingual
data.

INTERVAL:

INTERVAL YEAR TO MONTH: Represents a period of time in years and months.

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:

Associative Arrays: Key-value pairs for storing data in a flexible manner.

Nested Tables: Similar to tables but can be stored in a database column.

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:

Variable_name data_type [NOT NULL] := initial_value;

Example Declaration: Here’s an example of declaring different types of variables:

DECLARE

V_emp_name VARCHAR2(50); -- Variable for employee name

V_emp_id NUMBER; -- Variable for employee ID

V_join_date DATE := SYSDATE; -- Variable with an initial value

V_is_active BOOLEAN := TRUE; -- Boolean variable

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;

Example of Assignment: Here’s an example where variables are assigned values:

DECLARE

V_emp_id NUMBER;

V_emp_name VARCHAR2(50);

BEGIN

V_emp_id := 1001; -- Assigning a numeric value

V_emp_name := ‘John Doe’; -- Assigning a string value

END;

ARITHMETIC OPERATORS

In PL/SQL, arithmetic operators are used to perform mathematical calculations. Here are the
key arithmetic operators:

Addition (+): Adds two numeric values.

Example: V_total := v_a + v_b;

Subtraction (-): Subtracts the second numeric value from the first.

Example: V_difference := v_a – v_b;

Multiplication (*): Multiplies two numeric values.

Example: V_product := v_a * v_b;

Division (/): Divides the first numeric value by the second.

Example:. V_quotient := v_a / v_b;

Modulus (MOD): Returns the remainder of a division operation.

Example : V_remainder := MOD(v_a, v_b);

Example Usage:
DECLARE

V_a NUMBER := 10;

V_b NUMBER := 3;

V_sum NUMBER;

V_diff NUMBER;

V_prod NUMBER;

V_quot NUMBER;

V_rem NUMBER;

BEGIN

V_sum := v_a + v_b; -- Addition

V_diff := v_a – v_b; -- Subtraction

V_prod := v_a * v_b; -- Multiplication

V_quot := v_a / v_b; -- Division

V_rem := MOD(v_a, v_b); -- Modulus

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

The IF statement executes a block of code based on a condition.

Syntax

IF condition THEN

Statements;
ELSIF another_condition THEN

Statements;

ELSE

Statements;

END IF;

Example:

DECLARE

V_score NUMBER := 85;

BEGIN

IF v_score >= 90 THEN

DBMS_OUTPUT.PUT_LINE(‘Grade: A’);

ELSIF v_score >= 80 THEN

DBMS_OUTPUT.PUT_LINE(‘Grade: B’);

ELSE

DBMS_OUTPUT.PUT_LINE(‘Grade: C’);

END IF;

END;

CASE Statement

The CASE statement is used for multiple conditions.

Syntax:

CASE expression

WHEN value1 THEN

Statements;
WHEN value2 THEN

Statements;

ELSE

Statements;

END CASE;

Example:

DECLARE

V_day NUMBER := 3;

BEGIN

CASE v_day

WHEN 1 THEN DBMS_OUTPUT.PUT_LINE(‘Monday’);

WHEN 2 THEN DBMS_OUTPUT.PUT_LINE(‘Tuesday’);

WHEN 3 THEN DBMS_OUTPUT.PUT_LINE(‘Wednesday’);

ELSE DBMS_OUTPUT.PUT_LINE(‘Other 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;

EXIT WHEN v_counter > 5;

END LOOP;

END;

WHILE Loop

The WHILE loop continues as long as the condition is true.

Syntax:

WHILE condition LOOP

Statements;

END LOOP;

Example:

DECLARE

V_counter NUMBER := 1;

BEGIN

WHILE v_counter <= 5 LOOP


DBMS_OUTPUT.PUT_LINE(‘Counter: ‘ || v_counter);

V_counter := v_counter + 1;

END LOOP;

END;

FOR Loop

The FOR loop iterates over a specified range.

Syntax:

FOR counter IN lower_bound..upper_bound LOOP

Statements;

END LOOP;

Example:

BEGIN

FOR v_counter IN 1..5 LOOP

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

WHEN exception_name THEN

Error handling statements;

WHEN OTHERS THEN

Handle other exceptions;

END;

Example

DECLARE

V_number NUMBER := 0;

V_result NUMBER;

BEGIN

V_result := 10 / v_number; -- This will cause a divide-by-zero error

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE(‘Cannot divide by zero.’);

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE(‘An unexpected error occurred: ‘ || SQLERRM);

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

Outer block declarations

BEGIN

Outer block statements

DECLARE

Inner block declarations

BEGIN

Inner block statements

END;

More outer block statements

END;

Example of Nested Blocks

Here’s a practical example demonstrating nested blocks in PL/SQL:

DECLARE

V_outer_var NUMBER := 10; -- Outer block variable

BEGIN

DBMS_OUTPUT.PUT_LINE(‘Outer Variable: ‘ || v_outer_var);

 Start of the inner block

DECLARE

V_inner_var NUMBER := 5; -- Inner block variable

BEGIN
DBMS_OUTPUT.PUT_LINE(‘Inner Variable: ‘ || v_inner_var);

DBMS_OUTPUT.PUT_LINE(‘Sum: ‘ || (v_outer_var + v_inner_var)); -- Access outer


variable

END;

 End of the inner block

DBMS_OUTPUT.PUT_LINE(‘Outer Variable after inner block: ‘ || v_outer_var);

END;

Explanation

Outer Block: Declares v_outer_var and prints its value.

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.

Transaction control statements

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

UPDATE employees SET salary = salary * 1.1 WHERE id = 1;

ROLLBACK; -- Discards the changes

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;

UPDATE employees SET salary = salary * 1.1 WHERE id = 1;

 If something goes wrong

ROLLBACK TO before_update; -- Roll back to the savepoint

 Changes after the savepoint will be undone, but previous changes will be kept
COMMIT; -- Commit the changes before the savepoint

END;

PL/SQL Cursors and Exceptions:

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);

SELECT name INTO v_emp_name FROM employees WHERE id = 1; -- Implicit cursor

DBMS_OUTPUT.PUT_LINE(‘Inserted Employee: ‘ || v_emp_name);

END;

Explicit Cursors

Explicit cursors provide more control over the context and allow you to fetch multiple rows.
You must define them explicitly.

Steps to Use an Explicit Cursor:

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.

Close the Cursor: Release the cursor when it is no longer needed.

Example

DECLARE

CURSOR emp_cursor IS

SELECT name, salary FROM employees WHERE salary > 40000;

V_emp_name employees.name%TYPE;

V_emp_salary employees.salary%TYPE;

BEGIN

OPEN emp_cursor; -- Step 2: Open the cursor

LOOP

FETCH emp_cursor INTO v_emp_name, v_emp_salary; -- Step 3: Fetch rows

EXIT WHEN emp_cursor%NOTFOUND; -- Exit the loop if no more rows

DBMS_OUTPUT.PUT_LINE(‘Employee: ‘ || v_emp_name || ‘, Salary: ‘ ||


v_emp_salary);

END LOOP;

CLOSE emp_cursor; -- Step 4: Close the cursor

END;

Key Points About Cursors

Cursor Attributes:

%FOUND: Returns TRUE if the last fetch was successful.

%NOTFOUND: Returns TRUE if the last fetch failed (no more rows).

%ROWCOUNT: Returns the number of rows fetched so far


FOR Loop with Cursors:

You can simplify cursor handling by using a FOR loop, which automatically opens, fetches,
and closes the cursor.

Example Using FOR Loop:

BEGIN

FOR emp_record IN (SELECT name, salary FROM employees WHERE salary > 40000)
LOOP

DBMS_OUTPUT.PUT_LINE(‘Employee: ‘ || emp_record.name || ‘, Salary: ‘ ||


emp_record.salary);

END LOOP;

END;

You might also like