Sei sulla pagina 1di 8

6-18

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

Practice: Creating Triggers

The purpose of this practice is to enable you to create and drop triggers by using
Transact-SQL.

Objectives
In this practice, you will:

Drop existing triggers.

Create an UPDATE trigger.

Create an INSTEAD OF trigger.

Instructions

Start the 2779B-MIA-SQL-06 virtual machine.

Log on to the virtual machine with the user name Student and the password
Pa$$w0rd.

Drop existing triggers


1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then
click SQL Server Management Studio.
2. In the Connect to Server dialog box, specify the values in the following table, and
then click Connect.
Property

Value

Server type

Database Engine

Server name

MIAMI

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

Property

Value

Authentication

Windows Authentication

6-19

3. On the File menu, point to Open, and then click File.


4. In the Open File dialog box, browse to the D:\Practices folder, click the
DropTriggers.sql query file, and then click Open.
5. In the Connect to Database Engine dialog box, specify the values in the following
table, and then click Connect.
Property

Value

Server name

MIAMI

Authentication

Windows Authentication

6. On the toolbar, click Execute.


7. On the File menu, click Close to close the DropTriggers.sql query.
8. Keep SQL Server Management Studio open. You will use it in the next procedure.

Create an UPDATE trigger


1. In SQL Server Management Studio, on the toolbar, click New Query.
2. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
CREATE TRIGGER uEmployee ON HumanResources.Employee
AFTER UPDATE NOT FOR REPLICATION AS
BEGIN
SET NOCOUNT ON;
UPDATE HumanResources.Employee
SET HumanResources.Employee.ModifiedDate = GETDATE()
FROM inserted
WHERE inserted.EmployeeID = HumanResources.Employee.EmployeeID
END

3. On the toolbar, click Execute.


4. In Object Explorer, expand Databases, expand AdventureWorks, and then expand
Tables.
5. Expand the HumanResources.Employee table, and then expand Triggers to verify
that the uEmployee trigger has been created.
6. On the toolbar, click New Query.
7. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
UPDATE HumanResources.Employee
SET ModifiedDate = '01/01/01'
WHERE EmployeeID = 1

6-20

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

SELECT ModifiedDate
FROM HumanResources.Employee
WHERE EmployeeID = 1

8. On the toolbar, click Execute.


9. Verify that the trigger has set the ModifiedDate value to the current date and time,
even though you updated it to January 1, 2001.
10. Keep SQL Server Management Studio open. You will use it in the next procedure.

Create an INSTEAD OF trigger


