You are on page 1of 48

Implementing Triggers and Transactions

Objectives
In this lesson, you will learn to:
Create the INSERT, DELETE, and UPDATE triggers
Modify triggers
Drop triggers
Enforce data integrity through triggers
Use the AFTER triggers
Implementing Triggers and Transactions

10.D.1 Using the INSERT Trigger


When a new row is inserted in the Requisition table, the
value of the siNoOfVacancy attribute should be less than the
difference between the iBudgetedStrength and
iCurrentStrength attributes of the Position table. Ensure that
this user-defined data integrity requirement is implemented.
Implementing Triggers and Transactions

Task List
Identify the object that can maintain user-defined data
integrity
Draft statements to create an INSERT trigger
Create a trigger in the database
Check the existence of the trigger in the database
Insert a row in the Requisition table and verify that the trigger
is working
Implementing Triggers and Transactions

Identify the object that can maintain user-defined data


integrity
A trigger is a block of code that constitutes a set of T-SQL
statements that are activated in response to certain actions
Characteristics of a Trigger
 It is fired automatically by SQL Server when any data
modification statement is issued
 It cannot be explicitly invoked or executed, as in the case
of the stored procedures
Implementing Triggers and Transactions

Identify the object that can maintain data integrity


(Contd.)
 It prevents incorrect, unauthorized or inconsistent changes
in data
 It cannot return data to the user
Result:
 A trigger can be used to maintain data integrity
Implementing Triggers and Transactions

Draft the statements to create an INSERT trigger


Creating triggers
 Triggers can be created in the Query Analyzer window by
using the CREATE TRIGGER statement

 Syntax
CREATE TRIGGER trigger_name
ON table_name
[WITH ENCRYPTION]
FOR [INSERT | DELETE | UPDATE]
AS sql_statements
Implementing Triggers and Transactions

Draft the statements to create an INSERT trigger


(Contd.)
Magic tables
 Whenever a trigger fires in response to the INSERT,
DELETE, or UPDATE statement, two special tables are
created. These are the inserted and the deleted tables.
They are also referred to as magic tables
 The inserted table contains a copy of all records that are
inserted in the trigger table
 The deleted table contains all records that have been
deleted from the trigger table
 Whenever any updation takes place, the trigger uses both
the inserted and the deleted tables
Implementing Triggers and Transactions

Draft the statements to create an INSERT trigger


(Contd.)
The INSERT Trigger
 An INSERT trigger is fired whenever an attempt is made to
insert a row in the trigger table
 When an INSERT statement is issued, a new row is added
to both the trigger and the inserted tables
Implementing Triggers and Transactions

Draft the statements to create an insert trigger (Contd.)


Action:
 The table on which the trigger has to be created is
Requisition
 The trigger has to be of insert type
 The name of the trigger can be trgInsertRequisition
 Write the batch statements
CREATE TRIGGER trgInsertRequisition
ON Requisition FOR insert AS
DECLARE @VacancyReported int
DECLARE @ActualVacancy int
SELECT @ActualVacancy = iBudgetedStrength -
iCurrentStrength
Implementing Triggers and Transactions

Draft the statements to create an insert trigger (Contd.)


FROM Position Join Inserted on
Position.cPositionCode =
Inserted.cPositionCode
SELECT @VacancyReported =
inserted.siNoOfVacancy
FROM inserted
IF(@VacancyReported > @Actualvacancy)
BEGIN
PRINT 'The actual vacancies are less than the
vacancies reported. Hence, cannot insert.'
ROLLBACK TRANSACTION
END
RETURN
Implementing Triggers and Transactions

Create a trigger in the database


Action:
 Type the drafted code in the Query Analyzer window
 Press F5 to execute the code
Implementing Triggers and Transactions

Check the existence of the trigger in the database


Action:
sp_help trgInsertRequisition
Implementing Triggers and Transactions

Insert a row in the Requisition table and verify that the


trigger is working
Action:
INSERT Requisition
VALUES('000003','0001',getdate(), getdate()
+ 7, '0001', 'North', 20)
Implementing Triggers and Transactions

Just a Minute...
1. What are magic tables?
2. Which statement is used to create triggers?
Implementing Triggers and Transactions

10.P.1 Using the INSERT Trigger


When a new row is added to the Employee table, the
iCurrentStrength attribute of the Position table should be
increased by one.
Implementing Triggers and Transactions

10.D.2 Using the DELETE Trigger


Create a trigger to disable deleting rows from the
ContractRecruiter table
Implementing Triggers and Transactions

Task List
Draft statements to create a delete trigger
Create the trigger in the database
Check the existence of the trigger in the database
Delete a row from the ContractRecruiter table to verify the
trigger
Implementing Triggers and Transactions

