You are on page 1of 5

TRIGGERS

Contents
Triggers.................................................................................................................................................... 1
Types of triggers...................................................................................................................................... 1
Creating triggers...................................................................................................................................... 1
Examples of triggers ................................................................................................................................ 2
References .............................................................................................................................................. 3
Triggers
DML triggers are a special type of stored procedure that automatically takes effect when a data manipulation
language (DML) event takes place that affects the table or view defined in the trigger. You cannot explicitly
invoke triggers. DML events include INSERT, UPDATE, or DELETE statements. DML triggers can be used to enforce
business rules and data integrity, query other tables, and include complex Transact-SQL statements. The trigger
and the statement that fires it are treated as a single transaction, which can be rolled back from within the
trigger. If a severe error is detected (for example, insufficient disk space), the entire transaction automatically
rolls back.

Types of triggers
AFTER trigger
AFTER triggers are executed after the action of the INSERT, UPDATE, MERGE, or DELETE statement is
performed. AFTER triggers are never executed if a constraint violation occurs; therefore, these triggers
cannot be used for any processing that might prevent constraint violations. For every INSERT, UPDATE,
or DELETE action specified in a MERGE statement, the corresponding trigger is fired for each DML
operation.
INSTEAD OF trigger
INSTEAD OF triggers override the standard actions of the triggering statement. Therefore, they can be
used to perform error or value checking on one or more columns and then perform additional actions
before insert, updating or deleting the row or rows. For example, when the value being updated in an
hourly wage column in a payroll table exceeds a specified value, a trigger can be defined to either
produce an error message and roll back the transaction, or insert a new record into an audit trail before
inserting the record into the payroll table. The primary advantage of INSTEAD OF triggers is that they
enable views that would not be updatable to support updates. For example, a view based on multiple
base tables must use an INSTEAD OF trigger to support inserts, updates, and deletes that reference
data in more than one table. Another advantage of INSTEAD OF triggers is that they enable you to code
logic that can reject parts of a batch while letting other parts of a batch to succeed.
This table compares the functionality of the AFTER and INSTEAD OF triggers.

For the purposes of this course, you need only be able to write AFTER triggers.

Creating triggers
The basic syntax for creating a trigger is as follows:

CREATE TRIGGER [ schema_name . ]trigger_name


ON { table | view }
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

Triggers can also be created by expanding the node under the required table name, right-clicking on the Triggers
node and then selecting “New Trigger…” from the context menu.

1|Page
Figure 1: Creating a trigger

Examples of triggers
The following trigger prints a message to the client when anyone tries to add or change data in
the Customer table

CREATE TRIGGER reminder1


ON Sales.Customer
AFTER INSERT, UPDATE
AS RAISERROR ('Notify Customer Relations', 16, 10);

The following example sends an e-mail message to a specified person (MaryM) when the Customer table
changes.

CREATE TRIGGER reminder2


ON Sales.Customer
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'AdventureWorks2012 Administrator',
@recipients = 'danw@Adventure-Works.com',
@body = 'Don''t forget to print a report for the sales force.',
@subject = 'Reminder';

Because CHECK constraints can reference only the columns on which the column-level or table-level constraint
is defined, any cross-table constraints (in this case, business rules) must be defined as triggers.
The following example creates a DML trigger in the AdventureWorks2012 database. This trigger checks to make
sure the credit rating for the vendor is good (not 5) when an attempt is made to insert a new purchase order
into the PurchaseOrderHeader table. To obtain the credit rating of the vendor, the Vendor table must be
referenced. If the credit rating is too low, a message is displayed and the insertion does not execute.

-- This trigger prevents a row from being inserted in the


Purchasing.PurchaseOrderHeader table
-- when the credit rating of the specified vendor is set to 5 (below average).

CREATE TRIGGER Purchasing.LowCredit ON Purchasing.PurchaseOrderHeader


AFTER INSERT
AS
IF EXISTS (SELECT *
FROM Purchasing.PurchaseOrderHeader AS p
JOIN inserted AS i

2|Page
ON p.PurchaseOrderID = i.PurchaseOrderID
JOIN Purchasing.Vendor AS v
ON v.BusinessEntityID = p.VendorID
WHERE v.CreditRating = 5
)
BEGIN
RAISERROR ('A vendor''s credit rating is too low to accept new
purchase orders.', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;
GO

-- This statement attempts to insert a row into the PurchaseOrderHeader table


-- for a vendor that has a below average credit rating.
-- The AFTER INSERT trigger is fired and the INSERT transaction is rolled back.

INSERT INTO Purchasing.PurchaseOrderHeader (RevisionNumber, Status, EmployeeID,


VendorID, ShipMethodID, OrderDate, ShipDate, SubTotal, TaxAmt, Freight)
VALUES (
2
,3
,261
,1652
,4
,GETDATE()
,GETDATE()
,44594.55
,3567.564
,1114.8638 );

References
1. MSDN Library

3|Page

You might also like