0% found this document useful (0 votes)
43 views

PL - SQL & Triggers - Cursors

This is about triggers and cursors

Uploaded by

Anusha Maurya
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)
43 views

PL - SQL & Triggers - Cursors

This is about triggers and cursors

Uploaded by

Anusha Maurya
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/ 9

PL/SQL

PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural


language extension for SQL. It seamlessly integrates procedural constructs such as loops,
conditional statements, and exception handling with SQL statements. PL/SQL is used for
developing server-side database applications, triggers, stored procedures, and functions.
Various delimiters are used in PL/SQL like double colon(::), AS, IS, -- and /*---*/ (comments),
all operators, forward slash(/), BEGIN…..END & DECLARE…..BEGIN….END, etc.. Some key
features of PL/SQL are discussed below:
Blocks:
PL/SQL code is organized into blocks, which are units of code that can include declarations,
executable statements, and exception handlers. A PL/SQL block has a structure like this:
DECLARE
-- Declarations (optional)
BEGIN
-- Executable statements
EXCEPTION
-- Exception handling (optional)
END;
/

Variables and Constants: “PL/SQL allows you to declare variables and constants.” Variables
are used to store data temporarily, while constants hold values that do not change during
the program's execution.
DECLARE
v_employee_name VARCHAR2(50);
pi CONSTANT NUMBER := 3.14;
BEGIN
-- Code using variables and constants
END;
/
Control Structures: PL/SQL supports various control structures such as IF-THEN-ELSE, CASE,
FOR LOOP, WHILE LOOP, etc.
DECLARE
v_salary NUMBER := 5000;
BEGIN
IF v_salary > 10000 THEN
DBMS_OUTPUT.PUT_LINE('High Salary');
ELSE
DBMS_OUTPUT.PUT_LINE('Low Salary');
END IF;
END;
/

Cursors: Cursors are used for handling the result sets returned by SQL queries. Cursors can
be either implicit (automatically created by Oracle) or explicit (manually declared by the
programmer).
Exception Handling: PL/SQL provides a robust exception-handling mechanism to deal with
errors gracefully. Common exception types include NO_DATA_FOUND, TOO_MANY_ROWS,
and OTHERS.
DECLARE
v_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO v_salary
FROM employees
WHERE employee_id = 101;

DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);


EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred');
END;
/

Procedures and Functions: PL/SQL allows you to define stored procedures and functions,
which are named blocks of code that can be called multiple times.
CREATE OR REPLACE PROCEDURE print_employee_name
IS
v_employee_name employees.employee_name%TYPE;
BEGIN
SELECT employee_name INTO v_employee_name
FROM employees
WHERE employee_id = 101;

DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name);


END;
/

Triggers: PL/SQL is commonly used for writing triggers, which are pieces of code that are
automatically executed in response to specific events on a particular table or view.
CREATE OR REPLACE TRIGGER after_insert_employee
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
-- Code to be executed after an insert on the "employees" table
END;
TRIGGERS
A trigger is a set of instructions or a program that is automatically executed ("triggered") in
response to certain events on a particular table or view in the database. Triggers are a crucial
part of database systems as they enable the automatic execution of predefined actions,
helping to maintain data integrity, enforce business rules, and automate complex database
operations. Here are some key aspects of triggers and their uses:

Event-Driven Execution:
Insert Trigger: Fires when a new record is inserted into a specified table.
Update Trigger: Executes when an existing record is updated.
Delete Trigger: Activates when a record is deleted from the table.

Data Integrity:
Triggers can be used to enforce data integrity constraints, such as ensuring that certain
conditions are met before allowing changes to the database.
For example, a trigger can prevent the deletion of a record that is referenced by records in
another table, thus maintaining referential integrity.
Automated Logging:
Triggers are often used to automatically log changes to a database. This is useful for audit
trails, tracking modifications, and maintaining a history of data changes.
Business Rule Enforcement:
Triggers enable the enforcement of complex business rules that involve multiple tables or
conditions.
For instance, a trigger can be created to check if the total value of orders for a customer
exceeds a certain limit and take appropriate actions if it does.
Derived Data Maintenance:
Triggers can be employed to automatically update derived data or maintain denormalized
data structures. This helps in keeping data redundancies in check and ensures consistency.
Cascade Operations:
Triggers can be used to perform cascading actions when certain changes occur, such as
updating related records or performing additional actions in response to a modification.

Error Prevention:
Triggers can prevent certain types of errors by validating data before it is inserted, updated,
or deleted. This helps to ensure that only valid and consistent data is stored in the database.
Notification and Alerts:
Triggers can be configured to send notifications or alerts when specific conditions are met.
This is useful for real-time monitoring and response to critical events.

