Multiple triggers of the same type INSERT, UPDATE, or DELETE on a table allow multiple different actions to take place in response to the same modification statement.. The INSERTED tabl
Trang 1642 Chapter 14 • Implementing Objects
trigger to fire occur within the context of a single transaction It is possible to roll
back INSERT, UPDATE, and DELETE statements from within a trigger This is
useful for complex data validation purposes You can use triggers to manually
cascade changes through related tables; to guard against malicious or incorrect insert, update, and delete operations; and to enforce other restrictions that are more
complex than those defined by using CHECK constraints.
Ex a m Wa r n i n g
Triggers should be used sparingly because they have severe performance implications In addition,, triggers can be difficult to maintain.
Unlike CHECK constraints, triggers can reference columns in other tables For example, a trigger can use a SELECT statement from another table to compare
to the inserted or updated data and to perform additional actions, such as modifying the data, or displaying a user-defined error message Triggers can evaluate the state
of a table before and after a data modification and take actions based on that
difference Multiple triggers of the same type (INSERT, UPDATE, or DELETE)
on a table allow multiple different actions to take place in response to the same modification statement Triggers also allow the use of custom error messages
Triggers can be specified as FOR, AFTER, or INSTEAD OF The trigger action will fire during the DML statement, after the DML statements, or in place of the DML statement, respectively Triggers can be specified for UPDATE, INSERT,
DELETE, or any combination of these.
How do you know what data the user is attempting to insert, update, or delete
within a trigger? The trigger can access special tables called INSERTED and
DELETED These virtual tables exist only while the trigger is executing The INSERTED table contains the new values you are attempting to insert into the
table, or new values of the row when you are attempting to update data The
DELETED table contains the row you are attempting to delete or old values of the
row when you are attempting to update data Make use of these tables by querying them to determine old and new values of the data being affected To cancel the
DML statement from within a trigger and roll it back, use the ROLLBACK
TRANSACTION statement.
Example 14.17 demonstrates how to create triggers, and the effect they take
after a DML statement is executed on the table to which the trigger is bound.
Trang 2Example 14.17 Creating a Trigger on the Stars Table
CREATE TABLE StarHistory
(StarHistoryId int IDENTITY PRIMARY KEY, StarName varchar(50), OldType
ntext, NewType ntext, DateChanged DateTime);
GO
CREATE TRIGGER UpdateStarHistory
on dbo.Stars
AFTER INSERT, UPDATE
AS
BEGIN
INSERT StarHistory (StarName, OldType, NewType, DateChanged)
SELECT INSERTED.StarName, DELETED.StarType, INSERTED.StarType,
GETDATE()
FROM INSERTED LEFT JOIN DELETED on INSERTED.StarID = DELETED.StarID
END
GO
UPDATE Stars SET StarType = 'Burnt out' WHERE StarName = 'Sun';
GO
SELECT * FROM StarHistory
Results:
StarHistoryId StarName OldType NewType DateChanged
- - -
- 1 Sun Yellow dwarf Burnt out 2009-01-21
11:56:29.530
TesT Day Tip
You don’t need to be able to write a trigger for the exam Make sure
that you understand the concepts behind triggers and why you may wish
to use them Remember that triggers can be defined on views as well
Creating INSTEAD OF triggers on a view that is not updateable will allow
you to perform actions when a user attempts to insert, update, or delete
data in the view.
Trang 3644 Chapter 14 • Implementing Objects
EXERCISE 14.2
Working With VieWs and stored ProCedures
In this exercise, you will use Transact-SQL statements to create views and
stored procedures that show and modify data in the Planets table that you created in Exercise 14.1 Make sure that you have completed
Exercise 14.1 before proceeding with this exercise.
1 Switch to SQL Server Management Studio.
2 Create a new query against the AdventureWorks database.
3 Create a view named TerrestrialPlanets that shows planet name
and planet description for only those planets where the type is
“Terrestrial Planet” and insert a new row into the view View the data in the underlying table to ensure the new row has been inserted Use the following statement.
CREATE VIEW TerrestrialPlanets AS SELECT PlanetName, PlanetDescription FROM Planets
WHERE PlanetType = 'Terrestrial Planet' GO
SELECT * FROM TerrestrialPlanets;
INSERT TerrestrialPlanets VALUES ('Mars', 'Mars is the fourth planet from the Sun in the Solar System.')
SELECT * FROM Planets
4 Create a trigger that will update the PlanetType to “Terrestrial
Planet” when a new row is inserted into the TerrestrialPlanets
view Use the following statement.
DELETE FROM Planets WHERE PlanetName = 'Mars';
GO CREATE TRIGGER UpdatePlanetType
on dbo.Planets AFTER INSERT AS
Trang 4UPDATE Planets SET PlanetType = 'Terrestrial Planet'
FROM Planets join INSERTED ON INSERTED.PlanetName = Planets.
PlanetName
END
GO
INSERT TerrestrialPlanets
VALUES ('Mars', 'Mars is the fourth planet from the Sun in the
Solar System.')
SELECT * FROM Planets
5 Create and test a stored procedure that will update the radius for
a given planet Use the following statement.
CREATE PROCEDURE UpdateRadius
@Radius int,
@PlanetName varchar(50) AS
BEGIN
UPDATE Planets SET Radius = @Radius WHERE PlanetName = @
PlanetName
END;
GO
EXECUTE UpdateRadius 3376, 'Mars';
GO
SELECT PlanetName, Radius FROM Planets
Trang 5646 Chapter 14 • Implementing Objects
Summary of Exam Objectives
In this chapter you have learned about creating database objects As a database administrator, you must understand the types of objects that comprise a database system Database objects are divided into two broad categories: storage and
pro-grammability Tables store data and are created using the CREATE TABLE
state-ment For each column in the table you must select a built-in or a user-defined data type Indexes are created on tables to maximize query performance Constraints are associated with table columns and define the rules to which data in a particular column or columns must adhere Constraints can also define relationships between tables, like the necessity to have a Customer entity associated with every Order
entity These are known as foreign key constraints.
Programmability objects allow you to define Transact-SQL statements that will
be reused over and over again Views are based on Transact-SQL SELECT
state-ments They represent a way of viewing a data set, and they show data from one or more underlying tables Views based on a single underlying table can be updated
Specifying the WITH SCHEMABINDING option when creating a view prevents
the underlying table from being modified, if the modification will affect the view
Stored procedures are compiled Transact-SQL statements that perform particular actions
Stored procedures can accept parameters and return values Functions are similar to
stored procedures, except that they always return a value, and they never update data
Triggers are actions defined on tables that will execute every time data in a table
changes Triggers can be created FOR UPDATE, FOR DELETE, and FOR INSERT You can also create triggers for AFTER and INSTEAD OF DML operations.
Exam Objectives Fast Track
Understanding DDL and DML Language Elements
Data Definition Language (DDL) contains statements used to add, modify,
˛
and remove objects from the database The DDL statements are CREATE,
ALTER, and DROP These statements can be used to create and manipulate
tables, data types, indexes, views, stored procedures, functions, and triggers Data Manipulation Language (DML) is a part of the Transact-SQL
lan-˛
guage that allows you to insert, modify, and delete data in SQL Server
tables The core statements that comprise DML are INSERT, UPDATE,
DELETE, and MERGE.
DDL manipulates database structure, while DML manipulates actual data
˛
stored in tables