0% found this document useful (0 votes)
5 views36 pages

Module 5 Dbms Note

The document provides an overview of transaction management in database systems, detailing the properties of transactions (ACID), concurrency control, and common concurrency problems. It also discusses locking protocols, specifically two-phase locking, and introduces PL/SQL, its data types, variables, constants, and control statements. Additionally, it explains the use of the SET command and the SELECT INTO command in PL/SQL.

Uploaded by

toksgang
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)
5 views36 pages

Module 5 Dbms Note

The document provides an overview of transaction management in database systems, detailing the properties of transactions (ACID), concurrency control, and common concurrency problems. It also discusses locking protocols, specifically two-phase locking, and introduces PL/SQL, its data types, variables, constants, and control statements. Additionally, it explains the use of the SET command and the SELECT INTO command in PL/SQL.

Uploaded by

toksgang
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/ 36

Transaction Management

Transactions are a set of operations used to perform a logical


set of work. It is the bundle of all the instructions of a logical
operation. A transaction usually means that the data in the
database has changed. One of the major uses of DBMS is to
protect the user’s data from system failures. It is done by
ensuring that all the data is restored to a consistent state when
the computer is restarted after a crash. The transaction is any
one execution of the user program in a DBMS. One of the
important properties of the transaction is that it contains a finite
number of steps. Executing the same program multiple times will
generate multiple transactions.
Example: Consider the following example of transaction
operations to be performed to withdraw cash from an ATM
vestibule.

Steps for ATM Transaction


1. Transaction Start.
2. Insert your ATM card.
3. Select a language for your transaction.
4. Select the Savings Account option.
5. Enter the amount you want to withdraw.
6. Enter your secret pin.
7. Wait for some time for processing.
8. Collect your Cash.
9. Transaction Completed.
A transaction can include the following basic database access
operation.
 Read/Access data (R): Accessing the database item from disk
(where the database stored data) to memory variable.
 Write/Change data (W): Write the data item from the memory
variable to the disk.
 Commit: Commit is a transaction control language that is
used to permanently save the changes done in a transaction

Example: Transfer of 50₹ from Account A to Account B. Initially


A= 500₹, B= 800₹. This data is brought to RAM from Hard Disk.
R(A) -- 500 // Accessed from RAM.
A = A-50 // Deducting 50₹ from A.
W(A)--450 // Updated in RAM.
R(B) -- 800 // Accessed from RAM.
B=B+50 // 50₹ is added to B's Account.
W(B) --850 // Updated in RAM.
commit // The data in RAM is taken back to Hard Disk.

Concurrency Control

Concurrency control is a very important concept of DBMS which


ensures the simultaneous execution or manipulation of data by
several processes or user without resulting in data inconsistency.
Concurrency Control deals with interleaved execution of more
than one transaction.

Desirable Properties of Transaction (ACID Properties)


For a transaction to be performed in DBMS, it must possess
several properties often called ACID properties.
 A – Atomicity
 C – Consistency
 I – Isolation
 D – Durability
Atomicity
 States that all operations of the transaction take place at once
if not, the transactions are aborted.
 There is no midway, i.e., the transaction cannot occur partially.
Each transaction is treated as one unit and either run to
completion or is not executed at all.
 Atomicity involves the following two operations:
 Abort: If a transaction aborts, then all the changes made are
not visible.
 Commit : If a transaction commits then all the changes made
are visible.
Consistency
 The integrity constraints are maintained so that the database
is consistent before and after the transaction.
 The execution of a transaction will leave a database in either
its prior stable state or anew stable state.
 The consistent property of database states that every
transaction sees a consistent database instance.
 The transaction is used to transform the database from one
consistent state to another consistent state.
Isolation
 It shows that the data which is used at the time of execution
of a transaction cannot be used by the second transaction
until the first one is completed.
 In isolation, if the transaction T1 is being executed and using
the data item X, then that data item can’t be accessed by any
other transaction T2 until the transaction T1ends.
 The concurrency control subsystem of the DBMS enforced the
isolation property
Durability
 The durability property is used to indicate the performance of
the database’s consistent state. It states that the transaction
made the permanent changes.
 They cannot be lost by the erroneous operation of a faulty
