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

Chapter 6 DAatabaseTrigger 1 1

This document covers the concept of database triggers in PL/SQL, which are stored programs that automatically execute in response to specific events on tables, views, or schemas. It discusses the advantages of triggers, including automation, data integrity, and security, as well as the different types of triggers such as AFTER and INSTEAD OF triggers, and row-level versus statement-level triggers. Additionally, it provides examples of creating triggers for auditing customer data, preventing updates and deletes, and generating primary key values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 6 DAatabaseTrigger 1 1

This document covers the concept of database triggers in PL/SQL, which are stored programs that automatically execute in response to specific events on tables, views, or schemas. It discusses the advantages of triggers, including automation, data integrity, and security, as well as the different types of triggers such as AFTER and INSTEAD OF triggers, and row-level versus statement-level triggers. Additionally, it provides examples of creating triggers for auditing customer data, preventing updates and deletes, and generating primary key values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Advance Database using PL/SQL

Unit 6 : Database Triggers

PL/SQL – Triggers
• Triggers are stored programs, which are automatically executed or
fired when some events occur.
• Triggers can be defined on the table, view, schema, or database with
which the event is associated.
• Triggers are used to specify certain integrity constraints and
referential constraints that cannot be specified using the constraint
mechanism of SQL.
Advance Database using PL/SQL
Unit 6 : Database Triggers

Advantage of Triggers
• Automation: Triggers automate tasks, reducing manual effort and ensuring consistent actions in
response to specific events.
• Enforcing Rules: Triggers enforce business rules, validating data and maintaining consistency within
the database.
• Data Integrity: Triggers prevent invalid changes, preserving data integrity and safeguarding against
corruption.
• Audit Trail: Triggers create an audit trail, tracking modifications and ensuring accountability for data
changes.
• Security: Triggers enhance security, validating user actions and restricting access to sensitive data.
• Simplicity: Triggers simplify complex operations, encapsulating intricate logic within the database.
• Performance: Triggers can enhance performance by reducing the number of interactions with the
database in certain scenarios.
Advance Database using PL/SQL
Unit 6 : Database Triggers

Types of Triggers
There are two main types of triggers based on the timing of their execution: AFTER Triggers and INSTEAD OF Triggers.

AFTER Triggers: These triggers execute after the triggering action (INSERT, UPDATE, DELETE)
has occurred. They are commonly used for tasks such as auditing, enforcing business rules, and
cascading changes to related tables.
Syntax:
CREATE TRIGGER trigger_name ON table_name
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
-- Trigger logic
END;
Advance Database using PL/SQL
Unit 6 : Database Triggers

Types of Triggers
There are two main types of triggers based on the timing of their execution: AFTER Triggers and INSTEAD OF Triggers.

INSTEAD OF Triggers: These triggers replace the triggering action with the logic defined inside the trigger. They are
often used with views and allow you to customize how data modifications are handled.

Syntax:

CREATE TRIGGER trigger_name ON view_name


INSTEAD OF INSERT, UPDATE, DELETE
AS
BEGIN
-- Trigger logic
END;
Advance Database using PL/SQL
Unit 6 : Database Triggers

Types of Triggers
Triggers can also be classified based on the level at which they operate:

Row-Level Triggers: These triggers operate on each row affected by the triggering statement.
They can access the data of the row being modified and are defined using the FOR EACH
ROW clause (which is the default behavior in most databases).

Statement-Level Triggers: These triggers operate once for each triggering statement,
regardless of the number of rows affected. They do not have access to the individual rows
being modified and are defined without the FOR EACH ROW clause.
Advance Database using PL/SQL
Unit 6 : Database Triggers

Syntax of - Triggers
CREATE TRIGGER trigger_name ON table_name
AFTER INSERT, UPDATE, DELETE -- Specify the event(s) that will
activate the trigger
AS
BEGIN
-- Trigger logic goes here
END;
Advance Database using PL/SQL
Unit 6 : Database Triggers

AFTER INSERT Trigger


An AFTER INSERT trigger is executed automatically after a new row has
been inserted into the table.

Syntax,
CREATE TRIGGER trigger_name
ON table_name
AFTER INSERT
AS
-- Trigger logic here
Advance Database using PL/SQL
Unit 6 : Database Triggers

AFTER UPDATE Trigger


An AFTER UPDATE trigger is executed automatically after an existing
row in the table has been updated.
Syntax,
CREATE TRIGGER trigger_name
ON table_name
AFTER UPDATE
AS
-- Trigger logic here
Advance Database using PL/SQL
Unit 6 : Database Triggers

AFTER DELETE Trigger


An AFTER DELETE trigger is executed automatically after a row has
been deleted from the table.
Syntax,
CREATE TRIGGER trigger_name
ON table_name
AFTER DELETE
AS
-- Trigger logic here
Advance Database using PL/SQL
Unit 6 : Database Triggers

AFTER DELETE Trigger


An AFTER DELETE trigger is executed automatically after a row has
been deleted from the table.
Syntax,
CREATE TRIGGER trigger_name
ON table_name
AFTER DELETE
AS
-- Trigger logic here
Advance Database using PL/SQL
Unit 6 : Database Triggers

Example Based on MYSTORE-Customer table


We have customer table , select * from Customer

