Professional Documents
Culture Documents
SCHOOL/DEPT:
COURSE OF STUDY:
YEAR:
Three (3)
Introductory Notes:
Today we will be looking at the triggers and how they are used in our SQL Server Environment.
NB This trigger will return the result set of the record you are trying to insert. Our
expected result is that we should not see the record in our customer table. Instead we
should see the record being displayed because thats what we told it to do.
Example 2
CREATE TRIGGER before_insert_customer
ON customer INSTEAD OF INSERT
AS
Select DOB, last_name from Inserted
Comment [RW2]:
temporary row.
PLEASE DROP THE TRIGGERS AFTER YOU HAVE TRIED IT. IF YOU LEAVE THE TRIGGER IT MEANS
THAT YOU CAN NO LONGER INSERT.
Exercise 1
a) Develop the trigger in example 1 for marketing list.
I.
II.
III.
b) Create a table called Child List that has the same fields as Marketing List. Develop a
trigger that will be placed on the marketing list table that will insert a record into the
2
Comment
[R3]:
of the record.
Example 4 After Trigger (Lets say we wanted to display the recorded after it was deleted.)
CREATE TRIGGER before_delete_customer
ON customer AFTER DELETE
AS
Select * from deleted
Exercise 2
a) Try the trigger in example 3 for marketing list. Try to delete some records what are your
observations? [Remember to drop your trigger]
b) Create a table called Audit_Log that has the same fields as marketing list with 3
additional fields: Audit_Action, Audit_Table, Action_Date.
c) Develop triggers that will be placed on both the customer and child tables that will track
any record deleted and place them in the Audit_Log Table while populating the three
additional audit fields.
Hint:
INSERT INTO customer (first_name, last_name, sign_up_date )
SELECT first_name, last_name, getdate() from mailing_list ;
Comment [RW4]:
Example 1
CREATE TRIGGER update _customer
ON customer AFTER UPDATE
AS
Select DOB, last_name from Inserted
Comment
[RW6]:
temporary row.
Comment
[RW7]:
temporary row.
Exercise 3
a) Try the two examples above for marketing _list. Ensure for example 2 you are updating
the last_name and DOB of a customer.
b) Alter your marketing_list table and add a Date created field. Default the value to the
current date.
c) Create a trigger that only allows updates to records that are less than three days old.
d) Create a trigger that stores the old version of a record to the audit_log table with the
appropriate audit fields updated.
e) Create a trigger that will only update a record if the old record is different from the new.
5
BEGIN
Select The last name was changed
END
PLEASE DROP THE TRIGGER AFTER YOU HAVE TRIED IT.
Exercise 4
a) Create an update trigger on Marketing_list and Child that checks if the DOB has been
updated. If the new DOB is 18 and over in Child move the record to Customer table and
vice versa for Customer.