TYPES OF TRIGGERS

In a database management system (DBMS), there are generally two main types of triggers:
Row-level triggers and Statement-level triggers. These triggers are activated in response to
specific events, such as INSERT, UPDATE, DELETE, or other database-related actions.
Additionally, triggers can be classified based on when they are executed, resulting in
BEFORE and AFTER triggers. Here are the common types:
Row-Level Triggers:
BEFORE Row-Level Trigger: This trigger is executed before each row affected by the
triggering statement. It allows for validation or modification of data before it is actually
changed in the table.
AFTER Row-Level Trigger: Executed after each row affected by the triggering statement has
been processed. It can be used to perform actions based on the changes made to the data.

Statement-Level Triggers:
BEFORE Statement-Level Trigger: This trigger is executed once before the triggering SQL
statement is executed. It is useful for actions that should be performed once, regardless of
the number of rows affected.
AFTER Statement-Level Trigger: Executed once after the triggering SQL statement has been
executed. It can be used for actions that should be performed once after all rows have been
processed.

Instead of Triggers:
These triggers are associated with views and are used to replace the standard actions
(INSERT, UPDATE, DELETE) associated with the view. They allow for custom processing of
changes made to the view.
DML Triggers:
These triggers respond to Data Manipulation Language (DML) events such as INSERT,
UPDATE, and DELETE statements. Row-level and statement-level triggers are examples of
DML triggers.

DCL Triggers:
These triggers respond to Data Control Language (DCL) events, such as GRANT and REVOKE
statements. They are not as common as DML triggers but can be used for security-related
actions.

Nested Triggers:
Some database systems support nested triggers, which are triggers that can, in turn,
execute other triggers. The depth of nesting is usually controlled to prevent infinite loops or
excessive recursion.

Compound Triggers (Oracle):


Oracle Database introduced compound triggers to address certain limitations of traditional
triggers. A compound trigger is a single trigger that can include multiple timing points
(BEFORE/AFTER), multiple trigger events (INSERT, UPDATE, DELETE), and multiple trigger
bodies.

Logon and Logoff Triggers:


Some database systems support triggers that execute when a user logs in or logs out of the
database. These can be used for tasks such as auditing or setting session-specific
parameters.

EXAMPLE
CREATE OR REPLACE TRIGGER enforce_salary_limit
BEFORE INSERT ON employees
FOR EACH ROW
DECLARE
max_salary NUMBER := 10000; -- Set the maximum salary as per your requirement
BEGIN
IF :NEW.salary > max_salary THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary exceeds the allowed limit');
END IF;
END;
/

Verify Trigger Creation:


After creating the trigger, you can query the user_triggers view to verify that it has been
created successfully:
SELECT trigger_name, trigger_type, table_name
FROM user_triggers
WHERE table_name = 'EMPLOYEES';
“ Replace 'EMPLOYEES' with the name of your target table.”

CURSOR
A cursor is a mechanism that allows you to traverse the result set of a query. Cursors are
commonly used in database programming to work with query results one row at a time, and
they provide fine-grained control over the processing of data.
There are two main types of cursors: Implicit Cursors and Explicit Cursors.
1. Implicit Cursors:
Implicit cursors are automatically created by the Oracle database engine for all SQL DML (Data
Manipulation Language) statements, such as SELECT, INSERT, UPDATE, and DELETE. These
cursors are managed by the system, and you don't have to explicitly declare or control them.
However, you can retrieve information about the execution of the last SQL statement using
the SQL% attributes.

Example of an implicit cursor:


DECLARE
v_employee_name employees.employee_name%TYPE;
BEGIN
SELECT employee_name INTO v_employee_name
FROM employees
WHERE employee_id = 101;

DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name);


END;
/

2. Explicit Cursors:
Explicit cursors are defined and managed by the developer. They provide more control over
the result set traversal, and they are useful in situations where you need to fetch and process
multiple rows one at a time.

Example of an explicit cursor:


DECLARE
CURSOR employee_cursor IS
SELECT employee_id, employee_name
FROM employees
WHERE department_id = 10;

v_employee_id employees.employee_id%TYPE;
v_employee_name employees.employee_name%TYPE;
BEGIN
OPEN employee_cursor;
LOOP
FETCH employee_cursor INTO v_employee_id, v_employee_name;
EXIT WHEN employee_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_employee_id || ', Employee Name: ' ||
v_employee_name);
END LOOP;
CLOSE employee_cursor;
END;
/
In above example, we declare an explicit cursor named employee_cursor to retrieve
employee information from the "employees" table for a specific department. We then open
the cursor, fetch each row into variables, process the data, and finally close the cursor.
Remember to close the cursor explicitly after fetching the rows to release associated
resources.

You might also like