CREATE TRIGGER tr_Customer_Insert ON [dbo].[Customer]


AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CustomerName NVARCHAR(250)
-- Get the newly inserted CustomerName
SELECT @CustomerName = CustomerName FROM INSERTED
-- Print a message indicating a new customer has been added
PRINT 'New customer added: ' + @CustomerName
END
Advance Database using PL/SQL
Unit 6 : Database Triggers

Example Based on MYSTORE-Customer table


trigger , tr_Customer_Insert is created ,
Advance Database using PL/SQL
Unit 6 : Database Triggers

Example Based on MYSTORE-Customer table


When we insert data on customer table,
insert into Customer values ('Richa','Chitwan','985654098','[email protected]')

After inserting data trigger will be executed, as result will be

The trigger retrieves the CustomerName of the newly inserted row from the INSERTED
table and prints a message indicating the new customer's name.
Advance Database using PL/SQL
Unit 6 : Database Triggers
Example Based on MYSTORE-Customer table
we will create a trigger that stores transaction records of each insert operation on the Customer

Create table that will store the changes on parent table,


CREATE TABLE Customer_Audit(
[CustomerID] [int] ,
[CustomerName] [nvarchar](250) NULL,
[Address] [nvarchar](50) NULL,
[MobileNo] [nvarchar](12) NULL,
[Email] [nvarchar](150) NULL,
[AuditID] [bigint] IDENTITY(1,1) NOT NULL, --- unique audit id
[AuditAction] [char](1) NULL,--- Audit action I for inserted , U for Update, D for delete
[AuditDate] [datetime] default getdate(), -- default datetime of trigger action
)
Advance Database using PL/SQL
Unit 6 : Database Triggers
Example Based on MYSTORE-Customer table
we will create a trigger that stores transaction records of each insert operation on the Customer
table,

create TRIGGER tr_Customer_Audit_on_insert ON Customer


FOR insert AS
INSERT INTO Customer_Audit(
CustomerID ,
CustomerName,
Address ,
MobileNo ,
Email ,
AuditAction
)
SELECT *,'I' FROM inserted
Advance Database using PL/SQL
Unit 6 : Database Triggers
Example Based on MYSTORE-Customer table
When we insert any data on customer table then ,
tr_Customer_Audit_on_insert will executed to insert data on audit table
Customer_Audit
Advance Database using PL/SQL
Unit 6 : Database Triggers
Update trigger Example Based on MYSTORE-
Customer table
We will create trigger , tr_Customer_Audit_on_update which will be executed
when we will update any data on customer table
create TRIGGER tr_Customer_Audit_on_update ON Customer
FOR update AS
insert INTO Customer_Audit(
CustomerID ,
CustomerName,
Address ,
MobileNo ,
Email ,
AuditAction
)
SELECT *,'U' FROM inserted
Advance Database using PL/SQL
Unit 6 : Database Triggers
Update trigger Example Based on MYSTORE-
Customer table
Advance Database using PL/SQL
Unit 6 : Database Triggers
Delete trigger Example Based on MYSTORE-
Customer table
We will create trigger , tr_Customer_Audit_on_delete which will be executed
when we will delete any data on customer table
create TRIGGER tr_Customer_Audit_on_delete
ON Customer
FOR delete AS
insert INTO Customer_Audit(
CustomerID ,
CustomerName,
Address ,
MobileNo ,
Email ,
AuditAction
)
SELECT *,'D' FROM inserted
Advance Database using PL/SQL
Unit 6 : Database Triggers
Trigger to prevent update
create trigger TG_Prevent_Update ON
customer
FOR update
AS
BEGIN
RAISERROR ('UNABLE TO UPDATE RECORD',16,1)
ROLLBACK
END
Advance Database using PL/SQL
Unit 6 : Database Triggers
Trigger to prevent Delete on table
create trigger TG_Prevent_Delete
ON customer FOR DELETE
AS
BEGIN
RAISERROR ('UNABLE TO DELETE RECORD',16,1)
ROLLBACK
END
Advance Database using PL/SQL
Unit 6 : Database Triggers
To Disable trigger

To Enable a Trigger:
Advance Database using PL/SQL
Unit 6 : Database Triggers
To Delete or remove trigger
Advance Database using PL/SQL
Unit 6 : Database Triggers

Frequently Asked Questions


Q1: What is an SQL trigger?

Q2: How do SQL triggers work?

Q3: What are the benefits of using SQL triggers?

Q4: What are the types of Triggers available in SQL Server?

Q5: If you have table customer , then write a trigger to prevent data to update and
delete.
Q6: Write a trigger to generate primary key value using a Lookup table
Q7: Write different between trigger and Procedures
Advance Database using PL/SQL
Unit 6 : Database Triggers
Q6: Write a trigger to generate primary key value using a Lookup table
CREATE TABLE lookup_table (
id INT PRIMARY KEY
);
CREATE TRIGGER generate_primary_key
BEFORE INSERT ON main_table
FOR EACH ROW
BEGIN
DECLARE next_id INT;
SELECT MAX(id) + 1 INTO next_id FROM lookup_table;
IF next_id IS NULL THEN
SET next_id = 1;
END IF;
SET NEW.id = next_id;
INSERT INTO lookup_table (id) VALUES (next_id);

End

You might also like