transaction or by the system failure. When a transaction is
completed, then the database reaches a state known as the
consistent state. That consistent state cannot be lost, even in
the event of a system’s failure.
 The recovery subsystem of the DBMS has the responsibility of
Durability property.

Concurrency problems

When multiple transactions execute concurrently in an


uncontrolled or unrestricted manner, then it might lead to several
problems. These problems are commonly referred to as
concurrency problems in a database environment.

The five concurrency problems that can occur in the database


are:
 Temporary Update Problem
 Incorrect Summary Problem
 Lost Update Problem
 Unrepeatable Read Problem

Temporary Update Problem:


Temporary update or dirty read problem occurs when one
transaction updates an item and fails. But the updated item is
used by another transaction before the item is changed or
reverted back to its last value.
Example:

In the above example, if transaction 1 fails for some reason then


X will revert back to its previous value. But transaction 2 has
already read the incorrect value of X.
Incorrect Summary Problem:
Consider a situation, where one transaction is applying the
aggregate function on some records while another transaction is
updating these records. The aggregate function may calculate
some values before the values have been updated and others
after they are updated.
Example:
In the above example, transaction 2 is calculating the sum of
some records while transaction 1 is updating them. Therefore
the aggregate function may calculate some values before they
have been updated and others after they have been updated.
Lost Update Problem:
In the lost update problem, an update done to a data item by a
transaction is lost as it is overwritten by the update done by
another transaction.
Example:

In the above example, transaction 2 changes the value of X but it


will get overwritten by the write commit by transaction 1 on
X (not shown in the image above). Therefore, the update done by
transaction 2 will be lost. Basically, the write commit done by
the last transaction will overwrite all previous write commits.
Unrepeatable Read Problem:
The unrepeatable problem occurs when two or more read
operations of the same transaction read different values of the
same variable.
Example:

In the above example, once transaction 2 reads the variable X, a


write operation in transaction 1 changes the value of the variable
X. Thus, when another read operation is performed by
transaction 2, it reads the new value of X which was updated by
transaction 1.

Lock-Based Protocol

Locking protocols are used in database management


systems as a means of concurrency control. Multiple
transactions may request a lock on a data item simultaneously.
Hence, we require a mechanism to manage the locking requests
made by transactions. Such a mechanism is called a Lock
Manager.
1. Shared lock:

o It is also known as a Read-only lock. In a shared lock, the


data item can only read by the transaction.
o It can be shared between the transactions because when the
transaction holds a lock, then it can't update the data on the
data item.

2. Exclusive lock:

o In the exclusive lock, the data item can be both reads as well
as written by the transaction.
o This lock is exclusive, and in this lock, multiple transactions
do not modify the same data simultaneously.

Two-phase locking (2PL)


o The two-phase locking protocol divides the execution phase
of the transaction into three parts.
o In the first part, when the execution of the transaction starts,
it seeks permission for the lock it requires.
o In the second part, the transaction acquires all the locks. The
third phase is started as soon as the transaction releases its
first lock.
o In the third phase, the transaction cannot demand any new
locks. It only releases the acquired locks.
There are two phases of 2PL:

Growing phase: In the growing phase, a new lock on the data item
may be acquired by the transaction, but none can be released.

Shrinking phase: In the shrinking phase, existing lock held by the


transaction may be released, but no new locks can be acquired.

In the below example, if lock conversion is allowed then the


following phase can happen:

1. Upgrading of lock (from S(a) to X (a)) is allowed in growing


phase.
2. Downgrading of lock (from X(a) to S(a)) must be done in
shrinking phase.

Example:

The following way shows how unlocking and locking work with 2-
PL.

Transaction T1:

o Growing phase: from step 1-3


o Shrinking phase: from step 5-7
o Lock point: at 3

Transaction T2:

o Growing phase: from step 2-6


o Shrinking phase: from step 8-9
o Lock point: at 6

PL/SQL Introduction

PL/SQL is a block structured language that enables developers to


combine the power of SQL with procedural statements.All the
statements of a block are passed to oracle engine all at once
which increases processing speed and decreases the traffic.

