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

5-26

Module 5: Implementing Data Integrity by Using Constraints

Practice: Creating Constraints

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

Objectives
In this practice, you will:

Drop existing constraints.

Create a CHECK constraint by using Transact-SQL.

Create a DEFAULT constraint by using Transact-SQL.

Instructions

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

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

Drop existing constraints


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 5: Implementing Data Integrity by Using Constraints

Property

Value

Authentication

Windows Authentication

5-27

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


4. In the Open File dialog box, browse to the D:\Practices folder, click
DropConstraints.sql, and then click Open.
5. In the Connect to Databse 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. Verify that the commands completed successfully.
8. On the File menu, click Close to close the DropConstraints.sql query.

Create a CHECK constraint by using Transact-SQL


1. In SQL Server Management Studio, if Object Explorer is not visible, on the View
menu, click Object Explorer.
2. In Object Explorer, expand Databases, expand AdventureWorks, and then expand
Tables.
3. Expand the HumanResources.Employee table, and then expand the Constraints
folder to view the constraints on the HumanResources.Employee table.
4. On the toolbar, click New Query.
5. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
ALTER TABLE HumanResources.Employee WITH CHECK ADD CONSTRAINT CK_Employee_Gender
CHECK ((upper([Gender])='F' OR upper([Gender])='M'))

6. On the toolbar, click Execute.


7. When the command has completed successfully, in Object Explorer, right-click the
Constraints folder, and then click Refresh to verify that the
CK_Employee_Gender constraint has been created.
8. On the toolbar, click New Query .
9. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
UPDATE HumanResources.Employee
SET Gender = 'Q'
WHERE EmployeeID = 1

5-28

Module 5: Implementing Data Integrity by Using Constraints

10. On the toolbar, click Execute.


11. Verify that an error is returned because the update conflicted with the CHECK
constraint.
12. Keep SQL Server Management Studio open. You will use it in the next procedure.

Create a DEFAULT constraint by using Transact-SQL


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
ALTER TABLE HumanResources.Employee ADD
DEFAULT (getdate()) FOR ModifiedDate

CONSTRAINT DF_Employee_ModifiedDate

3. On the toolbar, click Execute.


4. When the command has completed successfully, in Object Explorer, right-click the
Constraints folder, and then click Refresh to verify that the
DF_Employee_ModifiedDate constraint has been created.Error! Bookmark not
defined.
5. On the toolbar, click New Query.
6. In the new, blank query window, type the following Transact-SQL code.
USE AdventureWorks
GO
UPDATE HumanResources.Employee
SET ModifiedDate = DEFAULT
WHERE EmployeeID = 1
SELECT ModifiedDate
FROM HumanResources.Employee
WHERE EmployeeID = 1

7. On the toolbar, click Execute.


8. Verify that the default ModifiedDate value is the current date and time.
9. Close SQL Server Management Studio. Click No if prompted to save any files.

Module 5: Implementing Data Integrity by Using Constraints

5-29

Lab: Implementing Data Integrity by Using


Constraints

After completing this lab, you will be able to:

Create constraints.

Enable and disable constraints.

Estimated time to complete this lab: 30 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-05 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 to keep a historical record of job
candidates so that it can contact past unsuccessful candidates if new positions come up,
and so that it can 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 asked you to:

Create a new table named HumanResources.JobCandidateHistory. The


JobCandidateHistory table will have the following columns and constraints:

5-30

Module 5: Implementing Data Integrity by Using Constraints

JobCandidateID. An int column that cannot contain null values. The values in
this column must be unique.

Resume. An xml column that can contain null values.

Rating. An int column that cannot contain null values. The values in this column
must be within the range 1 through 10, with a default value of 5.

RejectedDate. A datetime column that cannot contain null values.

ContactID. An int column that can contain null values. This column is a foreign
key to the ContactID column in the Person.Contact table.

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.

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
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

Module 5: Implementing Data Integrity by Using Constraints

5-31

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.

5-32

Module 5: Implementing Data Integrity by Using Constraints

Exercise 1: Creating Constraints


In this exercise, you will create and test the HumanResources.JobCandidateHistory
table and constraints.
The principal tasks for this exercise are as follows:

Create a SQL Server Scripts project.

Create the JobCandidateHistory table and constraints.

Test the JobCandidateHistory table and constraints.


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 a new query to the project, connecting to


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

In the query window, type the appropriate


Transact-SQL statement to create the
HumanResources.JobCandidateHistory table
in the AdventureWorks database.

Execute the query, and then save the query file.

Use Object Explorer to verify that the table and


constraints have been created.

In SQL Server Management Studio, open the


TestConstraints.sql script file in the
D:\Labfiles\Starter folder. Connect to the MIAMI
instance by using Windows authentication when
prompted.

Use the INSERT statement to test inserting


invalid data.

Use the INSERT statement to test inserting valid


data.

2.

3.

Create a SQL Server Scripts project.

Create the JobCandidateHistory


table and constraints.

Test the JobCandidateHistory table


and constraints.

Module 5: Implementing Data Integrity by Using Constraints

5-33

Exercise 2: Disabling Constraints


In this exercise you will insert multiple rows into the
HumanResources.JobCandidateHistory table before and after disabling constraints, to
compare the performance.
The principal tasks for this exercise are as follows:

Insert multiple rows into the JobCandidateHistory table.

Disable constraints on the JobCandidateHistory table.

Enable constraints on the JobCandidateHistory table.

Task

Supporting information

1.

In SQL Server Management Studio, open the


InsertTestData.sql script file in the
D:\Labfiles\Starter folder. Connect to the
MIAMI instance by using Windows
authentication when prompted.

Execute the script and record the client


statistics.

Add a new query to the project, connecting to


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

In the query window, type the appropriate


Transact-SQL to disable the constraints on
the HumanResources.JobCandidateHistory
table.

Execute the query, and then save the query


file.

Open the InsertTestData.sql script, execute


the query, and then record the client statistics.

Compare the performance statistics for the


INSERT statements before and after the
constraints were disabled.

In the Constraints.sql query window, type the


appropriate Transact-SQL to enable the
constraints on the
HumanResources.JobCandidateHistory
table.

Execute the query, and then save the query


file.

2.

3.

Insert multiple rows into the


JobCandidateHistory table.

Disable constraints on the


JobCandidateHistory table.

Enable constraints on the


JobCandidateHistory table.

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