Draft statements to create a DELETE trigger


DELETE trigger
 A DELETE trigger is fired whenever an attempt is made
to delete rows from the trigger table
Implementing Triggers and Transactions

Draft statements to create a DELETE trigger (Contd.)


Result:
 The table on which the trigger is to be created is
ContractRecruiter
 The trigger is a DELETE trigger
 The name of the trigger is trgDeleteContractRecruiter
 The batch statements are:
CREATE TRIGGER trgDeleteContractRecruiter
ON ContractRecruiter FOR delete
AS
PRINT 'Deletion of Contract Recruiters is
not allowed'
ROLLBACK TRANSACTION RETURN
Implementing Triggers and Transactions

Create the trigger in the database


Action:
 Type the drafted code in the Query Analyzer window
 Press F5 to execute the code
Check the existence of the trigger in the database
Action:
sp_help trgDeleteContractRecruiter
Implementing Triggers and Transactions

Delete a row from the ContractRecruiter table to verify


the trigger
Action:
 Execute the following statement:
DELETE ContractRecruiter
WHERE cContractRecruiterCode = '000001'
 When this command is executed, the trigger would be
fired and it would prevent the deletion of rows from the
ContractRecruiter table
Implementing Triggers and Transactions

Just a Minute...
When is a DELETE trigger fired?
Implementing Triggers and Transactions

10.D 3. Using the UPDATE Trigger


Create a trigger so that the average siPercentageCharge
attribute of the ContractRecruiter table should not be more
than 11 when the value of siPercentageCharge is increased
for any ContractRecruiter
Implementing Triggers and Transactions

Task List
Draft statements to create an update trigger
Create the trigger in the database
Check the existence of the trigger in the database
Update siPercentageCharge of the ContractRecruiter table
and verify that the average does not exceed the required
value
Implementing Triggers and Transactions

Draft statements to create an UPDATE trigger


The UPDATE trigger
 This trigger is fired whenever there is a modification to
the trigger table
Result:
 The table on which the trigger is to be created is
ContractRecruiter
 The trigger is an UPDATE trigger
 The name of the trigger is trgUpdateContractRecruiter
Implementing Triggers and Transactions

Draft statements to create an UPDATE trigger (Contd.)


 The trigger is:
CREATE TRIGGER trgUpdateContractRecruiter
ON ContractRecruiter FOR UPDATE
AS
DECLARE @AvgPercentageCharge int
SELECT @AvgPercentageCharge =
avg(siPercentageCharge)
FROM ContractRecruiter
IF(@AvgPercentageCharge > 11)
BEGIN
PRINT 'The average cannot be more than 11'
ROLLBACK TRANSACTION
END
RETURN
Implementing Triggers and Transactions

Create the trigger in the database


In the Query Analyzer window, type the draft code
Press F5 to execute the code

Check the existence of the trigger in the database


Action:
sp_help trgUpdateContractRecruiter
Implementing Triggers and Transactions

Update siPercentageCharge of the ContractRecruiter


table and verify that the average does not exceed the
required value
Action:
 Execute the following UPDATE statement:
UPDATE ContractRecruiter
SET siPercentageCharge
=siPercentageCharge+10
WHERE cContractRecruiterCode='0002’
If the average exceeds the limit, then the trigger would
generate an error message
Implementing Triggers and Transactions

10.P.2 Using the UPDATE Trigger


When an employee resigns, the resignation date is updated
in the Employee table. After the resignation date is updated,
the iCurrentStrength attribute of the Position table should be
decreased by 1.
Implementing Triggers and Transactions

10.D.4 Modifying the Trigger


Modify the trigger trgInsertRequisition that was created
earlier to check whether the siNoOfVacancy attribute is less
than the difference between iBudgetedStrength and
iCurrentStrength from the Position table. If so, the trigger
should display a message:
“Sorry, the available vacancy is less than the reported
vacancy. The transaction cannot be processed.”
Implementing Triggers and Transactions

Task List
Draft the command to modify the trigger
Create the trigger in the database
Check that the trigger has been modified in the database
Insert a row in the Requisition table and verify that the trigger
is working
Implementing Triggers and Transactions

Draft the command to modify the trigger


The ALTER TRIGGER Command
 The contents of a trigger can be modified by:
 Dropping the trigger and recreating it
 Using the ALTER TRIGGER statement
 It is advisable to drop a trigger and recreate it, if the
objects being referenced by it are renamed
Implementing Triggers and Transactions

Draft the command to modify the trigger (Contd.)


 Syntax:
