• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
9767405 - Implementing Data Integrity
 

9767405 - Implementing Data Integrity

on

  • 551 views

SQL - Implementing Data Integrity

SQL - Implementing Data Integrity

Statistics

Views

Total Views
551
Views on SlideShare
550
Embed Views
1

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 1

http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    9767405 - Implementing Data Integrity 9767405 - Implementing Data Integrity Document Transcript

    • Module 5Implementing Data IntegrityContents:Lesson 1: Data Integrity Overview 5-2Lesson 2: Implementing Constraints 5-6Lesson 3: Implementing Triggers 5-26Lesson 4: Implementing XML Schemas 5-44Lab: Implementing Data Integrity 5-54
    • Information in this document, including URL and other Internet Web site references, is subject to changewithout notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with anyreal company, organization, product, domain name, e-mail address, logo, person, place or event is intended orshould be inferred. Complying with all applicable copyright laws is the responsibility of the user. Withoutlimiting the rights under copyright, no part of this document may be reproduced, stored in or introduced intoa retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying,recording, or otherwise), or for any purpose, without the express written permission of MicrosoftCorporation.The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoftmakes no representations and warranties, either expressed, implied, or statutory, regarding thesemanufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer orproduct does not imply endorsement of Microsoft of the manufacturer or product. Links are provided tothird party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for thecontents of any linked site or any link contained in a linked site, or any changes or updates to such sites.Microsoft is not responsible for webcasting or any other form of transmission received from any linked site.Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not implyendorsement of Microsoft of the site or the products contained therein.Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rightscovering subject matter in this document. Except as expressly provided in any written license agreementfrom Microsoft, the furnishing of this document does not give you any license to these patents, trademarks,copyrights, or other intellectual property.©2006 Microsoft Corporation. All rights reserved.Microsoft, JScript, MSDN, Outlook, PowerPoint, Visual Basic, Visual C#, Visual C++, Visual FoxPro, Windows,and Windows Server are either registered tradmarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries.The names of actual companies and products mentioned herein may be the trademarks of their respectiveowners.
    • Module 5: Implementing Data Integrity 5–1**************************************** Illegal for non-trainer use ***************************************Module objectives After completing this module, students will be able to: ■ Describe types of data integrity and options for enforcing it. ■ Implement constraints. ■ Implement triggers. ■ Implement XML schemas.Introduction The quality of data in your database will largely determine the usefulness and effectiveness of applications (and people) that rely on it and can play a major role in the success or failure of an organization or a business venture. Ensuring data integrity is a critical step in maintaining high-quality data. You should enforce data integrity at all levels of an application from first entry or collection through storage. Microsoft® SQL Server™ 2005 provides a variety of features that simplify the enforcement of data integrity. This module begins with an overview of the types of data integrity that will concern you as a database developer and summarizes the features provided by SQL Server 2005 to meet those concerns. It then discusses in detail three of the richest and most powerful data integrity features of SQL Server 2005: constraints, triggers, and XML schemas.
    • 5–2 Module 5: Implementing Data IntegrityLesson 1: Data Integrity Overview**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe types of data integrity. ■ Describe options for enforcing data integrity.Data integrity overview An important step in database planning is deciding the best way to enforce the integrity of the data. Data integrity refers to the consistency and accuracy of data that is stored in a database. In this lesson, you will learn about the different types of data integrity in a relational database and the options provided by SQL Server 2005 to enforce data integrity.
    • Module 5: Implementing Data Integrity 5–3Types of Data Integrity**************************************** Illegal for non-trainer use ***************************************Types of data integrity Enforcing data integrity ensures the quality of the data in the database. The various types of data integrity that you must plan for are: ■ Domain (or column) integrity ■ Entity integrity ■ Referential integrityDomain integrity Domain (or column) integrity specifies a set of data values that are valid for a column and determines whether to allow null values. Domain integrity is often enforced by using validity checking and can be enforced by restricting the data type, format, or range of possible values allowed in a column.Entity integrity Entity (or table) integrity requires that all rows in a table have a unique identifier, known as the primary key value. Whether the primary key value can be changed, or whether the whole row can be deleted, depends on the level of integrity required between the primary key and any other tables.Referential integrity Referential integrity ensures that the relationships among the primary keys (in the referenced table) and foreign keys (in the referencing tables) are always maintained. A row in a referenced table cannot be deleted, nor can the primary key be changed, if a foreign key refers to the row, unless the cascade action is permitted. You can define referential integrity relationships within the same table or between separate tables. For More Information For more information about the different types of data integrity, see “Data Integrity” in SQL Server Books Online.
    • 5–4 Module 5: Implementing Data IntegrityOptions for Enforcing Data Integrity**************************************** Illegal for non-trainer use ***************************************Options for enforcing The following table summarizes the mechanisms provided by SQL Server 2005 fordata integrity enforcing data integrity. Mechanism Integrity types Description Data types Domain Data types enforce fundamental restrictions on the type of data that can be stored in each column. Assigning data types to each column in a table is the first step in enforcing data integrity. However, data types alone are not sufficient to enforce the type of data integrity required in business solutions without the other mechanisms listed in this table. For example, a column declared as type int ensures that only numerical integer values can be entered but cannot by itself restrict the values to the range 0 through 1000. Rules and Domain, Entity Rules define the acceptable values that a column can defaults contain, and defaults define the value of a column if a value is not specified. Importantly, rules and defaults are independent objects that can be bound to one or more columns or user-defined data types, making it possible to define them once and use them repeatedly. A disadvantage to using rules and defaults is that they are not American National Standards Institute (ANSI)–compliant. You should use constraints instead of rules and defaults.
    • Module 5: Implementing Data Integrity 5–5Mechanism Integrity types DescriptionConstraints Domain, Entity, Constraints let you define the way the SQL Server Referential 2005 Database Engine automatically enforces the integrity of a database. Constraints define restrictions on the values allowed in columns and are the standard mechanism for enforcing integrity. Using constraints is preferred to using triggers, rules, and defaults. The query optimizer also uses constraint definitions to build high-performance query execution plans.Triggers Domain, Entity, Triggers are a special kind of stored procedure that Referential executes when a data manipulation language (DML) event occurs in the database server. DML events include UPDATE, INSERT, or DELETE statements issued against a table or view. Triggers are used to enforce business rules when data is modified.XML schemas Domain (XML) XML schemas define the namespace, structure, and acceptable content of XML documents. By applying an XML schema to a table column defined with the xml data type, you can restrict the structure and content of the XML data stored in that column.For More Information For more information about the different options forenforcing data integrity in SQL Server 2005, see “Enforcing Data Integrity” in SQLServer Books Online.
    • 5–6 Module 5: Implementing Data IntegrityLesson 2: Implementing Constraints**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe constraints. ■ Define PRIMARY KEY constraints. ■ Define DEFAULT constraints. ■ Define CHECK constraints. ■ Define UNIQUE constraints. ■ Define FOREIGN KEY constraints. ■ Define cascading referential integrity. ■ Identify reasons to disable constraints.Implementing Constraints are the recommended method of enforcing data integrity. In this lesson, youconstraints will learn the types of constraints available, the type of constraint to use depending on your needs, the type of data integrity each constraint enforces, and how to define constraints.
    • Module 5: Implementing Data Integrity 5–7What Are Constraints?**************************************** Illegal for non-trainer use ***************************************Definition Constraints are an ANSI-standard method of enforcing data integrity. Each type of data integritydomain, entity, and referentialis enforced by using separate types of constraints. Constraints ensure that valid data values are entered in columns and that relationships between tables are maintained. The following table describes the various types of constraints available in SQL Server 2005 and whether they are defined on a table or a column.Integrity type Constraint type Target DescriptionDomain DEFAULT Column Specifies the default value for the column when an INSERT statement does not provide a value. The DEFAULT constraint is the recommended alternative to a default object. CHECK Column Specifies data values that are acceptable in a column. The CHECK constraint is the recommended alternative to a rule object. FOREIGN KEY Table Specifies the data values that are acceptable to update, based on values in a column in another table. NULL Column Specifies whether the value of a column can be NULL.Entity PRIMARY KEY Table Identifies each row uniquely—ensures that users do not enter duplicate values and that an index is created to enhance performance. Null values are not allowed. UNIQUE Column Prevents duplication of alternative (nonprimary) keys and ensures that an index is created to enhance performance. Null values are allowed.Referential FOREIGN KEY Table Defines a column or combination of columns with values that match the primary key of the same or another table. CHECK Column Specifies the data values that are acceptable in a column based on values in other columns in the same table.
    • 5–8 Module 5: Implementing Data IntegrityCreating constraints You create constraints when you create a table by using the CREATE TABLE statement. A column-level constraint applies to a single column and is part of the column’s definition. A table-level constraint can reference one or more of the table’s columns. Table-level constraints are specified together in a separate section after all columns have been defined. You can modify the constraints on an existing table by using the ALTER TABLE statement. You can add constraints to a table with existing data, and you can place constraints on single or multiple columns. The following is a simplified representation of the syntax of the CREATE TABLE statement that shows where you declare the various column-level and table-level constraints. CREATE TABLE table_name ({ < column_definition > | < table_constraint > } [ ,...n ]) < column_definition > ::= {column_name data_type } [{DEFAULT constant_expression | [ IDENTITY [( seed , increment )]]}] [ < column_constraint > [ ...n ] ] < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ PRIMARY KEY | UNIQUE ] | REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] } < table_constraint > ::= [ CONSTRAINT constraint_name ] { [ { PRIMARY KEY | UNIQUE } { (column [ ,...n ] ) } ] | FOREIGN KEY (column [ ,...n ] ) REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] }
    • Module 5: Implementing Data Integrity 5–9PRIMARY KEY Constraints**************************************** Illegal for non-trainer use ***************************************Definition A PRIMARY KEY constraint defines one or more columns in a table that constitute a primary key. The primary key uniquely identifies a row in a table and enforces entity integrity of the table. Consider the following facts before you implement a PRIMARY KEY constraint: ■ A table can have only one PRIMARY KEY constraint. ■ The columns included in the PRIMARY KEY constraint cannot accept null values. ■ The values in the columns specified as the PRIMARY KEY must be unique. If the PRIMARY KEY constraint contains more than one column, duplicates can appear in one column, but the combination of values from all the columns in the PRIMARY KEY constraint definition must be unique. ■ A PRIMARY KEY constraint creates a unique index with the specified columns as the index key. Therefore, the columns chosen for the primary key must follow the rules for creating unique indexes. You can specify a clustered or nonclustered index. (Clustered is the default if an index does not already exist.) You cannot drop the index that supports the PRIMARY KEY constraint. Only when you remove the PRIMARY KEY constraint is the index removed. This index also permits fast access to data when the primary key is used in queries. For More Information For more information about PRIMARY KEY constraints, see “PRIMARY KEY Constraints” in SQL Server Books Online.When to use PRIMARY Consider using a PRIMARY KEY constraint when:KEY constraints ■ One or more columns in a table should uniquely identify each row (entity) in the table. ■ One of the columns in the table is an identity column.
    • 5–10 Module 5: Implementing Data IntegrityCreating PRIMARY KEY You create PRIMARY KEY constraints by using the table-level CONSTRAINT clause ofconstraints the CREATE TABLE and ALTER TABLE statements. The following code shows the Transact-SQL statement used to create the HumanResources.Department table of the AdventureWorks database. The CONSTRAINT clause defines a clustered PRIMARY KEY constraint named PK_Department_DepartmentID on the DepartmentID column. CREATE TABLE [HumanResources].[Department]( [DepartmentID] [smallint] IDENTITY(1,1) NOT NULL, [Name] [dbo].[Name] NOT NULL, [GroupName] [dbo].[Name] NOT NULL, [ModifiedDate] [datetime] NOT NULL, CONSTRAINT [PK_Department_DepartmentID] PRIMARY KEY CLUSTERED ([DepartmentID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) For More Information For more information about creating and modifying PRIMARY KEY constraints, see “Creating and Modifying PRIMARY KEY Constraints” in SQL Server Books Online.
    • Module 5: Implementing Data Integrity 5–11DEFAULT Constraints**************************************** Illegal for non-trainer use ***************************************Definition A DEFAULT constraint enters a value in a column when one is not specified in an INSERT statement. DEFAULT constraints enforce domain integrity. Consider the following facts before you implement a DEFAULT constraint: ■ A DEFAULT constraint applies only to INSERT statements. ■ Each column can have only one DEFAULT constraint. ■ Columns with the IDENTITY property or the rowversion data type cannot have a DEFAULT constraint placed on them. ■ A DEFAULT constraint allows some system-supplied values—USER, CURRENT_USER, SESSION_USER, SYSTEM_USER, or CURRENT_TIMESTAMP—to be specified rather than user-defined values. For More Information For more information about DEFAULT constraints, see “DEFAULT Definitions” in SQL Server Books Online.When to use DEFAULT Consider using a DEFAULT constraint when:constraints ■ The data stored in a column has an obvious default value. ■ The column does not accept null values. ■ The column does not enforce unique values.Creating DEFAULT You create DEFAULT constraints by using the column-level CONSTRAINT clause of theconstraints CREATE TABLE and ALTER TABLE statements. The following code shows the Transact- SQL statement used to create the Production.Location table of the AdventureWorks database. The example creates DEFAULT constraints on the CostRate, Availability, and ModifiedDate columns.
    • 5–12 Module 5: Implementing Data Integrity CREATE TABLE [Production].[Location]( [LocationID] [smallint] IDENTITY(1,1) NOT NULL, [Name] [dbo].[Name] NOT NULL, [CostRate] [smallmoney] NOT NULL CONSTRAINT [DF_Location_CostRate] DEFAULT ((0.00)), [Availability] [decimal](8, 2) NOT NULL CONSTRAINT [DF_Location_Availability] DEFAULT ((0.00)), [ModifiedDate] [datetime] NOT NULL CONSTRAINT [DF_Location_ModifiedDate] DEFAULT (getdate()) ) For More Information For more information about creating and modifying DEFAULT constraints, see “Creating and Modifying DEFAULT Definitions” in SQL Server Books Online.
    • Module 5: Implementing Data Integrity 5–13CHECK Constraints**************************************** Illegal for non-trainer use ***************************************Definition A CHECK constraint restricts the data values that users can enter into a particular column during INSERT and UPDATE statements. You apply check constraints at the column or table level. Column-level CHECK constraints restrict the values that can be stored in that column. Table-level CHECK constraints can reference multiple columns in the same table to allow for cross-referencing and comparison of column values. Consider the following facts before you implement a CHECK constraint: ■ A CHECK constraint verifies data every time you execute an INSERT or UPDATE statement. ■ A CHECK constraint can be any logical (Boolean) expression that returns TRUE or FALSE. ■ A CHECK constraint cannot contain subqueries. ■ A single column can have multiple CHECK constraints. ■ A CHECK constraint cannot be placed on columns with the rowversion, text, ntext, or image data types. ■ The Database Consistency Checker (DBCC) CHECKCONSTRAINTS statement will return any rows containing data that violates a CHECK constraint. For More Information For more information about CHECK constraints, see “CHECK Constraints” in SQL Server Books Online.When to use CHECK Consider using a CHECK constraint when:constraints ■ Business logic dictates that the data stored in a column must be a member of a specific set or range of values. ■ The data stored in a column has natural limits on the values it can contain. ■ Relationships exist between the columns of a table that restrict the values a column can contain.
    • 5–14 Module 5: Implementing Data IntegrityCreating CHECK You create CHECK constraints by using the column or table-level CONSTRAINT clauseconstraints of the CREATE TABLE and ALTER TABLE statements. The following code shows the Transact-SQL statement used to add a CHECK constraint to the HumanResources.EmployeeDepartmentHistory table of the AdventureWorks database. The example ensures that the value of the EndDate column is equal to or greater than the value of the StartDate column, or that EndDate is NULL. ALTER TABLE [HumanResources].[EmployeeDepartmentHistory] WITH CHECK ADD CONSTRAINT [CK_EmployeeDepartmentHistory_EndDate] CHECK (([EndDate]>=[StartDate] OR [EndDate] IS NULL)) For More Information For more information about creating and modifying CHECK constraints, see “Creating and Modifying CHECK Constraints” in SQL Server Books Online.
    • Module 5: Implementing Data Integrity 5–15UNIQUE Constraints**************************************** Illegal for non-trainer use ***************************************Definition A UNIQUE constraint specifies that two rows in a column cannot have the same value. A UNIQUE constraint is helpful when you already have a primary key, such as an employee number, but you want to guarantee that other identifiers, such as an employee’s tax number, are also unique. Consider the following facts before you implement a UNIQUE constraint: ■ Only one null value can appear in a column with a UNIQUE constraint. ■ A table can have multiple UNIQUE constraints, whereas it can have only a single primary key. ■ A UNIQUE constraint is enforced through the creation of a unique index on the specified column or columns. This index cannot allow the table to exceed the 249 limit on nonclustered indexes. ■ The Database Engine will return an error if you create a UNIQUE constraint on a column that contains data in which duplicate values are found. For More Information For more information about UNIQUE constraints, see “UNIQUE Constraints” in SQL Server Books Online.When to use UNIQUE Consider using a UNIQUE constraint when:constraints ■ The table contains columns that are not part of the primary key but that, individually or as a unit, must contain unique values. ■ Business logic dictates that the data stored in a column must be unique. ■ The data stored in a column has natural uniqueness on the values it can contain, such as tax numbers or passport numbers.Creating UNIQUE You create UNIQUE constraints by using the column-level UNIQUE clause of theconstraints CREATE TABLE and ALTER TABLE statements. The following code shows the Transact-
    • 5–16 Module 5: Implementing Data Integrity SQL statement used to create the HumanResources.Employee table of the AdventureWorks database. The example defines a UNIQUE constraint on the NationalIDNumber column, and ensures that the column contains no null values and that the index created to support the UNIQUE constraint is nonclustered. CREATE TABLE [HumanResources].[Employee]( [EmployeeID] [int] IDENTITY(1,1) NOT NULL, [NationalIDNumber] [nvarchar](15) NOT NULL UNIQUE NONCLUSTERED, [ContactID] [int] NOT NULL, … ) For More Information For more information about creating and modifying UNIQUE constraints, see “Creating and Modifying UNIQUE Constraints” in SQL Server Books Online.
    • Module 5: Implementing Data Integrity 5–17FOREIGN KEY Constraints**************************************** Illegal for non-trainer use ***************************************Definition A foreign key is a column or combination of columns that is used to establish and enforce a link between the data in two tables. A FOREIGN KEY constraint enforces this referential integrity. The FOREIGN KEY constraint defines a reference to a column with a PRIMARY KEY or UNIQUE constraint in the same, or another, table. The values in the foreign key column must appear in the primary key column. While references exist to the primary key values, they cannot be changed or deleted. Consider the following facts before you implement a FOREIGN KEY constraint: ■ A FOREIGN KEY constraint provides single-column or multicolumn referential integrity. The number of columns and data types that are specified in the FOREIGN KEY statement must match the number of columns and data types in the REFERENCES clause. ■ Unlike PRIMARY KEY or UNIQUE constraints, FOREIGN KEY constraints do not create indexes automatically. ■ For another user to create a FOREIGN KEY constraint on a table you own, you must grant that user REFERENCES permission on that table. This ensures that no other user can restrict the operations on a table you own by creating a FOREIGN KEY that references your table. ■ A FOREIGN KEY constraint that uses only the REFERENCES clause without the FOREIGN KEY clause refers to a column in the same table. For More Information For more information about FOREIGN KEY constraints, see “FOREIGN KEY Constraints” in SQL Server Books Online.When to use FOREIGN Consider using a FOREIGN KEY constraint when:KEY constraints ■ The data in one or more columns can hold only values contained in certain columns in the same or another table.
    • 5–18 Module 5: Implementing Data Integrity ■ The rows in a table should not be deleted while rows in another table depend on them.Creating FOREIGN KEY You create FOREIGN KEY constraints by using the column-level or table-levelconstraints CONSTRAINT clause of the CREATE TABLE and ALTER TABLE statements. The following code shows the Transact-SQL statement used to add a FOREIGN KEY constraint to the Sales.SalesOrderHeader table of the AdventureWorks database. The example creates a FOREIGN KEY constraint named FK_SalesOrderHeader_Customer_CustomerID that establishes a referential link between the CustomerID column of the Sales.SalesOrderHeader table and the CustomerID column of the Sales.Customer table. ALTER TABLE [Sales].[SalesOrderHeader] WITH CHECK ADD CONSTRAINT [FK_SalesOrderHeader_Customer_CustomerID] FOREIGN KEY([CustomerID]) REFERENCES [Sales].[Customer] ([CustomerID]) For More Information For more information about creating and modifying FOREIGN KEY constraints, see “Creating and Modifying FOREIGN KEY Constraints” in SQL Server Books Online.
    • Module 5: Implementing Data Integrity 5–19Cascading Referential Integrity**************************************** Illegal for non-trainer use ***************************************Introduction The FOREIGN KEY constraint includes a CASCADE option that allows any change to a column value that defines a UNIQUE or PRIMARY KEY constraint to propagate the change to any foreign key values that reference it. This action is referred to as cascading referential integrity. The REFERENCES clauses of the CREATE TABLE and ALTER TABLE statements support ON DELETE and ON UPDATE clauses. These clauses allow you to specify the behavior of the cascading referential integrity. Possible values include NO ACTION, CASCADE, SET NULL, and SET DEFAULT. NO ACTION is the default value. For More Information For more information about cascading referential integrity, see “Cascading Referential Integrity Constraints” in SQL Server Books Online.Cascading updates The ON UPDATE clause of the FOREIGN KEY constraint defines the behavior when an UPDATE statement attempts to modify a primary key value that is referenced by foreign key values in other tables. The following table summarizes the possible values of the ON UPDATE clause and the effects they have. Option Behavior NO ACTION Specifies that if an attempt is made to update a key value in a row whose key is referenced by foreign keys in existing rows in other tables, an error is raised and the UPDATE statement is rolled back. CASCADE Specifies that if an attempt is made to update a key value in a row where the key value is referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key are also updated to the new value specified for the key.
    • 5–20 Module 5: Implementing Data Integrity Option Behavior SET NULL Specifies that if an attempt is made to update a row by using a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to NULL. All foreign key columns of the target table must be nullable for this constraint to execute. SET DEFAULT Specifies that if an attempt is made to update a row by using a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns of the target table must have a default definition for this constraint to execute. If a column is nullable and there is no explicit default value set, NULL becomes the implicit default value of the column. Any non- null values that are set because of ON UPDATE SET DEFAULT must have corresponding values in the primary table to maintain the validity of the FOREIGN KEY constraint.Cascading deletes The ON DELETE clause of the FOREIGN KEY constraint defines the behavior when a DELETE statement attempts to delete a primary key value that is referenced by foreign key values in other tables. The following table summarizes the possible values of the ON DELETE clause and the effects they have. Option Behavior NO ACTION Specifies that if an attempt is made to delete a row by using a key referenced by foreign keys in existing rows in other tables, an error is raised and the DELETE statement is rolled back. CASCADE Specifies that if an attempt is made to delete a row by using a key referenced by foreign keys in existing rows in other tables, all rows that contain those foreign keys are also deleted. SET NULL Specifies that if an attempt is made to delete a row by using a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to NULL. All foreign key columns of the target table must be nullable for this constraint to execute. SET DEFAULT Specifies that if an attempt is made to delete a row by using a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns of the target table must have a default definition for this constraint to execute. If a column is nullable and there is no explicit default value set, NULL becomes the implicit default value of the column. Any non- null values that are set because of ON DELETE SET DEFAULT must have corresponding values in the primary table to maintain the validity of the FOREIGN KEY constraint.
    • Module 5: Implementing Data Integrity 5–21Considerations for Constraint Checking**************************************** Illegal for non-trainer use ***************************************Considerations for You should specify meaningful names for constraints when you create them; if you doconstraint checking not specify a name for your constraints, SQL Server provides complicated, system- generated names. Names must be unique to the database object owner and follow the rules for SQL Server identifiers. Consider the following facts when you implement or modify constraints: ■ You can create, change, and drop constraints without having to drop and re-create a table. ■ You must build error-checking logic into your applications and transactions to test whether a constraint has been violated. ■ You must specify if you do not want SQL Server to enforce FOREIGN KEY and CHECK constraints for existing data when you add new constraints to an existing table. Tip For help with constraints, execute the sp_helpconstraint or sp_help system stored procedure, or query information schema views, such as check_constraints, referential_constraints, and table_constraints. In addition, the following system tables store constraint definitions: syscomments, sysreferences, and sysconstraints.When to disable You can disable only CHECK and FOREIGN KEY constraints. Other constraints mustconstraints be dropped and then added again. You might consider disabling constraints when: ■ You need to run a large batch job or import data and want to optimize performance. You need to either be confident that the data conforms to the appropriate constraints or run queries as part of the batch job to ensure that the data is accurate before turning the constraints back on. ■ You define a constraint on a table that already contains data. As a result, each row of data is only verified by the constraint the next time it is modified.
    • 5–22 Module 5: Implementing Data Integrity Warning Disabling constraints on one table does not affect constraints on other tables that reference the original table. Updates to a table still can generate constraint violation errors.How to disable To disable constraint checking when you add a CHECK or FOREIGN KEY constraint toconstraints a table with existing data, include the WITH NOCHECK option in the ALTER TABLE statement. Existing data will be checked only during future updates of the constraint column. The following example creates a FOREIGN KEY constraint on the Sales.SalesOrderHeader table and uses the WITH NOCHECK option to disable checking of existing data. ALTER TABLE [Sales].[SalesOrderHeader] WITH NOCHECK ADD CONSTRAINT [FK_SalesOrderHeader_Customer_CustomerID] FOREIGN KEY([CustomerID]) REFERENCES [Sales].[Customer] ([CustomerID]) You can disable constraint checking on existing CHECK and FOREIGN KEY constraints so that any data that you modify or add to the table is not checked against the constraint. To disable a CHECK and FOREIGN KEY constraint, use the ALTER TABLE statement and specify the NOCHECK option. To enable a disabled constraint, execute another ALTER TABLE statement, this time with the CHECK option. This example disables the FK_SalesOrderHeader_Customer_CustomerID constraint. ALTER TABLE [Sales].[SalesOrderHeader] NOCHECK CONSTRAINT [FK_SalesOrderHeader_Customer_CustomerID] This example reenables the FK_SalesOrderHeader_Customer_CustomerID constraint. ALTER TABLE [Sales].[SalesOrderHeader] CHECK CONSTRAINT [FK_SalesOrderHeader_Customer_CustomerID] Tip To determine whether a constraint is enabled or disabled on a table, execute the sp_help system stored procedure, or use the CnstIsDisabled property in the OBJECTPROPERTY function.
    • Module 5: Implementing Data Integrity 5–23Practice: Creating Constraints**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create constraints by using Transact-SQL.Preparation Ensure that virtual machine 2779A-MIA-SQL-05 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To drop existing 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and clickconstraints 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 Authentication Windows Authentication 3. On the File menu, point to Open and click File. 4. Browse to the D:Practices folder and open DropConstraints.sql. When prompted, connect to MIAMI by using Windows authentication. 5. On the toolbar, click the Execute button. 6. Close the DropConstraints.sql query.
    • 5–24 Module 5: Implementing Data IntegrityTo create a CHECK You must perform the following steps to create a CHECK constraint by usingconstraint by using Transact-SQL:Transact-SQL 1. In SQL Server Management Studio, if Object Explorer is not visible, click Object Explorer on the View menu. 2. In Object Explorer, expand Databases, AdventureWorks, Tables, HumanResources.Employee, and Constraints to view the constraints on the HumanResources.Employee table. 3. Click the New Query button on the toolbar. 4. 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)) 5. On the toolbar, click the Execute button. 6. When the command has completed successfully, right-click the Constraints folder in Object Explorer, and then click Refresh to verify that the CK_Employee_Gender constraint has been created. 7. Click the New Query button on the toolbar. 8. In the new, blank query window, type the following Transact-SQL code. USE AdventureWorks GO UPDATE HumanResources.Employee SET Gender = Q WHERE EmployeeID = 1 9. On the toolbar, click the Execute button. 10. Verify that an error is returned because the update conflicted with the CHECK constraint. 11. Keep SQL Server Management Studio open. You will use it in the next procedure.To create a DEFAULT You must perform the following steps to create a DEFAULT constraint by usingconstraint by using Transact-SQL:Transact-SQL 1. In SQL Server Management Studio, click the New Query button on the toolbar. 2. In the new, blank query window, type the following Transact-SQL code. USE AdventureWorks GO ALTER TABLE HumanResources.Employee ADD CONSTRAINT DF_Employee_ModifiedDate DEFAULT (getdate()) FOR ModifiedDate 3. On the toolbar, click the Execute button. 4. When the command has completed successfully, right-click the Constraints folder in Object Explorer, and then click Refresh to verify that the DF_Employee_ModifiedDate constraint has been created. 5. Click the New Query button on the toolbar.
    • Module 5: Implementing Data Integrity 5–256. 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 = 17. On the toolbar, click the Execute button.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 files.
    • 5–26 Module 5: Implementing Data IntegrityLesson 3: Implementing Triggers**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Define DML triggers. ■ Describe how an INSERT trigger works. ■ Describe how a DELETE trigger works. ■ Describe how an UPDATE trigger works. ■ Describe how an INSTEAD OF trigger works. ■ Describe how nested triggers work. ■ Describe considerations for recursive triggers.Introduction Data manipulation language (DML) triggers are a powerful tool that allows you to enforce domain, entity, and referential data integrity. In this lesson, you will learn what DML triggers are and how they enforce data integrity, the different types of triggers available to you, and how to define triggers in your database.
    • Module 5: Implementing Data Integrity 5–27What Are Triggers?**************************************** Illegal for non-trainer use ***************************************What are triggers? A trigger is a special kind of stored procedure that executes when an INSERT, UPDATE, or DELETE statement modifies the data in a specified table. A trigger can query other tables and can include complex Transact-SQL statements. You often create triggers to enforce referential integrity or consistency among logically related data in different tables. Because users cannot circumvent triggers and you have access to the features of Transact-SQL, you can use triggers to enforce complex business logic that is difficult or impossible to enforce by using other data integrity mechanisms. Consider the following facts about triggers: ■ The trigger and the statement that fires it are treated as a single transaction, which can be rolled back from within the trigger. If a severe error is detected (for example, insufficient disk space), the entire transaction automatically rolls back. ■ Triggers can cascade changes through related tables in the database; however, these changes can be executed more efficiently by using cascading referential integrity constraints. ■ Triggers can guard against malicious or incorrect insert, update, and delete operations and enforce other restrictions that are more complex than those defined by using CHECK constraints. ■ Triggers can reference columns in other tables, unlike CHECK constraints. 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.
    • 5–28 Module 5: Implementing Data Integrity For More Information For more information about DML triggers, see “DML Triggers” in SQL Server Books Online.Creating triggers You create triggers by using the CREATE TRIGGER Transact-SQL statement. The CREATE TRIGGER statement has the following syntax. CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ...n ] | EXTERNAL NAME <method specifier [ ; ] > } For More Information For more information about creating triggers, see “CREATE TRIGGER (Transact-SQL)” in SQL Server Books Online.Types of triggers There are two categories of DML triggers: AFTER triggers. AFTER triggers are executed after the action of the INSERT, UPDATE, or DELETE statement is performed. Specifying AFTER is the same as specifying FOR, which is the only option available in earlier versions of Microsoft SQL Server. You can define AFTER triggers only on tables. INSTEAD OF triggers. INSTEAD OF triggers are executed in place of the usual triggering action. INSTEAD OF triggers can also be defined on views with one or more base tables, where they can extend the types of updates that a view can support. For More Information For more information about the types of triggers, see “Types of DML Triggers” in SQL Server Books Online.Triggers vs. constraints The primary benefit of triggers is that they can contain complex processing logic that uses Transact-SQL code. Therefore, triggers can support a superset of the functionality of constraints. However, data integrity should always be enforced at the lowest level possible by using constraints, as long as the constraints meet the requirements of the solution. Triggers are most useful when the features supported by constraints cannot meet the functional needs of the application. For example: ■ FOREIGN KEY constraints can validate a column value only with an exact match to a value in another column, unless the REFERENCES clause defines a cascading referential action. ■ Constraints can communicate about errors only through standardized system error messages. If your application requires more complex error handling, you must use a trigger. Triggers can cascade changes through related tables in the database; however, these changes can be executed more efficiently through cascading referential integrity constraints: ■ Triggers can disallow or roll back changes that violate referential integrity, thereby canceling the attempted data modification. Such a trigger might go into effect
    • Module 5: Implementing Data Integrity 5–29 when you change a foreign key and the new value does not match its primary key. However, FOREIGN KEY constraints are usually used for this purpose. ■ If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution but prior to the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed.For More Information For further comparison of triggers and constraints, see“Triggers Compared to Constraints” in SQL Server Books Online.
    • 5–30 Module 5: Implementing Data IntegrityHow an INSERT Trigger Works**************************************** Illegal for non-trainer use ***************************************Definition An INSERT trigger is a trigger that executes whenever an INSERT statement inserts data into a table or view on which the trigger is configured.How an INSERT trigger When an INSERT trigger fires, new rows are added to both the trigger table and theworks inserted table. The inserted table is a logical table that holds a copy of the rows that have been inserted. The inserted table contains the logged insert activity from the INSERT statement. The inserted table allows you to reference logged data from the initiating INSERT statement. The trigger can examine the inserted table to determine whether, or how, the trigger actions should be executed. The rows in the inserted table are always duplicates of one or more rows in the trigger table. All data modification activity (INSERT, UPDATE, and DELETE statements) is logged, but the information in the transaction log is unreadable. However, the inserted table allows you to reference the logged changes that the INSERT statement caused. You can then compare the changes with the inserted data to verify them or to take further action. Also, you can reference inserted data without having to store the information in variables. For More Information For more information about creating INSERT triggers, see “CREATE TRIGGER (Transact-SQL)” in SQL Server Books Online.
    • Module 5: Implementing Data Integrity 5–31Implementing an INSERT The following code demonstrates the creation of an INSERT trigger namedtrigger insrtWorkOrder on the Production.WorkOrder table of the AdventureWorks database. Notice the use of the inserted table to work with the values that have caused the execution of the trigger. CREATE TRIGGER [insrtWorkOrder] ON [Production].[WorkOrder] AFTER INSERT AS BEGIN SET NOCOUNT ON; INSERT INTO [Production].[TransactionHistory]( [ProductID],[ReferenceOrderID],[TransactionType] ,[TransactionDate],[Quantity],[ActualCost]) SELECT inserted.[ProductID],inserted.[WorkOrderID] ,W,GETDATE(),inserted.[OrderQty],0 FROM inserted; END;
    • 5–32 Module 5: Implementing Data IntegrityHow a DELETE Trigger Works**************************************** Illegal for non-trainer use ***************************************Definition A DELETE trigger is a special kind of stored procedure that executes whenever a DELETE statement deletes data from a table or view on which the trigger is configured.How a DELETE trigger When a DELETE trigger is fired, deleted rows from the affected table are placed in aworks special deleted table. The deleted table is a logical table that holds a copy of the rows that have been deleted. The deleted table allows you to reference logged data from the initiating DELETE statement. Consider the following facts when you use the DELETE trigger: ■ When a row is appended to the deleted table, it no longer exists in the database table; therefore, the deleted table and the database tables have no rows in common. ■ Space is allocated from memory to create the deleted table. The deleted table is always in the cache. ■ A trigger that is defined for a DELETE action does not execute for the TRUNCATE TABLE statement because TRUNCATE TABLE is not logged. For More Information For more information about creating DELETE triggers, see “CREATE TRIGGER (Transact-SQL)” in SQL Server Books Online.Implementing a DELETE The following code demonstrates the creation of a DELETE trigger named delCustomertrigger on the Sales.Customer table of the AdventureWorks database. CREATE TRIGGER [delCustomer] ON [Sales].[Customer] AFTER DELETE AS BEGIN SET NOCOUNT ON; EXEC master..xp_sendmail @recipients=NSalesManagers@Adventure-Works.com, @message = NCustomers have been deleted!!; END;
    • Module 5: Implementing Data Integrity 5–33How an UPDATE Trigger Works**************************************** Illegal for non-trainer use ***************************************Definition An UPDATE trigger is a trigger that executes whenever an UPDATE statement changes data in a table or view on which the trigger is configured.How an UPDATE trigger An UPDATE trigger can be thought of as two steps:works 1. The DELETE step that captures the before image of the data. 2. The INSERT step that captures the after image of the data. When an UPDATE statement is executed on a table that has a trigger defined on it, the original rows (before image) are moved into the deleted table, and the updated rows (after image) are inserted into the inserted table. The trigger can examine the deleted and inserted tables, as well as the updated table, to determine whether multiple rows have been updated and how the trigger actions should be carried out. You can define a trigger to monitor data updates on a specific column by using the IF UPDATE statement. This allows the trigger to isolate activity easily for a specific column. When it detects that the specific column has been updated, it can take proper action, such as raising an error message that says that the column cannot be updated or by processing a series of statements based on the newly updated column value. For More Information For more information about creating UPDATE triggers, see “CREATE TRIGGER (Transact-SQL)” in SQL Server Books Online.
    • 5–34 Module 5: Implementing Data IntegrityImplementing an The following code demonstrates the creation of an UPDATE trigger namedUPDATE trigger updtProductReview on the Production.ProductReview table of the AdventureWorks database. CREATE TRIGGER [updtProductReview] ON [Production].[ProductReview] AFTER UPDATE NOT FOR REPLICATION AS BEGIN SET NOCOUNT ON; UPDATE [Production].[ProductReview] SET [Production].[ProductReview].[ModifiedDate] = GETDATE() FROM inserted WHERE inserted.[ProductReviewID] = [Production].[ProductReview].[ProductReviewID];
    • Module 5: Implementing Data Integrity 5–35How an INSTEAD OF Trigger Works**************************************** Illegal for non-trainer use ***************************************Definition An INSTEAD OF trigger is executed in place of the usual triggering action. INSTEAD OF triggers can also be defined on views with one or more base tables, where they can extend the types of updates a view can support.How an INSTEAD OF This trigger executes instead of the original triggering action. INSTEAD OF triggerstrigger works increase the variety of types of updates that you can perform against a view. Each table or view is limited to one INSTEAD OF trigger for each triggering action (INSERT, UPDATE, or DELETE). You can specify an INSTEAD OF trigger on both tables and views. You cannot create an INSTEAD OF trigger on views that have the WITH CHECK OPTION defined. The following list outlines the primary advantages of INSTEAD OF triggers: ■ They allow views comprising multiple base tables to support inserts, updates, and deletes that reference data in the tables. ■ They allow you to code logic that can reject parts of a batch while allowing other parts of a batch to succeed. ■ They allow you to specify an alternative database action for situations meeting specified conditions. For More Information For more information about creating INSTEAD OF triggers, see “CREATE TRIGGER (Transact-SQL)” in SQL Server Books Online.
    • 5–36 Module 5: Implementing Data IntegrityImplementing an The following code demonstrates the creation of an INSTEAD OF trigger namedINSTEAD OF trigger delEmployee on the HumanResources.Employee table of the AdventureWorks database. CREATE TRIGGER [delEmployee] 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 (NEmployees cannot be deleted. They can only be marked as not current., -- Message 10, -- Severity. 1); -- State. -- Roll back any active or uncommittable transactions IF @@TRANCOUNT > 0 BEGIN ROLLBACK TRANSACTION; END END; END;
    • Module 5: Implementing Data Integrity 5–37How Nested Triggers Work**************************************** Illegal for non-trainer use ***************************************Definition Any trigger can contain an UPDATE, INSERT, or DELETE statement that affects another table. Triggers are nested when a trigger performs an action that initiates another trigger.How nested triggers You can control whether triggers are nested by using the nested triggers serverwork configuration option. Nesting is enabled at installation and is set at the server level, but you can disable and re-enable it by using the sp_configure system stored procedure. Triggers can be nested to a depth of 32 levels. When a trigger in a nested chain sets off an infinite loop, the nesting capacity is exceeded. The trigger then terminates and rolls back the transaction. You can use nested triggers to perform functions, such as backing up a copy of rows that were affected by a previous trigger. Consider the following facts when you use nested triggers: ■ By default, a nested trigger’s configuration option is on. ■ A nested trigger will not fire twice in the same trigger transaction; a trigger does not call itself in response to a second update to the same table within the trigger. However, if a trigger modifies a table that causes another trigger to fire, and the second trigger modifies the original table, the original trigger will fire recursively. To prevent indirect recursion of this sort, turn off the nested triggers option. ■ Because a trigger is a transaction, a failure at any level of a set of nested triggers cancels the entire transaction, and all data modifications are rolled back. Therefore, you should include PRINT statements when you test triggers so that you can determine where the failure occurred.Nesting levels The nesting level increments each time the nested trigger fires. SQL Server supports up to 32 levels of nesting, but you might want to limit the levels of nesting to avoid exceeding the maximum nesting level. You can use the @@NESTLEVEL function to see the current levels of nesting.
    • 5–38 Module 5: Implementing Data IntegrityDisabling nested triggers Nesting is a powerful feature that you can use to maintain data integrity throughout a database. Occasionally, however, you might want to disable nesting. If nesting is disabled, a trigger cannot cascade (perform an action that initiates another trigger that initiates another trigger, and so on). You might decide to disable nesting because: ■ Nested triggers require a complex and well-planned design. Cascading changes can lead to unintended data modifications. ■ A data modification at any point in a series of nested triggers sets off the trigger series. Although this offers powerful protection for your data, it can be a problem if your tables must be updated in a specific order. Use the following statement to disable nesting. sp_configure nested triggers, 0
    • Module 5: Implementing Data Integrity 5–39Considerations for Recursive Triggers**************************************** Illegal for non-trainer use ***************************************Definition A recursive trigger is a trigger that performs an action that causes the same trigger to fire again either directly or indirectly. Any trigger can contain an UPDATE, INSERT, or DELETE statement that affects the same table or another table. With the recursive trigger option enabled, a trigger that changes data in a table can activate itself again, in a recursive execution. There are two types of recursion: Direct recursion. Direct recursion occurs when a trigger fires and performs an action on the same table that causes the same trigger to fire again. For example, an application updates table T1, which causes trigger Trig1 to fire. Trig1 updates table T1 again, which causes trigger Trig1 to fire again. Indirect recursion. Indirect recursion occurs when a trigger fires and performs an action that causes another trigger (in the same or a different table) to fire, and subsequently causes an update to occur on the original table. This then causes the original trigger to fire again. For example, an application updates table T2, which causes trigger Trig2 to fire. Trig2 updates table T3, which causes trigger Trig3 to fire. Trig3 in turn updates table T2, which causes Trig2 to fire again.How to control recursive The recursive trigger option is disabled by default when a database is created, but youcall behavior can enable it by using the alter database statement. A trigger does not call itself recursively unless the RECURSIVE_TRIGGERS database option is set. Use the following statement to enable recursive triggers. ALTER DATABASE AdventureWorks SET RECURSIVE_TRIGGERS ON sp_dboption databasename, recursive triggers, True If the nested trigger option is off, the recursive trigger option is also disabled, regardless of the recursive trigger setting in the database.
    • 5–40 Module 5: Implementing Data Integrity If the nested trigger option is on, indirect recursion will still occur, even though the recursive option is off. The recursive trigger option protects only against direct recursion. (See the definitions of direct and indirect recursion earlier in this topic.) The inserted and deleted tables for a given trigger contain rows that correspond only to the UPDATE, INSERT, or DELETE statement that last invoked the trigger. Trigger recursion can occur to a depth of 32 levels. If a trigger recursion causes an infinite loop, as soon as it exceeds 32 levels, the trigger will be automatically terminated and the transaction rolled back.Considerations for Recursive triggers are a complex feature that you can use to solve complex relationships,recursive triggers such as self-referencing relationships (also known as transitive closures). Consider the following guidelines before you use recursive triggers: ■ Recursive triggers are complex and must be well designed and thoroughly tested. Recursive triggers require controlled looping logic code (termination check). Otherwise, you will exceed the 32-level nesting limit. ■ A data modification at any point can set off the trigger series. Although this provides the ability to process complex relationships, it can be a problem if your tables must be updated in a specific order. ■ You can create similar functionality without the recursive trigger feature; however, your trigger design will differ substantially. In designing recursive triggers, each trigger must contain a conditional check that will stop recursive processing when the condition becomes false. The design of nonrecursive triggers must contain the full programming looping structures and checks.
    • Module 5: Implementing Data Integrity 5–41Practice: Creating Triggers**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create triggers by using Transact-SQL.Preparation Ensure that virtual machine 2779A-MIA-SQL-05 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To drop existing 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and clickconstraints 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 Authentication Windows Authentication 3. On the File menu, point to Open, and click File. 4. Browse to the D:Practices folder and open DropTriggers.sql. When prompted, connect to MIAMI by using Windows authentication. 5. On the toolbar, click the Execute button. 6. Close the DropTriggers.sql query.
    • 5–42 Module 5: Implementing Data IntegrityTo create an UPDATE You must perform the following steps to create an UPDATE trigger by usingtrigger Transact-SQL: 1. In SQL Server Management Studio, click the New Query button on the toolbar. 2. In Object Explorer, expand Databases, AdventureWorks, Tables, and HumanResources.Employee, and click Triggers. 3. 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 4. On the toolbar, click the Execute button. 5. When the command has completed successfully, right-click the Triggers folder in Object Explorer, click Refresh, and then expand the folder to verify that the uEmployee trigger has been created. 6. Click the New Query button on the toolbar. 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 SELECT ModifiedDate FROM HumanResources.Employee WHERE EmployeeID = 1 8. On the toolbar, click the Execute button. 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.To create an INSTEAD OF You must perform the following steps to create an INSTEAD OF trigger by usingtrigger by using Transact-SQL:Transact-SQL 1. In SQL Server Management Studio, click the New Query button on the toolbar. 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
    • Module 5: Implementing Data Integrity 5–43 DECLARE @DeleteCount int SELECT @DeleteCount = COUNT(*) FROM deleted IF @DeleteCount > 0 BEGIN RAISERROR (NEmployees 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 END3. On the toolbar, click the Execute button.4. When the command has completed successfully, right-click the Triggers folder in Object Explorer, and then click Refresh to verify that the dEmployee trigger has been created.5. Click the New Query button on the toolbar.6. In the new, blank query window, type the following Transact-SQL code. USE AdventureWorks GO DELETE FROM HumanResources.Employee WHERE EmployeeID = 17. On the toolbar, click the Execute button.8. Verify that the delete is unsuccessful, and that the trigger returns an error.9. Close SQL Server Management Studio. Click No if prompted to save files.
    • 5–44 Module 5: Implementing Data IntegrityLesson 4: Implementing XML Schemas**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the purpose of XML schemas. ■ Explain the purpose of an XML schema collection. ■ Define typed XML and describe how it works.Introduction The xml data type supports both typed and untyped XML. To use typed XML, you must define XML schemas and associate those schemas with a column, a parameter, or a variable of the xml data type by using an XML schema collection. In this lesson, you will learn what XML schemas and XML schema collections are as well how to use them to implement typed XML data.
    • Module 5: Implementing Data Integrity 5–45What Are XML Schemas?**************************************** Illegal for non-trainer use ***************************************Definition An XML schema defines the elements and attributes that are valid in any XML document associated with the schema.XML Schema syntax The XML Schema syntax is defined by the World Wide Web Consortium (W3C). An XML schema is contained in a top-level schema element and identified by the targetNamespace definition. Here is an example XML schema definition. <xsd:schema targetNamespace="http://schemas.microsoft.com/sqlserver/2004/ 07/adventure-works/ProductModelManuInstructions" xmlns ="http://schemas.microsoft.com/sqlserver/2004/07/adventure- works/ProductModelManuInstructions" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" > <xsd:complexType name="StepType" mixed="true" > <xsd:choice minOccurs="0" maxOccurs="unbounded" > <xsd:element name="tool" type="xsd:string" /> <xsd:element name="material" type="xsd:string" /> <xsd:element name="blueprint" type="xsd:string" /> <xsd:element name="specs" type="xsd:string" /> <xsd:element name="diag" type="xsd:string" /> </xsd:choice> </xsd:complexType> <xsd:element name="root"> <xsd:complexType mixed="true"> <xsd:sequence> <xsd:element name="Location" minOccurs="1" maxOccurs="unbounded"> <xsd:complexType mixed="true"> <xsd:sequence> <xsd:element name="step" type="StepType" minOccurs="1" maxOccurs="unbounded" /> </xsd:sequence>
    • 5–46 Module 5: Implementing Data Integrity <xsd:attribute name="LocationID" type="xsd:integer" use="required"/> <xsd:attribute name="SetupHours" type="xsd:decimal" use="optional"/> <xsd:attribute name="MachineHours" type="xsd:decimal" use="optional"/> <xsd:attribute name="LaborHours" type="xsd:decimal" use="optional"/> <xsd:attribute name="LotSize" type="xsd:decimal" use="optional"/> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> For More Information For more information about the XML schema syntax, see “XML Schema” on the W3C Web site.
    • Module 5: Implementing Data Integrity 5–47What Is an XML Schema Collection?**************************************** Illegal for non-trainer use ***************************************Definition XML schemas are registered in XML schema collection objects in a database. Each XML schema collection can contain one or more XML schemas, each identified by using a namespace (specified in the targetNamespace attribute of the schema).How to create XML To create an XML schema collection, use the CREATE XML SCHEMA COLLECTIONschema collections statement. The syntax for the CREATE XML SCHEMA COLLECTION statement is shown here. CREATE XML SCHEMA COLLECTION sql_identifier AS Expression The parameters in the CREATE XML SCHEMA COLLECTION syntax are described in the following table. Parameter Description sql_identifier A valid Transact-SQL identifier for the XML schema collection Expression An XML value containing one or more XML schema documents The following example shows how to use the CREATE XML SCHEMA COLLECTION statement to register an XML schema collection named ResumeSchemaCollection, which contains a single schema with the namespace http://schemas.adventure- works.com/EmployeeResume. CREATE XML SCHEMA COLLECTION ResumeSchemaCollection AS N<?xml version="1.0" ?> <xsd:schema targetNamespace= "http://schemas.adventure-works.com/EmployeeResume" xmlns="http://schemas.adventure-works.com/EmployeeResume" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
    • 5–48 Module 5: Implementing Data Integrity <xsd:element name="resume"> <xsd:complexType> <xsd:sequence> <xsd:element name="name" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="employmentHistory"> <xsd:complexType> <xsd:sequence minOccurs="1" maxOccurs="unbounded"> <xsd:element name="employer"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="endDate" use="optional"/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> You can modify an XML schema collection by using the ALTER XML SCHEMA COLLECTION statement. You can use the ALTER XML SCHEMA COLLECTION statement to add or remove schemas from a schema collection. You remove an XML schema collection by using the DROP XML SCHEMA COLLECTION statement, as shown in the following example. DROP XML SCHEMA COLLECTION ResumeSchemaCollection You cannot drop an XML schema collection that contains schemas that are referenced by typed xml columns. You must first remove the referencing by altering or dropping the table.How to view XML schema You can view information about the schema collections in a database by querying theinformation sys.xml_schema_collections catalog view, as shown in the following example. SELECT * FROM sys.xml_schema_collections You can also retrieve the individual XML namespaces defined in the database’s schema collections by querying the sys.xml_schema_namespaces catalog view, as shown in the following example. SELECT * FROM sys.xml_schema_namespaces You can view the XML components defined in the database by querying the sys.xml_schema_components catalog view, as shown in the following example. SELECT * FROM sys.xml_schema_components
    • Module 5: Implementing Data Integrity 5–49What Is Typed XML?**************************************** Illegal for non-trainer use ***************************************Definition Typed XML is XML that is associated with an XML schema. When the xml data type is used to store typed XML, SQL Server validates the XML against the schema and optimizes the internal storage of the data by assigning appropriate SQL Server data types to the data based on the XML data types defined in the schema.Referencing a schema To use typed XML, you must declare the xml column or variable and associate the XML schema collection that contains the schema that you want to use to validate the XML. The following example shows how to define a table by using an xml column associated with the ResumeSchemaCollection XML schema collection. CREATE TABLE HumanResources.EmployeeResume (EmployeeID int, Resume xml (ResumeSchemaCollection)) You declare typed xml variables in the same way, as shown in the following example. DECLARE @resumeDoc xml (ResumeSchemaCollection)How SQL Server You assign a value to a typed xml column or variable in the same way that you assign anvalidates typed XML untyped value. However, the XML string you assign must conform to a schema in the XML schema collection associated with the column or variable and must be declared within the same target namespace. The following example shows how to assign a typed xml value. INSERT INTO HumanResources.EmployeeResume VALUES (1, <?xml version="1.0" ?>
    • 5–50 Module 5: Implementing Data Integrity <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>)CONTENT vs. DOCUMENT You can control whether a typed xml column or variable limits values to a single document or allows a fragment composed of multiple documents by specifying CONTENT or DOCUMENT in the definition. Specifying CONTENT allows valid fragments, while specifying DOCUMENT ensures that only single document instances can be assigned. If neither keyword is specified, the default value is CONTENT. The following example shows how to use the DOCUMENT keyword to limit the allowable values in a column to single valid documents. CREATE TABLE HumanResources.EmployeeResume (EmployeeID int, Resume xml (DOCUMENT ResumeSchemaCollection))
    • Module 5: Implementing Data Integrity 5–51Practice: Using Typed XML**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to use typed XML.Preparation Ensure that virtual machine 2779A-MIA-SQL-05 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To create a new SQL You must perform the following steps to create a new schema collection:schema collection 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and 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 Authentication Windows Authentication 3. On the File menu, point to Open and click File. 4. Browse to the D:Practices folder and open CreateEmployeeResumeSchemaCollection.sql. When prompted, connect to MIAMI by using Windows authentication. 5. Examine the code, and notice that it creates an XML schema collection containing a single XML schema.
    • 5–52 Module 5: Implementing Data Integrity 6. On the toolbar, click the Execute button. 7. Keep SQL Server Management Studio open. You will use it in the next procedure.To create a typed XML You must perform the following steps to create a typed XML column:column 1. In SQL Server Management Studio, if Object Explorer is not visible, click Object Explorer on the View menu. 2. In Object Explorer, expand Databases, AdventureWorks, and Tables. 3. In SQL Server Management Studio, click the New Query button on the toolbar. 4. In the new, blank query window, type the following Transact-SQL code. USE AdventureWorks GO CREATE TABLE HumanResources.EmployeeResume (EmployeeID int, Resume xml (EmployeeResumeSchemaCollection)) 5. On the toolbar, click the Execute button. 6. When the command has completed successfully, right-click the Tables folder in Object Explorer, and then click Refresh to verify that the EmployeeResume table has been created. 7. In Object Explorer, expand EmployeeResume, Columns, and verify that the EmployeeResumeSchemaCollection schema collection is associated with the Resume column. 8. Keep SQL Server Management Studio open. You will use it in the next procedure.To insert data into a You must perform the following steps to insert data into a typed XML column:typed XML column 1. In SQL Server Management Studio, click the New Query button on the toolbar. 2. In the new, blank query window, type the following Transact-SQL code. USE AdventureWorks INSERT INTO HumanResources.EmployeeResume VALUES (1, <?xml version="1.0" ?> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> <hobby>football</hobby> </resume>) 3. On the toolbar, click the Execute button. 4. When the command fails, review the error message, and note that the hobby element is not permitted within the EmployeeResumeSchemaCollection schema collection.
    • Module 5: Implementing Data Integrity 5–535. Edit the query to remove the <hobby>football</hobby> line. The correct Transact-SQL code is shown here. INSERT INTO HumanResources.EmployeeResume VALUES (1, <?xml version="1.0" ?> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>)6. On the toolbar, click the Execute button.7. Close SQL Server Management Studio. Click No if prompted to save files.
    • 5–54 Module 5: Implementing Data IntegrityLab: Implementing Data Integrity**************************************** Illegal for non-trainer use ***************************************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 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: ● 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 new DELETE trigger named dJobCandidate on the HumanResources.JobCandidate table that copies the candidate’s 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.
    • Module 5: Implementing Data Integrity 5–55 ■ Create a SQL Server Scripts project for the modifications by using SQL Server Management Studio, and then store the project in the D:LabfilesStarter folder. ■ A file named HistoricResumeSchema.xml containing the schema for the HistoricResumeSchemaCollection XML schema collection is provided in the D:LabfilesStarter folder.Additional information When performing administrative 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. To add a query file to a project: 1. Click New Query on the Project menu, or right-click the Queries folder in Solution Explorer and click New Query. If Solution Explorer is not visible, you can display it by clicking Solution Explorer on the View menu. 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. Change the name of the query file from the default name (SQLQuery1.sql) by right-clicking it in Solution Explorer and clicking Rename. Although you can perform all administrative 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 Script drop-down 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 and then script each action to the Clipboard as it is performed and 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, you can display it by clicking Object Explorer on the View menu.Preparation Ensure that virtual machine 2779A-MIA-SQL-05 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.
    • 5–56 Module 5: Implementing Data IntegrityExercise 1: Creating ConstraintsCreating constraints Task Supporting information Create a SQL Server Scripts 1. Create a new SQL Server Scripts project named project. AW_DataIntegrity. 2. Add a new query to the project, connecting to MIAMI by using Windows authentication when prompted. Change the query file name to TableAndConstraints.sql. Create the 1. In the query window, type the appropriate JobCandidateHistory table Transact-SQL statement to create the and constraints. HumanResources.JobCandidateHistory table in the AdventureWorks database. 2. Execute the query, and then save the query file. 3. Use Object Explorer to verify that the table and constraints have been created. 4. Keep SQL Server Management Studio open. You will use it in the next exercise. Test the 1. In SQL Server Management Studio, open the JobCandidateHistory table TestConstraints.sql script file in the and constraints. D:LabfilesStarter folder. Connect to MIAMI by using Windows authentication when prompted. 2. Select the code under the comment This should fail and click the Execute button. The INSERT operation should fail because the Rating value conflicts with the CHECK constraint. 3. Select the code under the comment This should succeed and click the Execute button. The INSERT operation should succeed.
    • Module 5: Implementing Data Integrity 5–57Exercise 2: Creating TriggersCreating a trigger Task Supporting information Create a new query file. 1. In Solution Explorer, add a new query to the project, connecting to MIAMI by using Windows authentication when prompted. 2. Change the query file name to Trigger.sql. Create the dJobCandidate 1. In the query window, type the appropriate trigger. Transact-SQL statement to create the dJobCandidate trigger on the HumanResources.JobCandidate table in the AdventureWorks database. 2. Execute the query, and then save the query file. 3. Use Object Explorer to verify that the trigger has been created. 4. Keep SQL Server Management Studio open. You will use it in the next exercise. Test the dJobCandidate 1. In SQL Server Management Studio, open the trigger. TestTrigger.sql script file in the D:LabfilesStarter folder. Connect to MIAMI by using Windows authentication when prompted. 2. Execute the query script, and look in the Results Pane to verify that the record deleted from the HumanResources.JobCandidate table is inserted into the HumanResources.JobCandidateHistory table.
    • 5–58 Module 5: Implementing Data IntegrityExercise 3: Implementing XML SchemasImplementing an XMLschema Task Supporting information Create a new query file. 1. Add a new query to the project. When prompted, use Windows authentication to connect to MIAMI. 2. Rename the new query file to XMLSchema.sql. Implement the 1. Use SQL Server Management Studio to open HistoricResumeSchema XML the file named HistoricResumeSchema.xml schema. in the D:LabfilesStarter folder, and then copy its contents to the Clipboard. 2. In the XMLSchema.sql query window in Solution Explorer, type the appropriate Transact-SQL statement to create the HistoricResumeSchemaCollection XML schema collection, and then modify the JobCandidateHistory table to make the Resume column typed XML. 3. Execute the query, and then save the query file. 4. Use Object Explorer to verify that the Resume column is now typed XML. 5. Close SQL Server Management Studio. Test the HistoricResumeSchema 1. In SQL Server Management Studio, open the XML schema. TestXMLSchema.sql script file in the D:LabfilesStarter folder. Connect to MIAMI by using Windows authentication when prompted. 2. Select the code under the comment This should fail and click the Execute button. The INSERT operation should fail because the Resume XML does not conform to the schema. 3. Select the code under the comment This should succeed and click the Execute button. The INSERT operation should succeed.Results checklist Use the following checklist of results to verify whether you have successfully performed this lab: ■ Created a table named JobCandidateHistory in the AdventureWorks database. ■ Created a trigger named dJobCandidate in the AdventureWorks database. ■ Created an XML schema collection named HistoricResumeSchemaCollection in the AdventureWorks database.