Basics of PL/SQL

 •PL/SQL stands for Procedural Language extensions to the


Structured Query Language (SQL).
 PL/SQL is a combination of SQL along with the procedural
features of programming languages.
 Oracle uses a PL/SQL engine to processes the PL/SQL
statements.
 PL/SQL includes procedural language elements like conditions
and loops. It allows declaration of constants and variables,
procedures and functions, types and variable of those types
and triggers.
Disadvantages of SQL:
 SQL doesn’t provide the programmers with a technique of
condition checking, looping and branching.
 SQL statements are passed to Oracle engine one at a time
which increases traffic and decreases speed.
 SQL has no facility of error checking during manipulation of
data.

Data types

Scalar( Base type)


Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.
Composite
Data items that have internal components that can be accessed
individually. For example, collections and records.

PL/SQL Scalar Data Types

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 composite data types

Composite types have internal components that can be


manipulated individually, such as the elements of an array, record,
or table.

TimesTen supports the following composite data types:

 Associative array (index-by table)


 Nested table
 Varray
 Record

Associative arrays, nested tables, and varrays are also referred to


as collections.

Variables

A variable is a meaningful name which facilitates a programmer


to store data temporarily during the execution of code. It helps
you to manipulate data in PL/SQL programs. It is nothing except a
name given to a storage area.

Following is the syntax for declaring variable:

1. variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT i


nitial_value]

Here, variable_name is a valid identifier in PL/SQL and datatype


must be valid PL/SQL data type. A data type with size, scale or
precision limit is called a constrained declaration. The
constrained declaration needs less memory than unconstrained
declaration.

Example:

Radius Number := 5;

Date_of_birth date;

PL/SQL Constants

A constant is a value used in a PL/SQL block that remains


unchanged throughout the program. It is a user-defined literal
value. It can be declared and used instead of actual values.

Syntax to declare a constant:

1. constant_name CONSTANT datatype := VALUE;


2. Constant_name:it is the name of constant just like variable
name. The constant word is a reserved word and its value
does not change.
3. VALUE: it is a value which is assigned to a constant when it
is declared. It can not be assigned later.

1. Eg: pi constant number := 3.141592654;

Attributes

In PL/SQL, attributes are properties or characteristics of data


types, objects, or constructs that help define their structure and
behavior. Here are the main categories of attributes in PL/SQL:

1. Scalar Attributes

Scalar attributes provide details about the basic data types:


 %TYPE: This attribute is used to declare a variable with the
same data type as a column in a table or another variable.

plsql
Copy code
DECLARE
v_employee_name employees.name%TYPE;
BEGIN
SELECT name INTO v_employee_name FROM employees
WHERE employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Employee Name: ' ||
v_employee_name);
END;
2. Composite Attributes

Composite attributes deal with collections and records:

 %ROWTYPE: This attribute declares a record with the same


structure as a row in a table or a cursor.

plsql
Copy code
DECLARE
v_employee employees%ROWTYPE;
BEGIN
SELECT * INTO v_employee FROM employees WHERE
employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Employee Name: ' ||
v_employee.name);
END;
3. Cursor Attributes

Cursor attributes provide information about the execution of SQL


statements:

 %FOUND: Returns TRUE if a FETCH statement successfully


retrieves a row.
 %NOTFOUND: Returns TRUE if a FETCH statement does not
retrieve a row.
 %ISOPEN: Returns TRUE if the cursor is open.

SET Command

The SET command is generally used in SQLPlus or Oracle SQL


Developer to change the environment settings for a session. It is
not used for variable assignments in PL/SQL blocks. Here are
some common uses of the SET command in SQLPlus:

sql
Copy code
SET SERVEROUTPUT ON;
SET PAGESIZE 50;
SET LINESIZE 100;
SELECT INTO Command

The SELECT INTO command is used within PL/SQL to assign the


result of a query to one or more variables. This is the primary way
to fetch data from the database into PL/SQL variables.

Syntax
plsql
Copy code
SELECT column1, column2, ...
INTO variable1, variable2, ...
FROM table_name
WHERE condition;
control statements

control statements are used to control the flow of execution