ALTER TRIGGER trigger_name
ON table_name
[WITH ENCRYPTION]
FOR [INSERT | DELETE | UPDATE]
AS sql_statements
Action:
 The table on which the trigger had been created is
Requisition
 Determine the type of trigger
 The name of the trigger to be modified is
trgInsertRequisition
Implementing Triggers and Transactions

Draft the command to modify the trigger (Contd.)


 Write the batch statements:
ALTER TRIGGER trgInsertRequisition ON
Requisition
FOR insert
AS
DECLARE @VacancyReported int
DECLARE @ActualVacancy int
SELECT @ActualVacancy = iBudgetedStrength –
iCurrentStrength
FROM Position
SELECT @VacancyReported =
inserted.siNoOfVacancy
FROM inserted
Implementing Triggers and Transactions

Draft the command to modify the trigger (Contd.)


IF(@VacancyReported > @ActualVacancy)
BEGIN
Print 'Sorry, the available
vacancy is less than the reported vacancy.
The transaction cannot be processed.'
ROLLBACK TRANSACTION
END
RETURN
Create the trigger in the database
Action:
 In the Query Analyzer window, type the drafted code
 Press F5 to execute the batch statement
Implementing Triggers and Transactions

Check that the trigger has been modified in the


database
Action:
sp_helptext trgInsertRequisition

Insert a row in Requisition table and verify that the


trigger is working
Action:
INSERT Requisition
VALUES('000002','0001',getdate
(),getdate()+7,’0001','North',20)
Implementing Triggers and Transactions

Just a Minute...
Which statement is used to recreate a trigger?
Implementing Triggers and Transactions

10.D.5 Dropping the Trigger


The DELETE trigger named trgDeleteContractRecruiter
needs to be removed, as it is no longer required.
Implementing Triggers and Transactions

Task List
 Draft the command to delete the trigger
 Execute the command
 Verify that the trigger has been removed
Implementing Triggers and Transactions

Draft the command to delete the trigger


The DROP TRIGGER Command is used to delete a trigger
from the database
 Syntax:
DROP TRIGGER trigger_name[,..n]
Action:
 The command to delete the trigger would be:
DROP TRIGGER trgDeleteContractRecruiter
Implementing Triggers and Transactions

Execute the command


Action:
 In the Query Analyzer window, type the drafted code
 Press F5 to execute the batch statement

Verify that the trigger has been removed


Action:
sp_help trgDeleteContractRecruiter
 The above command will give an error message as the
trigger has been removed
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers


Triggers and Data Integrity
 A trigger can be used to enforce business rules and data
integrity in the following ways:
 If changes are made to the master table, then the same
changes are cascaded to all the dependent tables
 If some changes violate referential integrity, then all
such changes are rejected, thereby canceling any
attempt to modify data in the database
 It allows very complex restrictions to be enforced
 It can perform a particular action, depending on the
outcome of the modifications that have been made to
the tables
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers (Contd.)


Multiple Triggers
 SQL Server allows multiple triggers to be defined on a
given table. This implies that a single DML statement
may fire two or more triggers. The triggers are fired in the
order of creation
AFTER Triggers
 The AFTER trigger can be created on any table for the
INSERT, UPDATE, or DELETE operation just like the
normal triggers
 The AFTER trigger gets fired after the execution of the
DML operation for which it has been defined
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers (Contd.)


 By default, if more than one AFTER trigger is created on a
table for a DML operation such as INSERT, UPDATE, or
DELETE, then the sequence of execution is the order in
which they were created
Implementing Triggers and Transactions

Just a Minute...
How are triggers used to maintain integrity and consistency
of data?
Implementing Triggers and Transactions

Summary
In this lesson you learned that:
A trigger is a block of code that constitutes a set of T-SQL
statements that get activated in response to certain actions
A trigger fires in response to the INSERT, UPDATE, and
DELETE statements
A trigger can be created in the Query Analyzer by using the
CREATE TRIGGER statement
A magic table is a conceptual table that is structurally similar
to the table on which a trigger is defined
Implementing Triggers and Transactions

Summary (Contd.)
There are two types of magic tables:
 Inserted, which stores a copy of the rows that have been
inserted into the trigger table
 Deleted, which stores those records that have been
deleted from the trigger table
A trigger can be viewed using the sp_help and sp_helptext
system stored procedures
A trigger can be altered using the ALTER TRIGGER
statement
A trigger can be deleted using the DROP TRIGGER
statement
Implementing Triggers and Transactions

Summary (Contd.)
 A trigger can be used to enforce business rules and data
integrity
The AFTER trigger is executed after all constraints and triggers
defined on the table have successfully executed

You might also like