Trigger Sample

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

CREATE TABLE Person

(
SSN char(11) PRIMARY KEY,
Name nvarchar(100),
Address nvarchar(100),
Birthdate datetime
)

CREATE TABLE EmployeeTable


(
EmployeeID int PRIMARY KEY,
SSN char(11) UNIQUE,
Department nvarchar(10),
Salary money,
CONSTRAINT FKEmpPer FOREIGN KEY (SSN)
REFERENCES Person (SSN)
)

This view reports all relevant data from the two tables for a person:

CREATE VIEW Employee AS


SELECT P.SSN as SSN, Name, Address,
Birthdate, EmployeeID, Department, Salary
FROM Person P, EmployeeTable E
WHERE P.SSN = E.SSN

You can record attempts to insert rows with duplicate social security numbers. The
PersonDuplicates table logs the inserted values, the name of the user who
attempted the insert, and the time of the insert:

CREATE TABLE PersonDuplicates


(
SSN char(11),
Name nvarchar(100),
Address nvarchar(100),
Birthdate datetime,
InsertSNAME nchar(100),
WhenInserted datetime
)

The INSTEAD OF trigger inserts rows into multiple base tables from a single view.
Attempts to insert rows with duplicate social security numbers are recorded in the
PersonDuplicates table. Duplicate rows in the EmployeeTable are changed to update
statements.

CREATE TRIGGER IO_Trig_INS_Employee ON Employee


INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
FROM Person P, inserted I
WHERE P.SSN = I.SSN))
INSERT INTO Person
SELECT SSN,Name,Address,Birthdate,Comment
FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
INSERT INTO PersonDuplicates
SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
FROM EmployeeTable E, inserted
WHERE E.SSN = inserted.SSN))
INSERT INTO EmployeeTable
SELECT EmployeeID,SSN, Department, Salary,Comment
FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
UPDATE EmployeeTable
SET EmployeeID = I.EmployeeID,
Department = I.Department,
Salary = I.Salary,
Comment = I.Comment
FROM EmployeeTable E, inserted I
WHERE E.SSN = I.SSN
END

�1988-2000 Microsoft Corporation. All Rights Reserved.

==================================================================================
Examples
A. Use an AFTER INSERT trigger
The following example assumes the existence of a table called newsale in the pubs
database. This the CREATE statement for newsale:

CREATE TABLE newsale


(stor_id char(4),
ord_num varchar(20),
date datetime,
qty smallint,
payterms varchar(12),
title_id tid)

If you want to examine each of the records you are trying to insert, the trigger
conditionalinsert analyzes the insert row by row, and then deletes the rows that
do not have a title_id in titles.

CREATE TRIGGER conditionalinsert


ON sales
AFTER INSERT AS
IF
(SELECT COUNT(*) FROM titles, inserted
WHERE titles.title_id = inserted.title_id) <> @@ROWCOUNT
BEGIN
DELETE sales FROM sales, inserted
WHERE sales.title_id = inserted.title_id AND
inserted.title_id NOT IN
(SELECT title_id
FROM titles)
PRINT 'Only sales records with matching title_ids added.'
END
When unacceptable titles have been inserted, the transaction is not rolled back;
instead, the trigger deletes the unwanted rows.
This ability to delete rows that have been inserted relies on the order in which
processing occurs when triggers are fired.
First, rows are inserted into the sales table and the inserted table, and then the
trigger fires.

To test the trigger, insert four rows in the newsale table. Two of the newsale
rows
have title_ids that do not match any of those already in the titles table:

=================================================================================

-- to save a backup copy of table before delete data of table(Important trigger)


You can use nested triggers to perform useful housekeeping functions such as
storing a backup copy of rows affected by a previous trigger. For example, you can
create a trigger on titleauthor that saves a backup copy of the titleauthor rows
that the delcascadetrig trigger deleted. With the delcascadetrig trigger in
effect, deleting title_id PS2091 from titles deletes the corresponding row or rows
from titleauthor. To save the data, you create a DELETE trigger on titleauthor
that saves the deleted data into another separately created table, del_save. For
example:

CREATE TRIGGER savedel


ON titleauthor
FOR DELETE
AS
INSERT del_save
SELECT * FROM deleted
==============================

You might also like