within a program. They include conditional statements, iterative
statements, and sequential control.

1. Conditional Statements

These statements execute different actions based on different


conditions.

IF-THEN

Executes a sequence of statements if a condition is true.

plsql
Copy code
DECLARE
v_number NUMBER := 10;
BEGIN
IF v_number > 5 THEN
DBMS_OUTPUT.PUT_LINE('v_number is greater than 5');
END IF;
END;
IF-THEN-ELSE

Executes one sequence of statements if a condition is true and


another sequence if it is false.

plsql
Copy code
DECLARE
v_number NUMBER := 3;
BEGIN
IF v_number > 5 THEN
DBMS_OUTPUT.PUT_LINE('v_number is greater than 5');
ELSE
DBMS_OUTPUT.PUT_LINE('v_number is 5 or less');
END IF;
END;
IF-THEN-ELSIF

Tests multiple conditions sequentially.

plsql
Copy code
DECLARE
v_number NUMBER := 7;
BEGIN
IF v_number > 10 THEN
DBMS_OUTPUT.PUT_LINE('v_number is greater than 10');
ELSIF v_number > 5 THEN
DBMS_OUTPUT.PUT_LINE('v_number is greater than 5 but
less than or equal to 10');
ELSE
DBMS_OUTPUT.PUT_LINE('v_number is 5 or less');
END IF;
END;
CASE

Executes one sequence of statements based on the value of an


expression.

Simple CASE Statement:

plsql
Copy code
DECLARE
v_grade CHAR := 'B';
BEGIN
CASE v_grade
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Good');
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Average');
ELSE DBMS_OUTPUT.PUT_LINE('Below Average');
END CASE;
END;
2. Iterative Statements

These statements repeatedly execute a sequence of statements.

LOOP

Executes a sequence of statements multiple times.

plsql
Copy code
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

Executes a sequence of statements as long as a condition is true.


plsql
Copy code
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

Executes a sequence of statements a specified number of times.

plsql
Copy code
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || i);
END LOOP;
END;
Using CONTINUE in Loops

Here are examples of using CONTINUE in different types of loops:

1. Basic LOOP with CONTINUE

Example
plsql
Copy code
DECLARE
v_counter NUMBER := 0;
BEGIN
LOOP
v_counter := v_counter + 1;

IF v_counter = 3 THEN
CONTINUE; -- Skip the rest of the loop when v_counter is 3
END IF;

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

EXIT WHEN v_counter >= 5;


END LOOP;
END;

Looping through arrays (or collections) in PL/SQL is a common


task that can be performed using various types of loops. PL/SQL
supports three primary types of collections: associative arrays
(index-by tables), nested tables, and varrays. Here's how you can
loop through each type of collection using PL/SQL loops.

Example: Looping through a Nested Table

1. Define a Collection Type and Populate It

First, let's define a nested table type and populate it with some
values.

plsql
Copy code
DECLARE
TYPE t_numbers IS TABLE OF NUMBER;
v_numbers t_numbers := t_numbers(1, 2, 3, 4, 5);
BEGIN
FOR i IN 1..v_numbers.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Element at index ' || i || ': ' ||
v_numbers(i));
END LOOP;
END;

In this example, t_numbers is a nested table of NUMBER data type,


and v_numbers is an instance of this nested table, initialized with
five numbers. The FOR LOOP iterates through each element in the
nested table.

Lock
In database management systems, locks are mechanisms used
to control access to resources (such as rows, tables, or even the
entire database) to ensure data integrity and consistency in a
multi-user environment. Here are some common types of locks:

1. Shared (Read) Locks

Shared locks allow multiple transactions to read data


simultaneously, but they prevent other transactions from writing
to the locked resource.

2. Exclusive (Write) Locks

Exclusive locks prevent other transactions from reading or writing


to the locked resource. They are used when a transaction intends
to modify the data.

3. Row-Level Locks

Row-level locks apply to individual rows in a table. They allow


multiple transactions to access other rows simultaneously while
preventing concurrent updates to the locked rows.
4. Table-Level Locks

Table-level locks apply to the entire table, preventing other


