Вы находитесь на странице: 1из 4

Triggers and Indexes

Introduction
This lesson introduces triggers. There are four different types of procedural
programs, one of which is triggers. Triggers are defined on tables in a Structured
Query Language (SQL) database to automatically perform tasks such as data checks,
tracking changes, or business rule enforcements. Triggers are treated as a single
transaction. Triggers are set to fire in response to an action query. They are
important because they help prevent data inconsistencies, which helps to keep the
database running efficiently. More than one trigger can be set for an action. This
lesson also briefly touches on indexes and how they can be used as an effective
means of accessing data within a database. Image

Topics for this lesson include the following:

Triggers
How SQL Server treats a trigger
Why to use triggers
Triggers to enforce business rules
Creating triggers
Considerations for triggers
Indexes

Learning Materials
There are four different types of procedural programs, scripts, triggers, stored
procedures, and user-defined functions. All four are considered executable database
objects because they are each stored within the actual database. Data Definition
Language (DDL) statements are used to create objects. Objects are stored in the
database until they are removed. The difference between these four programs is how
they are executed. This lesson focuses on triggers. Image
Image You can define triggers on tables in your SQL databases so that SQL
Server will automatically perform tasks such as verifying data, tracking changes to
a table, or enforcing business rules. The table on which a trigger is based is
referred to as the trigger table. Although a trigger is very similar to a stored
procedure, you can't execute a trigger directly. Instead, you base triggers on the
INSERT, UPDATE, and DELETE SQL statements, and SQL Server automatically executes
the triggers for you whenever a user executes one of these SQL statements. For
example, if you create an INSERT trigger on a table, SQL Server automatically calls
the trigger whenever you insert a new row into the table.

How SQL Server Treats a Trigger


SQL Server treats a trigger and the statement that calls it as a single
transaction. You don't have to explicitly mark the beginning of the transaction by
using the BEGIN TRANSACTION statement. You can roll back the entire transaction
from anywhere within the trigger. For example, you can include error checking
within your trigger and call the ROLLBACK TRANSACTION statement if an error occurs.
Keep in mind that if a user transaction calls a trigger and the trigger executes
the ROLLBACK TRANSACTION statement, SQL Server rolls back both the trigger's steps
along with the steps in the user transaction. It's important that you be aware that
rolling back transactions can degrade the performance of your server.

Image

When you roll back a transaction, SQL Server will have performed all of the steps
up to the ROLLBACK TRANSACTION statement, and then it must undo those steps. It's
much better for you to check your data prior to beginning the transaction rather
than within the transaction itself.
Triggers run in response to an action query (Syverson & Murach, 2012). Triggers are
written to help prevent invalid data or data inconsistency. Also, triggers cannot
use parameters while stored procedures and user-defined functions can. Parameters
are values that are passed or returned from a parameter.

Differences between scripts, stored procedures, user-defined functions, and


triggers are as follows:

Scripts can contain multiple batches, are stored in a file, are executed from
within a client tool such as Management Studio, and do not accept parameters.
A user-defined function and a stored procedure are both stored as an object in
the database, are executed by an application or a SQL script, and can accept
parameters.
A trigger is stored as an object in the database and is executed automatically
by the server when a specific condition is met but cannot accept parameters.

Why use triggers?


Image You use triggers for a couple of reasons, such as to enforce data
integrity and to enforce business rules. You should use triggers to enforce data
integrity on your tables, not for returning query results. Keep in mind that
triggers are typically fired when you change the data in a table.

For example, you might use a trigger to perform cascading deletes. You can use a
trigger to delete a customer by first deleting the customer's invoices from both
the rental_detail and rental tables and then the customer themselves. Likewise, you
can use a trigger to perform cascading updates of rows in multiple tables.

Triggers are specific procedures that execute using the INSERT, UPDATE, or DELETE
statement to prevent database errors. Triggers provide greater control and
flexibility over scripts.

Triggers to Enforce Business Rules

You can also use triggers to enforce business rules that are too complex for
constraints. For example, you might not want to rent new movies to a customer if
that customer has any overdue movies. You can use a trigger to verify that the
customer doesn't have overdue movies before permitting the customer to rent a new
one.

Another use for triggers is to generate computed values. For example, you might use
a trigger to create each customer's account number in the customer table by using a
portion of the customers last name plus a portion of his or her phone number
instead of using the IDENTITY property to autogenerate account numbers.
Here's one last use for triggers: You can use them to keep track of changes to a
table. For example, you can use an update trigger to detect whenever users change
the data in a sensitive table, such as one that contains employee salary
information. The update trigger can then record the changed information not only to
the user table but also to an audit trail table. Image

Constraints are used to ensure data integrity. You should keep in mind that
triggers are essentially reactive, whereas constraints are proactive. SQL Server
fires an UPDATE trigger only after you've updated the data in a table. In contrast,
table constraints are proactive. SQL Server checks a table's constraints before it
will let you perform an action. For example, if you attempt to add a new movie to
the movie table with a duplicate movie numberwhich is the primary key for this
tablethe primary key constraint, not the trigger, will prevent you from adding the
new row.

Creating Triggers
Triggers are fired automatically when an action query is executed. Just about any
logic can be coded for a trigger, which makes it a very powerful tool. To create a
trigger, start by using the CREATE TRIGGER statement. There are two kinds of
triggers: AFTER and INSTEAD OF. An AFTER trigger executes after the query action,
while an INSTEAD OF is fired before the query runs. When using INSTEAD OF, the
query is never executed.

The following is an example of an AFTER trigger (Syverson & Murach, 2012):

CREATE TRIGGER trigger_name

On (table_name/view_name)

AFTER INSERT,UPDATE

As sql_statements

The FOR key word can be used. The FOR key word works just like the AFTER. The only
difference is that FOR is an ANSI-standard key word that was allowed prior to SQL
Server 2000 (Syverson & Murach, 2012).

Keep in mind that a trigger is associated with a single table or a single view. A
trigger can be set to fire after or before the query call. Multiple AFTER queries
can be set; however, only one INSTEAD OF can be set for an action.

Considerations for Triggers

You can configure more than one trigger for an action. If you're the owner of a
table with multiple triggers for an action, such as updates, you can specify which
of the triggers must fire first and last. However, you can't specify the order in
which SQL Server calls the in-between triggers if you have that many. For example,
you can configure four update triggers on a table and specify which of the triggers
you want to be first and which one you want to be last, but SQL Server will call
the remaining two triggers in random order, and the order will vary from one UPDATE
statement to the next. If you want the steps in the triggers to be performed in a
specific order, you should combine them into a single trigger.

Indexes
Image Data are stored in one or more tables. How data are accessed is
important. In relational databases, data are stored in rows (records) or columns
(fields). Tables that contain more than one column use uniquely defined keys.
Indexes provide an efficient way to access the rows in a table based on one or more
columns (Syverson & Murach, 2012). An index is created for each primary and non-
primary key that is defined within a table. A table can be defined with more than
one index.

Summary

This lesson discussed the importance of using triggers. How triggers differ from
scripts, stored procedures, and user-defined parameters was outlined. Not only is
it important to understand what a trigger is, how triggers are managed, and when to
use them, but it is also important to understand why they are used. Triggers are
set to fire automatically when the action query is executed, which makes a trigger
a very powerful tool. Triggers provide greater control and flexibility and are used
to enforce data integrity and business rules. Indexes are an efficient way to
access rows in a table based on one or more columns.
Reference

Syverson, B., & Murach, J. (2012). Murach's SQL Server 2012 for developers. Fresno,
CA: Mike Murach & Associates.

Вам также может понравиться