1. In SQL Server Management Studio, on the toolbar, click New Query.
2. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
CREATE TRIGGER dEmployee ON HumanResources.Employee
INSTEAD OF DELETE NOT FOR REPLICATION AS
BEGIN
SET NOCOUNT ON
DECLARE @DeleteCount int
SELECT @DeleteCount = COUNT(*) FROM deleted
IF @DeleteCount > 0
BEGIN
RAISERROR
(N'Employees cannot be deleted. They can only be marked as not
current.', 10, 1)
-- Roll back any active or uncommittable transactions
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
END
END

3. On the toolbar, click Execute.


4. When the command has completed successfully, in Object Explorer, right-click the
Triggers folder, and then click Refresh to verify that the dEmployee trigger has
been created.
5. On the toolbar, click New Query.
6. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
DELETE FROM HumanResources.Employee
WHERE EmployeeID = 1

7. On the toolbar, click Execute.

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

8. Verify that the DELETE operation is unsuccessful and that the trigger returns an
error.
9. Close SQL Server Management Studio. Click No if prompted to save any files.

6-21

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

6-33

Lab: Implementing Data Integrity by Using Triggers


and XML Schemas

After completing this lab, you will be able to:

Create triggers by using Transact-SQL.

Implement XML schemas.

Estimated time to complete this lab: 45 minutes

Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the
lab, you must:

Start the 2779B-MIA-SQL-06 virtual machine.

Log on to the virtual machine with the user name Student and the password
Pa$$w0rd.

Lab Scenario
The Human Resources department has decided that it wants to keep a historical record of
job candidates so that it can contact past unsuccessful candidates if new positions come
up, and compare the information provided by candidates if they apply for different
positions over time. After consulting with the Human Resources team, the senior
database developer has decided a new table is required to store this historical information.
The senior database developer has provided you with the Transact-SQL to create the
HumanResources.JobCandidateHistory table. The senior database developer has asked
you to:

6-34

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

Create a new DELETE trigger named dJobCandidate on the


HumanResources.JobCandidate table that copies the candidates information to the
HumanResources.JobCandidateHistory table when somebody deletes a candidate.
The JobCandidateId and Resume columns must be copied directly across and the
RejectedDate set to the current date by using the getdate function. Rating should be
left at its default value, and ContactDetails should be set to NULL.

Create an XML schema collection named


HumanResources.HistoricResumeSchemaCollection. The Human Resources
department will supply the XML schema, which is a variant of the schema that the
department currently uses for the resumes of active candidates. Apply the schema
collection to the JobCandidateHistory.Resume column to make it typed xml data.

Create a SQL Server Scripts project for the modifications by using SQL Server
Management Studio, and then store the project in the D:\Labfiles\Starter folder.

A file named HistoricResumeSchema.xml containing the schema for the


HistoricResumeSchemaCollection XML schema collection is provided in the
D:\Labfiles\Starter folder.

Additional Information
When performing database development tasks, it can be helpful to use SQL Server
Management Studio to create a SQL Server Scripts project, and use it to document the
Transact-SQL code necessary to re-create the solution if necessary.
Use the following procedure to create a SQL Server Scripts project:
1. Open SQL Server Management Studio, connecting to the server you want to manage.
2. On the File menu, point to New, and then click Project.
3. Select the SQL Server Scripts template and enter a suitable name and location for
the project. Note that you can create a solution that contains multiple projects, but in
many cases a single project per solution is appropriate.
Use the following procedure to add a query file to a project:
1. On the Project menu, click New Query, or in Solution Explorer, right-click the
Queries folder, and then click New Query. If Solution Explorer is not visible, on the
View menu, click Solution Explorer.
2. When prompted, connect to the server on which you want to execute the query. This
will add a connection object to the project.
3. To change the name of the query file from the default name (SQLQuery1.sql), rightclick it in Solution Explorer and click Rename.
Although you can perform all database development tasks by executing Transact-SQL
statements, it is often easier to use the graphical user interface in SQL Server

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

6-35

Management Studio. However, you should generate the corresponding Transact-SQL


scripts and save them in the project for future reference.
Often, you can generate the Transact-SQL script for an action before clicking OK in the
Properties dialog box used to perform the action. Many Properties dialog boxes include a
Script list with which you can script the action to a new query window, a file, the
Clipboard, or a SQL Server Agent job. A common technique is to add a blank query file
to a project, script each action to the Clipboard as it is performed, and then paste the
generated script into the query file.
You can also generate scripts for many existing objects, such as databases and tables. To
generate a script, right-click the object in Object Explorer and script the CREATE action.
If Object Explorer is not visible, on the View menu, click Object Explorer.

6-36

Module 6: Implementing Data Integrity by Using Triggers and XML Schemas

Exercise 1: Creating Triggers


In this exercise, you will create and test the dJobCandidate DELETE trigger to copy the
candidates information to the HumanResources.JobCandidateHistory table when the
candidate record is deleted from the database.
The principal tasks for this exercise are as follows:

Create a SQL Server Scripts project.

Create the dJobCandidate trigger.

Test the dJobCandidate trigger.


Task

Supporting information

1.

Start SQL Server Management Studio and


connect to the MIAMI instance by using
Microsoft Windows authentication.

Create a new SQL Server Scripts project named


AW_DataIntegrity.

Add the CreateTable.sql query file to the project


from the D:\Labfiles\Starter folder. Connect to
the MIAMI instance by using Windows
Authentication when prompted.

Execute the CreateTable.sql query and verify


that the
HumanResources.JobCandidateHistory table
has been created.

Add a new query to the project, connecting to


the MIAMI instance by using Windows
authentication when prompted. Change the
query file name to Trigger.sql

In the query window, type the appropriate


Transact-SQL to create the dJobCandidate
trigger on the HumanResources.JobCandidate
table in the AdventureWorks database.

Execute the query, and then save the query file.

Use Object Explorer to verify that the trigger has


been created.

In SQL Server Management Studio, open the


TestTrigger.sql query file from the
D:\Labfiles\Starter folder. Connect to the MIAMI
instance by using Windows Authentication when
prompted.

Execute the query script, and look in the results


pane to verify that the record deleted from the
HumanResources.JobCandidate table has
been inserted into the
HumanResources.JobCandidateHistory table.

2.

3.

Create a SQL Server Scripts project.

Create the dJobCandidate trigger.

Test the dJobCandidate trigger.

Potrebbero piacerti anche