Trigger

Insert | Update | Delete

Trigger
-Is used to execute a batch of SQL code.
-Associted with single table.
-Trigger is fired whenever specified action (INSERT, UPDATE, or DELETE SQL command)
is executed against table.

Create Trigger
-Enterprise Manager>Pubs(db)>authors(tb)
-Right click>All tasks>Manage trigger

Create Trigger

Testing Trigger

CREATE TRIGGER trig_addAuthor
ON authors
FOR INSERT

AS

-- Get the first and last name of new author
DECLARE @newName VARCHAR(100)
SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted) //virtual table

-- Print the name of the new author
P RINT 'New author "' + @newName + '" added.'

-Initialize Query Analyzer
-Execute following code

USE pubs
SET NOCOUNT ON

INSERT INTO authors(au_id, au_lname, au_fname, phone, address, city, state, zip, contract)
VALUES('172-85-4534', 'Doe', 'John', '123456', '1 Black Street', 'Doeville', 'CA', '90210', 0)

Result
New author "John Doe" added.

 

CREATE TRIGGER trig_updateAuthor
ON authors
FOR UPDATE

AS

DECLARE @oldName VARCHAR(100)
DECLARE @newName VARCHAR(100)

IF NOT UPDATE(au_fName) AND NOT UPDATE(au_lName)

BEGIN
RETURN
END

SELECT @oldName = (SELECT au_fName + ' ' + au_lName FROM Deleted)
SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted)

PRINT 'Name changed from "' + @oldName + '" to "' + @newName + '"'

UPDATE authors

SET au_lName = 'Black'

WHERE au_id = '172-32-1176'

Result
Name changed from "John Doe" to "John Black"

 

CREATE TRIGGER trig_delAuthor
ON authors
FOR DELETE

AS

DECLARE @isOnContract BIT
SELECT @isOnContract = (SELECT contract FROM Deleted)

IF(@isOnContract = 1)
BEGIN

PRINT "Code to notify publisher goes here"
END

 

Back

@Copy right of Soon Lim 2006. All Right Reserved