transactions from accessing any rows in the table. They are less
granular than row-level locks and can lead to contention in multi-
user environments.

5. Deadlocks

Deadlocks occur when two or more transactions are waiting for


each other to release locks, resulting in a deadlock situation
where none of the transactions can proceed. Database
management systems typically detect and resolve deadlocks
automatically by aborting one of the transactions involved.

Advisory lock

An advisory lock, also known as an application lock or a user-


defined lock, is a mechanism used to coordinate access to
resources across multiple sessions or transactions within an
application.

Cursors
Cursors in PL/SQL are programming constructs used to retrieve
and process multiple rows of data returned by SQL queries.
Cursors provide a mechanism for sequential traversal of query
result sets and enable operations such as fetching, updating, and
deleting rows one at a time.

Bound Cursors

Bound cursors are associated with a specific SQL query at


compile time. This means that the SQL query is fixed and cannot
be changed dynamically at runtime. Bound cursors are typically
declared using a static SQL query directly within the cursor
declaration.

Example of Bound Cursor:


plsql
Copy code
DECLARE
CURSOR bound_cursor IS
SELECT column1, column2 FROM table_name WHERE
condition;
variable1 table_name.column1%TYPE;
variable2 table_name.column2%TYPE;
BEGIN
OPEN bound_cursor;
-- Fetch and process data using bound_cursor
CLOSE bound_cursor;
END;

In this example, the bound_cursor is associated with the SQL


query specified in the SELECT statement at compile time. The
query cannot be changed dynamically during runtime.

Unbound Cursors

Unbound cursors, also known as dynamic cursors, allow the SQL


query to be specified dynamically at runtime. This provides
flexibility in constructing queries based on runtime conditions or
user input. Unbound cursors are typically declared without
specifying the SQL query at compile time. Instead, the query is
assigned to the cursor using the OPEN statement with a FOR
clause.

Example of Unbound Cursor:


plsql
Copy code
DECLARE
CURSOR unbound_cursor IS
SELECT column1, column2 FROM table_name;
variable1 table_name.column1%TYPE;
variable2 table_name.column2%TYPE;
BEGIN
OPEN unbound_cursor FOR
SELECT column1, column2 FROM table_name WHERE
condition;
-- Fetch and process data using unbound_cursor
CLOSE unbound_cursor;
END;

In this example, the unbound_cursor is declared without


specifying the SQL query in the cursor declaration. Instead, the
query is assigned to the cursor dynamically at runtime using the
OPEN statement with a FOR clause.

1. Cursor Declaration

Declare a cursor by specifying the SQL query that defines the


result set to be processed.

plsql
Copy code
DECLARE
CURSOR cursor_name IS
SELECT column1, column2 FROM table_name WHERE
condition;
2. Cursor Variables

Declare variables to store the values retrieved by the cursor.


plsql
Copy code
variable1 table_name.column1%TYPE;
variable2 table_name.column2%TYPE;
3. Opening the Cursor

Open the cursor to execute the query and retrieve the result set.

plsql
Copy code
OPEN cursor_name;
4. Fetching Data

Fetch rows from the cursor into variables one at a time within a
loop.

plsql
Copy code
LOOP
FETCH cursor_name INTO variable1, variable2;
EXIT WHEN cursor_name%NOTFOUND;
-- Process the retrieved data
END LOOP;
5. Processing Data

Process the retrieved data as needed within the loop.

plsql
Copy code
DBMS_OUTPUT.PUT_LINE('Column1: ' || variable1 || ', Column2: ' ||
variable2);
6. Closing the Cursor

Close the cursor to release resources after processing the result


set.

plsql
Copy code
CLOSE cursor_name;
Example:
plsql
Copy code
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, first_name, last_name FROM
employees WHERE department_id = 100;
v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_employee_id, v_first_name,
v_last_name;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_employee_id || ',
Name: ' || v_first_name || ' ' || v_last_name);
END LOOP;
CLOSE emp_cursor;
END;

stored procedure
stored procedure is a precompiled collection of SQL statements
and procedural logic stored in a database. It can be invoked by
name and executed with or without parameters. Stored
procedures offer several advantages and disadvantages:

Advantages of Stored Procedures:

1. Improved Performance: Stored procedures are precompiled


and stored in the database, resulting in faster execution
compared to dynamically generated SQL statements.
2. Reduced Network Traffic: Since the logic resides in the
database server, only the procedure call needs to be
transmitted over the network rather than individual SQL
statements, reducing network traffic.
3. Enhanced Security: Access to data can be controlled
through stored procedures, limiting direct access to tables
and ensuring data security and integrity.
4. Code Reusability: Stored procedures can be reused across
multiple applications and queries, reducing redundancy and
promoting consistency in logic and results.
5. Encapsulation of Business Logic: Complex business logic
can be encapsulated within stored procedures, promoting
modularity, maintainability, and ease of understanding.
6. Transaction Management: Stored procedures can be used
to encapsulate multiple SQL statements within a single
transaction, ensuring atomicity, consistency, isolation, and
durability (ACID properties).
7. Parameterized Queries: Stored procedures support
parameterized queries, allowing for flexible and dynamic
SQL statements based on input parameters.
Disadvantages of Stored Procedures:

1. Database Vendor Lock-In: Stored procedures may contain


vendor-specific syntax or logic, leading to vendor lock-in and
potential migration challenges.
2. Limited Portability: Stored procedures are specific to a
particular database system, limiting portability across
different database platforms.
3. Debugging Complexity: Debugging stored procedures can
be challenging, especially when dealing with complex logic
or nested procedures.
4. Versioning and Maintenance: Changes to stored procedures
may require updates to multiple applications, leading to
versioning and maintenance challenges.
5. Performance Overhead: While stored procedures offer
performance benefits in many cases, they can also introduce
overhead due to resource consumption, context switching,
and caching issues.
6. Complexity and Scalability: Overuse of stored procedures
can lead to code complexity, making maintenance and
scalability more challenging, especially in large and rapidly
evolving systems.
7. Development Overhead: Developing and maintaining stored
procedures may require specialized skills and tools,
increasing development overhead compared to other
programming approaches.

Creating a Stored Procedure

Here's a basic example to create a stored procedure:

Example 1: Simple Stored Procedure

This example creates a stored procedure that outputs a greeting


message.

plsql
Copy code
CREATE OR REPLACE PROCEDURE greet_user IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, welcome to PL/SQL!');
END greet_user;

To execute this procedure:

plsql
Copy code
BEGIN
greet_user;
END;
Parameters in Stored Procedures

Stored procedures can accept input parameters, output


parameters, or both. The three types of parameters are:

 IN: Passes a value to the procedure.


 OUT: Returns a value to the caller.
 IN OUT: Passes a value to the procedure and returns an
updated value.

Example 2: Procedure with IN Parameter

This procedure takes an employee ID as input and outputs the


corresponding employee's name and salary.

plsql
Copy code
CREATE OR REPLACE PROCEDURE get_employee_details (
p_employee_id IN employees.employee_id%TYPE
) IS
v_emp_name employees.last_name%TYPE;
v_emp_salary employees.salary%TYPE;
BEGIN
SELECT last_name, salary
INTO v_emp_name, v_emp_salary
FROM employees
WHERE employee_id = p_employee_id;

DBMS_OUTPUT.PUT_LINE('Name: ' || v_emp_name || ', Salary: ' ||


v_emp_salary);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found with ID ' ||
p_employee_id);
END get_employee_details;

To execute this procedure:

plsql
Copy code
BEGIN
get_employee_details(100);
END;

PL/SQL function
In PL/SQL, a function is a stored program unit that performs a
specific task and returns a single value. Functions are similar to
procedures but are designed to return a value and can be used in
SQL statements, while procedures cannot. Functions can take
parameters and contain complex business logic, similar to
procedures.

Key Concepts of PL/SQL Functions

1. Return Value:
o A function must return a single value of a specified data
type.
o The return type is declared in the function header.
2. Parameters:
o Functions can have IN parameters (input) but typically
do not have OUT or IN OUT parameters.
o Parameters allow passing values to the function for
processing.
3. Usage:
o Functions can be called from SQL statements, PL/SQL
blocks, and other PL/SQL program units (e.g.,
procedures, other functions).
o They are often used in SELECT, INSERT, UPDATE, and
DELETE statements.

Structure of a Function

The basic structure of a PL/SQL function includes:

1. Header: Function name, parameter list, and return type.


2. Declarative Section: Declarations of variables, constants,
and types.
3. Executable Section: The main logic of the function, including
the RETURN statement to return a value.
4. Exception Handling Section: Optional section for handling
exceptions.
Example of a Simple Function

Creating a Function

This example creates a function that calculates the area of a


circle given its radius.

plsql
Copy code
CREATE OR REPLACE FUNCTION calculate_circle_area (
p_radius IN NUMBER
) RETURN NUMBER IS
v_area NUMBER;
BEGIN
v_area := 3.14159 * p_radius * p_radius;
RETURN v_area;
END calculate_circle_area;
Calling the Function

You can call the function from a PL/SQL block or SQL statement.

plsql
Copy code
-- Calling from a PL/SQL block
DECLARE
v_radius NUMBER := 5;
v_area NUMBER;
BEGIN
v_area := calculate_circle_area(v_radius);
DBMS_OUTPUT.PUT_LINE('Area of the circle: ' || v_area);
END;
sql
Copy code
-- Calling from a SQL statement
SELECT calculate_circle_area(5) AS area FROM dual;

Trigger
A trigger in PL/SQL is a stored program unit that is automatically
executed, or "fired," in response to certain events on a particular
table or view. Triggers can be used to enforce business rules,
maintain audit trails, replicate data, and ensure data integrity.
They are closely tied to the operations on the data in the database.

Key Concepts of Triggers

1. Trigger Events:
o Triggers can be set to fire before or after the following
events:
 INSERT
 UPDATE
 DELETE
2. Trigger Timing:
o BEFORE: The trigger action is executed before the
triggering statement.
o AFTER: The trigger action is executed after the
triggering statement.
3. Trigger Scope:
o ROW: Fires once for each row affected by the triggering
statement.
o STATEMENT: Fires once for the triggering statement,
regardless of the number of rows affected.
4. Trigger Body:
o The PL/SQL code block that defines what the trigger
does when it fires.
Structure of a Trigger

The basic structure of a PL/SQL trigger includes:

1. Trigger Name: The name of the trigger.


2. Trigger Timing and Event: Specifies when and what event
causes the trigger to fire.
3. Table or View: The table or view to which the trigger is
associated.
4. Trigger Scope: Specifies whether the trigger is row-level or
statement-level.
5. Trigger Body: The PL/SQL block that contains the logic
executed when the trigger fires.

Example of a Simple Trigger

Creating a Trigger

This example creates a trigger that automatically logs an audit


record whenever a row in the employees table is updated.

plsql
Copy code
CREATE OR REPLACE TRIGGER trg_audit_employee_update
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit (
employee_id,
old_salary,
new_salary,
change_date
) VALUES (
:OLD.employee_id,
:OLD.salary,
:NEW.salary,
SYSDATE
);
END trg_audit_employee_update;
Advantages of Triggers

1. Automation:
o Triggers automate actions in response to changes in
the database, such as enforcing business rules or
maintaining audit logs.
2. Data Integrity:
o Triggers can enforce complex integrity constraints and
ensure data consistency across related tables.
3. Audit and Security:
o Triggers can automatically log changes to sensitive
data, helping maintain an audit trail and enhancing
security.
4. Complex Business Logic:
o Triggers can encapsulate complex business logic that
cannot be easily enforced through constraints alone.

Error handling

Error handling in PL/SQL is a critical aspect of building robust and


reliable database applications. PL/SQL provides several
mechanisms to catch, handle, and manage exceptions (errors)
that occur during the execution of a block of code.

Key Concepts in PL/SQL Error Handling

1. Exceptions:
o Exceptions are events that disrupt the normal flow of
execution. PL/SQL categorizes exceptions into
predefined exceptions, user-defined exceptions, and
non-predefined Oracle exceptions.
2. Exception Handling:
o PL/SQL blocks can include an EXCEPTION section
where specific actions can be taken in response to
errors.

You might also like