Sie sind auf Seite 1von 514

OFFICIAL

MICROSOFT

LEARNING

PRODUCT

6232A
Implementing a Microsoft SQL Server 2008 Database

Be sure to access the extended learning content on your Course Companion CD enclosed on the back cover of the book.

ii

Implementing a Microsoft SQL Server 2008 Database

Information in this document, including URL and other Internet Web site references, is subject to change without 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 any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a 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 Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents 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 imply endorsement of Microsoft of the site or the products contained therein. 2008 Microsoft Corporation. All rights reserved. Microsoft, Excel, IntelliSense, Internet Explorer, MS, MSDN, PowerPoint, SQL Server, Visual Basic, Visual C#, Visual C++, Visual Studio, Windows and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are property of their respective owners.

Technical Reviewer: Geoff Black

Product Number: 6232A Part Number X15-01555 Released: 11/2008

MICROSOFT LICENSE TERMS OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER EDITION Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to the Licensed Content named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft updates, supplements, Internet-based services, and support services

for this Licensed Content, unless other terms accompany those items. If so, those terms apply. By using the Licensed Content, you accept these terms. If you do not accept them, do not use the Licensed Content. If you comply with these license terms, you have the rights below.

1. DEFINITIONS. a. Academic Materials means the printed or electronic documentation such as manuals,
workbooks, white papers, press releases, datasheets, and FAQs which may be included in the Licensed Content. location, an IT Academy location, or such other entity as Microsoft may designate from time to time. conducted at or through Authorized Learning Centers by a Trainer providing training to Students solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or MOC) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions Courseware). Each Authorized Training Session will provide training on the subject matter of one (1) Course. Center during an Authorized Training Session, each of which provides training on a particular Microsoft technology subject matter.

b. Authorized Learning Center(s) means a Microsoft Certified Partner for Learning Solutions

c. Authorized Training Session(s) means those training sessions authorized by Microsoft and

d. Course means one of the courses using Licensed Content offered by an Authorized Learning

e. Device(s) means a single computer, device, workstation, terminal, or other digital electronic or
analog device.

f.

Licensed Content means the materials accompanying these license terms. The Licensed Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student Content, (iii) classroom setup guide, and (iv) Software. There are different and separate components of the Licensed Content for each Course. Software means the Virtual Machines and Virtual Hard Disks, or other software applications that may be included with the Licensed Content.

g.

h. Student(s) means a student duly enrolled for an Authorized Training Session at your location.

i.

Student Content means the learning materials accompanying these license terms that are for use by Students and Trainers during an Authorized Training Session. Student Content may include labs, simulations, and courseware files for a Course. Trainer(s) means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer and b) such other individual as authorized in writing by Microsoft and has been engaged by an Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its behalf. Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and demonstration guides and script files for a Course. Virtual Hard Disks means Microsoft Software that is comprised of virtualized hard disks (such as a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single computer or other device in order to allow end-users to run multiple operating systems concurrently. For the purposes of these license terms, Virtual Hard Disks will be considered Trainer Content. Microsoft Virtual PC or Microsoft Virtual Server software that consists of a virtualized hardware environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard Disks will be considered Trainer Content. you means the Authorized Learning Center or Trainer, as applicable, that has agreed to these license terms.

j.

k. Trainer Content means the materials accompanying these license terms that are for use by

l.

m. Virtual Machine means a virtualized computing experience, created and accessed using

n.

2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and electronic), Trainer Content, Student Content, classroom setup guide, and associated media. License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center location or per Trainer basis.

3. INSTALLATION AND USE RIGHTS. a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may: i. either install individual copies of the relevant Licensed Content on classroom Devices only for use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided that the number of copies in use does not exceed the number of Students enrolled in and the Trainer delivering the Authorized Training Session, OR

ii. install one copy of the relevant Licensed Content on a network server only for access by classroom Devices and only for use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided that the number of Devices accessing the Licensed Content on such server does not exceed the number of Students enrolled in and the Trainer delivering the Authorized Training Session. iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to use the Licensed Content that you install in accordance with (ii) or (ii) above during such Authorized Training Session in accordance with these license terms.

i.

Separation of Components. The components of the Licensed Content are licensed as a single unit. You may not separate the components and install them on different Devices.

ii. Third Party Programs. The Licensed Content may contain third party programs. These license terms will apply to the use of those third party programs, unless other terms accompany those programs.

b. Trainers:
i. Trainers may Use the Licensed Content that you install or that is installed by an Authorized Learning Center on a classroom Device to deliver an Authorized Training Session.

ii. Trainers may also Use a copy of the Licensed Content as follows:

A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for your own personal training Use and for preparation of an Authorized Training Session. personal training Use and for preparation of an Authorized Training Session.

B. Portable Device. You may install another copy on a portable device solely for your own 4. PRE-RELEASE VERSIONS. If this is a pre-release (beta) version, in addition to the other provisions
in this agreement, these terms also apply:

a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not

contain the same information and/or work the way a final version of the Licensed Content will. We may change it for the final, commercial version. We also may not release a commercial version. You will clearly and conspicuously inform any Students who participate in each Authorized Training Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with any further content, including but not limited to the final released version of the Licensed Content for the Course. Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software, Licensed Content, or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement.

b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to

c. Confidential Information. The Licensed Content, including any viewer, user interface, features

and documentation that may be included with the Licensed Content, is confidential and proprietary to Microsoft and its suppliers. i. Use. For five years after installation of the Licensed Content or its commercial release, whichever is first, you may not disclose confidential information to third parties. You may disclose confidential information only to your employees and consultants who need to know the information. You must have written agreements with them that protect the confidential information at least as much as this agreement. Survival. Your duty to protect confidential information survives this agreement.

ii.

iii. Exclusions. You may disclose confidential information in response to a judicial or governmental order. You must first give written notice to Microsoft to allow it to seek a

protective order or otherwise protect the information. Confidential information does not include information that d. becomes publicly known through no wrongful act; you received from a third party who did not breach confidentiality obligations to Microsoft or its suppliers; or you developed independently.

Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs you is the end date for using the beta version, or (ii) the commercial release of the final release version of the Licensed Content, whichever is first (beta term). Use. You will cease using all copies of the beta version upon expiration or termination of the beta term, and will destroy all copies of same in the possession or under your control and/or in the possession or under the control of any Trainers who have received copies of the pre-released version. Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you for such copies and distribution.

e.

f.

5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.


a. Authorized Learning Centers and Trainers: i. Software.

ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced Server and/or other Microsoft products which are provided in Virtual Hard Disks. A. If the Virtual Hard Disks and the labs are launched through the Microsoft Learning Lab Launcher, then these terms apply: Time-Sensitive Software. If the Software is not reset, it will stop running based upon the time indicated on the install of the Virtual Machines (between 30 and 500 days after you install it). You will not receive notice before it stops running. You may not be able to access data used or information saved with the Virtual Machines when it stops running and may be forced to reset these Virtual Machines to their original state. You must remove the Software from the Devices at the end of each Authorized Training Session and reinstall and launch it prior to the beginning of the next Authorized Training Session. B. If the Virtual Hard Disks require a product key to launch, then these terms apply: Microsoft will deactivate the operating system associated with each Virtual Hard Disk. Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized Training Session, you will obtain from Microsoft a product key for the operating system software for the Virtual Hard Disks and will activate such Software with Microsoft using such product key. C. These terms apply to all Virtual Machines and Virtual Hard Disks:

You may only use the Virtual Machines and Virtual Hard Disks if you comply with the terms and conditions of this agreement and the following security requirements: o o You may not install Virtual Machines and Virtual Hard Disks on portable Devices or Devices that are accessible to other networks. You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at the end of each Authorized Training Session, except those held at Microsoft Certified Partners for Learning Solutions locations. You must remove the differencing drive portions of the Virtual Hard Disks from all classroom Devices at the end of each Authorized Training Session at Microsoft Certified Partners for Learning Solutions locations. You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or downloaded from Devices on which you installed them. You will strictly comply with all Microsoft instructions relating to installation, use, activation and deactivation, and security of Virtual Machines and Virtual Hard Disks. You may not modify the Virtual Machines and Virtual Hard Disks or any contents thereof. You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.

o o o o

ii. Classroom Setup Guide. You will assure any Licensed Content installed for use during an
Authorized Training Session will be done in accordance with the classroom set-up guide for the Course. iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip art, animations, sounds, music, shapes, video clips and templates provided with the Licensed Content solely in an Authorized Training Session. If Trainers have their own copy of the Licensed Content, they may use Media Elements for their personal training use. iv. iv Evaluation Software. Any Software that is included in the Student Content designated as Evaluation Software may be used by Students solely for their personal training outside of the Authorized Training Session.

b. Trainers Only:
i. Use of PowerPoint Slide Deck Templates. The Trainer Content may include Microsoft PowerPoint slide decks. Trainers may use, copy and modify the PowerPoint slide decks only for providing an Authorized Training Session. If you elect to exercise the foregoing, you will agree or ensure Trainer agrees: (a) that modification of the slide decks will not constitute creation of obscene or scandalous works, as defined by federal law at the time the work is created; and (b) to comply with all other terms and conditions of this agreement.

ii. Use of Instructional Components in Trainer Content. For each Authorized Training Session, Trainers may customize and reproduce, in accordance with the MCT Agreement, those portions of the Licensed Content that are logically associated with instruction of the Authorized Training Session. If you elect to exercise the foregoing rights, you agree or ensure the Trainer agrees: (a) that any of these customizations or reproductions will only be used for providing an Authorized Training Session and (b) to comply with all other terms and conditions of this agreement.

iii. Academic Materials. If the Licensed Content contains Academic Materials, you may copy and use the Academic Materials. You may not make any modifications to the Academic Materials and you may not print any book (either electronic or print version) in its entirety. If you reproduce any Academic Materials, you agree that:

The use of the Academic Materials will be only for your personal reference or training use You will not republish or post the Academic Materials on any network computer or broadcast in any media; You will include the Academic Materials original copyright notice, or a copyright notice to Microsofts benefit in the format provided below: Form of Notice: 2008 Reprinted for personal reference use only with permission by Microsoft Corporation. All rights reserved. Microsoft, Windows, and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the US and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

6. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed

Content. It may change or cancel them at any time. You may not use these services in any way that could harm them or impair anyone elses use of them. You may not use the services to try to gain unauthorized access to any service, data, account or network by any means.

7. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some

rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only allow you to use it in certain ways. You may not install more copies of the Licensed Content on classroom Devices than the number of Students and the Trainer in the Authorized Training Session; allow more classroom Devices to access the server than the number of Students enrolled in and the Trainer delivering the Authorized Training Session if the Licensed Content is installed on a network server; copy or reproduce the Licensed Content to any server or location for further reproduction or distribution; disclose the results of any benchmark tests of the Licensed Content to any third party without Microsofts prior written approval; work around any technical limitations in the Licensed Content; reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent that applicable law expressly permits, despite this limitation; make more copies of the Licensed Content than specified in this agreement or allowed by applicable law, despite this limitation; publish the Licensed Content for others to copy;

transfer the Licensed Content, in whole or in part, to a third party; access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not been authorized by Microsoft to access and use; rent, lease or lend the Licensed Content; or use the Licensed Content for commercial hosting services or general business purposes. Rights to access the server software that may be included with the Licensed Content, including the Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft intellectual property in software or devices that may access the server.

8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and

regulations. You must comply with all domestic and international export laws and regulations that apply to the Licensed Content. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting. Content marked as NFR or Not for Resale.

9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed 10. ACADEMIC EDITION. You must be a Qualified Educational User to use Licensed Content marked as
Academic Edition or AE. If you do not know whether you are a Qualified Educational User, visit www.microsoft.com/education or contact the Microsoft affiliate serving your country. fail to comply with the terms and conditions of these license terms. In the event your status as an Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this agreement, you must destroy all copies of the Licensed Content and all of its component parts.

11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you

12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-

based services and support services that you use, are the entire agreement for the Licensed Content and support services.

13. APPLICABLE LAW. a. United States. If you acquired the Licensed Content in the United States, Washington state law
governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.

b. Outside the United States. If you acquired the Licensed Content in any other country, the laws
of that country apply.

14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the

laws of your country. You may also have rights with respect to the party from whom you acquired the Licensed Content. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so.

15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed as-is. You bear the risk of
using it. Microsoft gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this agreement cannot change. To the extent permitted under your local laws, Microsoft excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.

16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES. This limitation applies to anything related to the Licensed Content, software, services, content (including code) on third party Internet sites, or third party programs; and claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.

It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages. Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this agreement are provided below in French. Remarque : Ce le contenu sous licence tant distribu au Qubec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en franais. EXONRATION DE GARANTIE. Le contenu sous licence vis par une licence est offert tel quel . Toute utilisation de ce contenu sous licence est votre seule risque et pril. Microsoft naccorde aucune autre garantie expresse. Vous pouvez bnficier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualit marchande, dadquation un usage particulier et dabsence de contrefaon sont exclues. LIMITATION DES DOMMAGES-INTRTS ET EXCLUSION DE RESPONSABILIT POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement hauteur de 5,00 $ US. Vous ne pouvez prtendre aucune indemnisation pour les autres dommages, y compris les dommages spciaux, indirects ou accessoires et pertes de bnfices. Cette limitation concerne: tout ce qui est reli au le contenu sous licence , aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et les rclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilit stricte, de ngligence ou dune autre faute dans la limite autorise par la loi en vigueur.

Elle sapplique galement, mme si Microsoft connaissait ou devrait connatre lventualit dun tel dommage. Si votre pays nautorise pas lexclusion ou la limitation de responsabilit pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou lexclusion ci-dessus ne sappliquera pas votre gard. EFFET JURIDIQUE. Le prsent contrat dcrit certains droits juridiques. Vous pourriez avoir dautres droits prvus par les lois de votre pays. Le prsent contrat ne modifie pas les droits que vous confrent les lois de votre pays si celles-ci ne le permettent pas.

Implementing a Microsoft SQL Server 2008 Database

xi

Acknowledgement
Microsoft Learning would like to acknowledge and thank the following for their contribution towards developing this title. Their effort at various stages in the development has ensured that you have a good classroom experience.

Peter Lammers Lead Developer


Peter Lammers joined Aeshen in 2002 as a Product Analyst, and he has been a Lead Product Analyst since 2005, working on Microsoft TechNet Content, Webcasts, White Papers, and Microsoft Learning Courses. Prior to that he has been a computer programmer and network technician with a 14-year background in troubleshooting, training, modifying and supporting a software application; network administration, troubleshooting, and server, desktop, and firewall support.

Sean Masters Content Developer


Mr. Masters joined Aeshen in 2007. He has worked in SMB technical operations for nearly 10 years including 4 years as manager of information technology at a property management firm and 4 years as a private consultant to various legal and financial firms in the New England area.

Sunni Brock Content Developer


Sunni has been working with Aeshen as a content developer since 2006. In her 20year career, she spent 15 years at Microsoft as a Lead Program Manager in the Windows Product Group and as a Technical Support lead replicating customer configuration scenarios. Prior to joining Aeshen, she served as a Technical Account Manager for Sonic Solutions/Roxio acting as liaison to Adobe, Microsoft, Sony, and other technology leaders.

Seth Wolf Content Developer


Seth Wolf has been working with computing technology for over 20 years. His background includes programming, database design, Web site design, network management, hardware troubleshooting, and user support. He remembers the good old days of dBase and Btrieve.

Jerry Knowles Content Developer


Mr. Knowles joined Aeshen in 2008 as an Application Analyst. He has worked in Information Technology since 1989 as an instructor, application developer, SQL database administrator, and consultant.

xii

Implementing a Microsoft SQL Server 2008 Database

Karl Middlebrooks - Subject Matter Expert


Mr. Middlebrooks is a Product Analyst with Aeshen, and joined in 2004. He has over 20 years experience in IT and Operations management, network administration, and database administration.

Geoff Black Technical Reviewer


Geoff is the Principal MCT for IT Training Solutions in Brisbane, Australia. He holds a degree in Computational Physics with Distinction and multiple Developer and Infrastructure certifications. With more than 20 years experience in Information Technology, he has become a demonstrated leader in the field through pioneering many new and innovative technologies.

Implementing a Microsoft SQL Server 2008 Database

xiii

Contents
Module 1: Creating Databases and Database Files
Lesson 1: Creating Databases Lesson 2: Creating Filegroups Lesson 3: Creating Schemas Lesson 4: Creating Database Snapshots Lab: Creating Databases and Database Files 1-3 1-11 1-15 1-19 1-25

Module 2: Creating Data Types and Tables


Lesson 1: Creating Data Types Lesson 2: Creating Tables Lesson 3: Creating Partitioned Tables Lab: Creating Data Types and Tables 2-3 2-8 2-17 2-23

Module 3: Creating and Tuning Indexes


Lesson 1: Planning Indexes Lesson 2: Creating Indexes Lesson 3: Optimizing Indexes Lab: Creating and Optimizing Indexes 3-3 3-8 3-21 3-29

Module 4: Implementing Data Integrity by Using Constraints and Triggers


Lesson 1: Data Integrity Overview Lesson 2: Implementing Constraints Lesson 3: Implementing Triggers Lab: Implementing Data Integrity by Using Constraints and Triggers 4-3 4-7 4-14 4-27

xiv

Implementing a Microsoft SQL Server 2008 Database

Module 5: Using XML


Lesson 1: Using the XML Data Type Lesson 2: Retrieving XML by Using FOR XML Lesson 3: Shredding XML by Using OPENXML Lab 5A: Using XML Lesson 4: Introducing XQuery Lesson 5: Creating XML Indexes Lesson 6: Implementing XML Schemas Lab 5B: Using XML 5-3 5-12 5-21 5-27 5-37 5-43 5-48 5-54

Module 6: Implementing Views


Lesson 1: Introduction to Views Lesson 2: Creating and Managing Views Lesson 3: Optimizing Performance by Using Views Lab: Implementing Views 6-3 6-9 6-19 6-24

Module 7: Implementing Stored Procedures


Lesson 1: Using Stored Procedures Lesson 2: Creating Parameterized Stored Procedures Lesson 3: Working with Execution Plans Lesson 4: Handling Exceptions Lab: Implementing Stored Procedures 7-3 7-12 7-17 7-24 7-28

Module 8: Implementing Functions


Lesson 1: Introducing Functions Lesson 2: Working with Functions Lesson 3: Controlling Execution Context Lab: Implementing Functions 8-3 8-9 8-13 8-17

Implementing a Microsoft SQL Server 2008 Database

xv

Module 9: Implementing Managed Code in a Database


Lesson 1: Introduction to the SQL Server Common Language Runtime Lesson 2: Importing and Configuring Assemblies Lesson 3: Creating Managed Database Objects Lab: Implementing Managed Code in a Database 9-4 9-10 9-15 9-20

Module 10: Managing Transactions and Locks


Lesson 1: Overview of Transactions and Locks Lesson 2: Managing Transactions Lesson 3: Understanding SQL Server Locking Architecture Lesson 4: Managing Locks Lab: Managing Transactions and Locks 10-3 10-11 10-25 10-34 10-49

Module 11: Using Service Broker


Lesson 1: Service Broker Overview Lesson 2: Creating Service Broker Objects Lesson 3: Sending and Receiving Messages Lab: Using Service Broker 11-3 11-14 11-22 11-27

Lab Answer Keys

About This Course

xvii

MCT USE ONLY. STUDENT USE PROHIBITED

About This Course


This section provides you with a brief description of the course, audience, suggested prerequisites, and course objectives.

Course Description
This five-day instructor-led course provides students with the knowledge and skills to implement a Microsoft SQL Server 2008 database. The course focuses on teaching individuals how to use SQL Server 2008 product features and tools related to implementing a database.

Audience
The primary audience for this course is IT Professionals who want to become skilled on SQL Server 2008 product features and technologies for implementing a database. The secondary audiences for this course are individuals who are developers from other product platforms or previous versions of SQL Server looking to become skilled in the implementation of a SQL Server 2008 database.

Student Prerequisites
This course requires that you meet the following prerequisites: Working knowledge of Transact-SQL. Working knowledge of Relational databases. Core Windows Server skills. Database design skills. Basic knowledge of XML and XML schemas. SQL Server skills ability to write Transact-SQL queries or completed Course 2778: Writing Queries Using Microsoft SQL Server 2008 Transact-SQL.

xviii

About This Course

MCT USE ONLY. STUDENT USE PROHIBITED

Course Objectives
After completing this course, students will be able to: Create databases and database files. Create data types and tables. Plan, create, and optimize indexes. Implement data integrity in Microsoft SQL Server 2008 databases by using constraints. Implement data integrity in Microsoft SQL Server 2008 by using triggers. Use XML-related features in Microsoft SQL Server 2008. Implement views. Implement stored procedures. Implement functions. Implement managed code in the database. Manage transactions and locks. Use Service Broker to build a messaging-based solution.

About This Course

xix

MCT USE ONLY. STUDENT USE PROHIBITED

Course Outline
This section provides an outline of the course: Module 1: Creating Databases and Database Files This module introduces one of the most fundamental tasks that a database developer must perform, the creation of a database and its major components, such as creating databases, setting database options, creating filegroups, schemas, and database snapshots. Module 2: Creating Data Types and Tables This module introduces the system-supplied data types in SQL Server 2008. The students will learn how to define custom Transact-SQL data types and also describes how to create tables and how to use partitioned tables to organize data into multiple partitions. Module 3: Creating and Tuning Indexes This module describes how to plan, create, and optimize indexes to attain optimal performance benefits. Module 4: Implementing Data Integrity by Using Constraints and Triggers This module explains implementing data integrity in SQL Server 2008 by using constraints. They will also implement data integrity by using triggers. Module 5: Using XML This module describes how to work with XML, including use of the FOR XML clause, the OPENXML function, XQuery expressions, and the xml native data type. The students will learn the considerations you must take into account when creating XML indexes and the syntax used to create the XML indexes. They will also learn what XML schemas and XML schema collections are as well how to use them to implement typed XML data. Module 6: Implementing Views This module explains the different types of views available in Microsoft SQL Server 2008 which provide a convenient way to access data through a predefined query. Module 7: Implementing Stored Procedures This module describes the design and implementation of stored procedures to enforce business rules or data consistency, or to modify and maintain existing stored procedures written by other developers.

xx

About This Course

MCT USE ONLY. STUDENT USE PROHIBITED

Module 8: Implementing Functions This module discusses the design and implementation of user-defined functions that enforce business rules or data consistency, or to modify and maintain existing functions written by other developers. Module 9: Implementing Managed Code in the Database This module describes how to use managed code to implement database objects, such as stored procedures, user-defined data types, user-defined functions, and triggers. Module 10: Managing Transactions and Locks This module describes how to use transactions and SQL Server locking mechanisms to meet the performance and data integrity requirements of their applications. Module 11: Using Service Broker In this module you will learn more about Service Broker, how to create Service Broker objects, and how to use Service Broker to send and receive messages.

About This Course

xxi

MCT USE ONLY. STUDENT USE PROHIBITED

Course Materials
The following materials are included with your kit: Course Handbook. A succinct classroom learning guide that provides all the critical technical information in a crisp, tightly-focused format, which is just right for an effective in-class learning experience. Lessons: Guide you through the learning objectives and provide the key points that are critical to the success of the in-class learning experience. Labs: Provide a real-world, hands-on platform for you to apply the knowledge and skills learned in the module. Module Reviews and Takeaways: Provide improved on-the-job reference material to boost knowledge and skills retention. Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips when its needed. Course Companion CD. Searchable, easy-to-navigate digital content with integrated premium on-line resources designed to supplement the Course Handbook. Lessons: Include detailed information for each topic, expanding on the content in the Course Handbook. Labs: Include complete lab exercise information and answer keys in digital form to use during lab time. Resources: Include well-categorized additional resources that give you immediate access to the most up-to-date premium content on TechNet, MSDN, Microsoft Press Student Course Files: Include the Allfiles.exe, a self-extracting executable file that contains all the files required for the labs and demonstrations.

Note: To access the full course content, insert the Course Companion CD into the CDROM drive, and then in the root directory of the CD, double-click StartCD.exe.

Course evaluation. At the end of the course, you will have the opportunity to complete an online evaluation to provide feedback on the course, training facility, and instructor.

xxii

About This Course

MCT USE ONLY. STUDENT USE PROHIBITED

To provide additional comments or feedback on the course, send e-mail to support@mscourseware.com. To inquire about the Microsoft Certification Program, send e-mail to mcphelp@microsoft.com.

Virtual Machine Environment


This section provides the information for setting up the classroom environment to support the business scenario of the course.

Virtual Machine Configuration


In this course, you will use Microsoft Virtual Server 2005 R2 with SP1 to perform the labs.

Important: At the end of each lab, you must close the virtual machine and must not save any changes. To close a virtual machine without saving the changes, perform the following steps: 1. On the virtual machine, on the Action menu, click Close. 2. In the Close dialog box, in the What do you want the virtual machine to do? list, click Turn off and delete changes, and then click OK.

The following table shows the role of each virtual machine used in this course:
Virtual machine 6232A-NY-SQL-01 Role SQL Server for Adventure Works

Software Configuration
The following software is installed on each VM: Windows Server 2008 Enterprise Edition SQL Server 2008

Course Files
There are files associated with the labs in this course. The lab files are located in the folder E:\Labfiles on the student computers.

About This Course

xxiii

MCT USE ONLY. STUDENT USE PROHIBITED

Classroom Setup
Each classroom computer will have the same virtual machine configured in the same way.

Course Hardware Level


To ensure a satisfactory student experience, Microsoft Learning requires a minimum equipment configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft Learning Product courseware are taught. This course requires that you have a computer that meets or exceeds hardware level 5.5, which specifies a 2.4gigahertz (GHz) (minimum) Pentium 4 or equivalent CPU, at least 2 gigabytes (GB) of RAM, 16 megabytes (MB) of video RAM, and two 7200 RPM 40-GB hard disks.

MCT USE ONLY. STUDENT USE PROHIBITED

Implementing a Microsoft SQL Server 2008 Database

1-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 1
Creating Databases and Database Files
Contents:
Lesson 1: Creating Databases Lesson 2: Creating Filegroups Lesson 3: Creating Schemas Lesson 4: Creating Database Snapshots Lab: Creating Databases and Database Files 1-3 1-11 1-15 1-19 1-25

1-2

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

Databases in Microsoft SQL Server 2008 are made up of a collection of tables that store a specific set of structured data. Every SQL Server database has a primary filegroup that contains the primary data file and any secondary files. Inside every database is a schema, or a container that holds tables, views, and procedures. A database snapshot is a read-only, static view of a database used for reporting and recovery. In this module you will learn how to create databases, filegroups, schemas, and database snapshots using SQL Server Management Studio.

Implementing a Microsoft SQL Server 2008 Database

1-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Creating Databases

A database in SQL Server is made up of a collection of tables that stores a specific set of structured data. A table contains a collection of rows, also referred to as records or tuples, and columns, also referred to as attributes. It is important to consider the database type, table structure, and collation type when designing a database. In addition, every SQL Server 2008 database has a transaction log that records all transactions and the database modifications made by each transaction. The transaction log is a critical component of the database and, if there is a system failure, the transaction log might be required to bring your database back to a consistent state. Several database-level options that determine the characteristics of the database can be set for each database. These options are unique to each database and do not affect other databases. In this lesson you will learn several considerations for creating a database. You will also learn about transaction logging, database options, and data compression.

1-4

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Creating a Database

Key Points
Before creating a database, there are several things that must be taken into consideration. Online Transaction Processing (OLTP) relational databases typically have several users performing transactions at the same time and changing real-time data, so you must determine the likely access patterns of the data and plan to combine frequently accessed data together. Online Analytical Processing (OLAP) databases require you to take into account the cubes, measures and measure groups, dimensions, attributes, and hierarchies, as well as the perspectives and translations required by your organization.

Implementing a Microsoft SQL Server 2008 Database

1-5

MCT USE ONLY. STUDENT USE PROHIBITED

Collation settings, which include character set, sort order, and other localespecific settings, are fundamental to the structure and function of Microsoft SQL Server databases. When you select a collation for your server or database you are assigning certain characteristics to your data that will affect the results of many operations in your database. When you design a database, you must first decide the tables that it needs, the type of data that goes in each table, and the users that can access each table.

Question: What table characteristics should you take into account before creating an OLTP database and its objects?

1-6

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Transaction Logging

Key Points
Every SQL Server 2008 database has a transaction log that records all transactions and the database modifications made by each transaction. Note that the transaction log is a critical component of the database and, if there is a system failure, the transaction log might be required to bring your database back to a consistent state. Therefore it is vital to know at least what the transaction log is and how it operates before you create a database. If an application issues a ROLLBACK statement, or if the Database Engine detects an error such as the loss of communication with a client, transaction log records are used to roll back the modifications made by an incomplete transaction.

Implementing a Microsoft SQL Server 2008 Database

1-7

MCT USE ONLY. STUDENT USE PROHIBITED

When an instance of SQL Server is started, it runs a recovery of each database. Every modification recorded in the log which may not have been written to the data files is rolled forward. Every incomplete transaction found in the transaction log is then rolled back to make sure the integrity of the database is preserved. The Log Reader Agent monitors the transaction log of each database configured for transactional replication and copies the transactions marked for replication from the transaction log into the distribution database. The standby-server solutions, database mirroring, and log shipping, rely heavily on the transaction log. The Transaction Log supports the following operations. Recovery of individual transactions. Recovery of all incomplete transactions when SQL Server is started. Rolling a restored database, file, filegroup, or page forward to the point of failure. Transactional replication. Standby-server solutions.

The characteristics of the Transaction Log are: A log cache that is managed separately from the buffer cache for data pages. The format of log records and pages is not constrained to follow the format of data pages. Transaction logs can expand across multiple files.

Question: How can you roll a restored database, file, filegroup, or page forward to the point of failure?

1-8

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Database Options

Key Points
Several database-level options that determine the characteristics of the database can be set for each database. These options are unique to each database and do not affect other databases. After you set a database option, a checkpoint is automatically issued that causes the modification to take effect immediately. Many database options can be changed using ALTER DATABASE (T-SQL) or through the database properties window in SQL Server Management Studio.

Question: How are server-wide settings set in SQL Server?

Implementing a Microsoft SQL Server 2008 Database

1-9

MCT USE ONLY. STUDENT USE PROHIBITED

Data Compression

Key Points
The new data compression feature in SQL Server 2008 reduces the size of tables, indexes or a subset of their partitions by storing fixed-length data types in variable length storage format and by reducing the redundant data. ROW compression enables storing fixed length types in variable length storage format. Since column values are stored as variable length, an additional 4-bit length code is stored for each field within the row. PAGE compression minimizes storage of redundant data on the page by storing commonly occurring byte patterns on the page once and then referencing these values for respective columns. The relative CPU overhead with ROW is less than for PAGE, but PAGE compression can provide better compression.

1-10

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Databases

Question: What various options are available when creating a database? Question: How can you generate scripts in SQL Server Management Studio?

Implementing a Microsoft SQL Server 2008 Database

1-11

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Creating Filegroups

Every database has a primary filegroup. This filegroup contains the primary data file and any secondary files that are not put into other filegroups. User-defined filegroups can be created to group data files together for administrative, data allocation, and placement purposes. In this lesson you will learn what filegroups are and what information you need to know about when to create filegroups.

1-12

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Filegroups?

Key Points
Filegroups are named collections of files and are used to simplify data placement and administrative tasks such as backup and restore operations. Using files and filegroups can improve performance. The primary filegroup contains the primary data file and any secondary files that are not put into other filegroups, and the system tables of the user database. A user-defined filegroup is any filegroup that is specifically created by the user when the user first creates or later modifies the database. When objects are created in the database without specifying which filegroup they belong to, they are assigned to the default filegroup.

Implementing a Microsoft SQL Server 2008 Database

1-13

MCT USE ONLY. STUDENT USE PROHIBITED

Improving Database Performance by Using Filegroups

Key Points
Using files and filegroups can improve database performance by letting a database span multiple disks, multiple disk controllers, or RAID (redundant array of independent disks) systems. For tables that must not be modified, such as historical data, put them on filegroups and then mark the filegroup as read-only. This prevents accidental updates. SQL Server backup and restore operations support compressed filegroups. No modifications to the backup and restore implementation are required. Databases made up of multiple filegroups can be restored in stages by a process known as piecemeal restore, which can be performed either online or offline. Piecemeal restore works with all recovery models, but is more flexible for the full and bulk-logged models than for the simple model.

1-14

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Filegroups

Question: What is the file and filegroup fill strategy used by the SQL Server Database Engine? Question: How can using filegroups improve database performance?

Implementing a Microsoft SQL Server 2008 Database

1-15

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Creating Schemas

A database schema is a distinct namespace that is separate from a database user. Think of a schema as a container of objects. In this lesson you will learn about schemas and how object name resolution works in SQL Server 2008.

1-16

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Schemas?

Key Points
A schema is a container that holds tables, views, procedures, and so on. It is inside a database, which is inside a server. These entities fit together like nested boxes. The server is the outermost box, and the schema is the innermost box. Schemas can be created and altered in a database, and users can be granted access to a schema. A schema can be owned by any user, and schema ownership is transferable.

Question: How are schemas in SQL Server 2008 different from those in SQL Server 2005 and SQL Server 2000?

Implementing a Microsoft SQL Server 2008 Database

1-17

MCT USE ONLY. STUDENT USE PROHIBITED

How Object Name Resolution Works

Key Points
In order to resolve the names of securables that are not fully qualified names, SQL Server uses name resolution to check the schema owned by the calling database user and the schema owned by dbo. The default schema can be set and changed by using the DEFAULT_SCHEMA option of CREATE USER or ALTER USER. If DEFAULT_SCHEMA is left undefined, the database user will have dbo as its default schema. It is always good practice to be explicit with names and fully qualify object names with the schema such as schema.object. This is particularly important when creating or altering objects in SQL Server 2008.

1-18

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating a Schema

Question: Where are objects created by a CREATE SCHEMA statement created?

Implementing a Microsoft SQL Server 2008 Database

1-19

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 4

Creating Database Snapshots

A database snapshot provides a read-only, static view of a source database as it existed at snapshot creation, minus any uncommitted transactions. Snapshots can be used for reporting purposes. In this lesson you will learn how database snapshots work and you will learn about when to use database snapshots.

1-20

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

How Database Snapshots Work

Key Points
A database snapshot provides a read-only, static view of a source database as it existed at snapshot creation, minus any uncommitted transactions. Database Snapshots: Are dependent on the source database. Operate at the data-page level. Use one or more sparse files to store data.

Database snapshots are dependent on the source database. The snapshots of a database must be on the same server instance as the database.

Implementing a Microsoft SQL Server 2008 Database

1-21

MCT USE ONLY. STUDENT USE PROHIBITED

In the event of a user error on a source database, you can revert the source database to the state it was in when the snapshot was created. Data loss is confined to updates to the database since the snapshot's creation. As data is written to a sparse file, NTFS allocates disk space gradually. If a database snapshot runs out of space, it is marked as suspect, and it must be dropped, however, the source database is not affected.

Question: How can you find out the actual size of a sparse file?

1-22

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

When to Use Database Snapshots

Key Points
Clients can query a database snapshot, which makes it useful for writing reports based on the data at the time of snapshot creation. Also, if the source database later becomes damaged, you can revert the source database to the state it was in when the snapshot was created. Because a database snapshot provides a static view of a database, a snapshot can extend access to data from a particular point in time. Using database snapshots with database mirroring permits you to make the data on the mirror server accessible for reporting. Before doing major updates, such as a bulk update, create a database snapshot on the database protects data. If you make a mistake, you can use the snapshot to recover by reverting the database to the snapshot.

Implementing a Microsoft SQL Server 2008 Database

1-23

MCT USE ONLY. STUDENT USE PROHIBITED

By creating database snapshots on a regular basis, you can mitigate the impact of a major user error, such as a dropped table. In a testing environment, it can be useful when repeatedly running a test protocol for the database to contain identical data at the start of each round of testing.

1-24

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Database Snapshots

Question: What file types are not allowed in the CREATE DATABASE statement when creating a database snapshot?

Implementing a Microsoft SQL Server 2008 Database

1-25

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating Databases and Database Files

Exercise 1: Creating a Database


Scenario
The senior database developer at Adventure Works has created a specification for a new database in which details of the information technology (IT) assets used by the company will be stored. You must first use the specification to create the database with the necessary options and create the appropriate filegroups. To do this you will create a new database and create a SQL Server Management Studio Scripts project with the following specifications: The new database name is AW_IT_Assets. The database should consist of two data files and one log file with the names AW_IT_Assets_Data1, AW_IT_Assets_Data2, and AW_IT_Assets_log. These files should be created in the E:\MOD01\Labfiles folder. The database should use two filegroups, the primary filegroup and a filegroup named SECONDARY, which should be the default filegroup. The AW_IT_Assets_Data2 file should be placed in the SECONDARY filegroup.

1-26

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Both data files should have an initial size of 20 megabytes (MB) each and should not grow automatically. The log file should have an initial size of 5 MB and should not grow automatically. The database should automatically close when no users are connected and should automatically shrink when appropriate. All scripts should be saved in a SQL Server Scripts project in the E:\MOD01\Labfiles\Scripts folder.

The main tasks for this exercise are as follows: 1. 2. Create a SQL Server Management Studio Scripts project. Create a new database by executing a SQL Server Management Studio Scripts project.

Task 1: Create a SQL Server Management Studio Scripts project


1. 2. Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. Create the AW_IT_Assets database based on the specifications provided.

Task 2: Create a new database by executing a SQL Server Management


Studio Scripts project
Use the Generate Scripts Wizard to create a script of the database created in Task 1. Save these scripts in a SQL Server Scripts project in the E:\MOD01\Labfiles\Scripts folder.
Results: After this exercise, you should have created a new database with the appropriate options and filegroups and created a SQL Server Management Studio Scripts project.

Implementing a Microsoft SQL Server 2008 Database

1-27

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Creating a Schema


Scenario
The senior database developer is now requesting that access to the new database being used by the company be granted to a new user. In this exercise you will now create the required schemas for the new AW_IT_Assets database. The main tasks for this exercise are as follows: 1 2. 3. Create a new database user. Create a schema and assign ownership to a user. Display ownership of a schema.

Task 1: Create a new database user


Create a new database user named Katie. Do not grant Katie any permissions in the Database User window, as permissions will be added in the next task.

Task 2: Create a schema and assign ownership to a user


The database should have one user-defined schema named TechSupport. The user NY-SQL-01\Katie should use the TechSupport schema as her default schema.

Task 3: Display ownership of a schema


1. 2. 3. Create a T-SQL statement that displays ownership of the TechSupport schema. Comment the T-SQL statement to explain what it will do on execution. Execute the T-SQL statement.
Results: After this exercise, you should have created a schema and assigned ownership to a user. You should have also displayed ownership of the newly created schema.

1-28

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating a Database Snapshot


Scenario
The senior developer at Adventure Works is now requesting a database snapshot be created for reporting purposes. You will use T-SQL to write a statement that will create a database snapshot, change the current database, and then restore the database from the snapshot to undo those changes. In this exercise you will create a database snapshot, alter the database, and then revert the database to the previously created snapshot. The main tasks for this exercise are as follows: 1. 2. 3. Create a database snapshot. Alter the database. Revert the database to the previously created database snapshot.

Task 1: Create a database snapshot


A database snapshot named AW_IT_Assets_Snapshot1 must be created for reporting purposes. Using T-SQL, create a snapshot of the AW_IT_Assets database. The files for the database snapshot must be created in the E:\MOD01\Labfiles\Snapshots folder.

Task 2: Alter the database


Delete the TechSupport.Hardware table on the AW_IT_Assets database. Delete the TechSupport schema on the AW_IT_Assets database.

Implementing a Microsoft SQL Server 2008 Database

1-29

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Revert the database to the previously created database


snapshot
Create a T-SQL statement to revert the AW_IT_Assets database. Revert the database to the AW_IT_Assets_Snapshot1 database snapshot. Notice that the TechSupport.Hardware table and TechSupport schema have both been restored.
Results: After this exercise, you should have created a database snapshot, altered the database, and then reverted the database to the database snapshot.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

1-30

Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. When are objects assigned to the default filegroup? What is a database schema and how can schemas be used? How would you recover an accidently dropped table and all of the corresponding data from a database snapshot without recovering the entire database?

Best Practices related to creating databases


Supplement or modify the following best practices for your own work situations: When you design a database you must first decide the tables that it needs. Before you create a table and its objects, you should outline your plans about the following table characteristics: The types of data the table will contain.

Implementing a Microsoft SQL Server 2008 Database

1-31

MCT USE ONLY. STUDENT USE PROHIBITED

The number of columns in the table and, for each column, the data type and length, if it is required. Which columns will accept null values. Whether and where to use constraints or defaults and rules. The types of indexes that will be needed, where required, and which columns are primary keys and which are foreign keys.

The most efficient way to create a database is to define everything that you need at the same time. This includes the tables you require, the type of data that goes into each table, and the users that can access those tables. You should not create any user objects, such as tables, views, stored procedures, or triggers, in the master database. The master database contains system-level information used by the instance of SQL Server, such as logon information and configuration option settings.

Best Practices related to database snapshots


Supplement or modify the following best practices for your own work situations: Taking regular backups and testing your restore plan are essential to protect a database. If you must restore the source database to the point in time at which you created a database snapshot, implement a backup policy that enables you to do that. Using database snapshots for reverting a database is not a substitute for your backup and restore strategy. Reverting does not work on an offline or corrupted database.

Best practices related to compression


Supplement or modify the following best practices for your own work situations: If CPU is the dominant cost in your workload but you want to save some disk space, you may want to enable PAGE compression on partitions that are not accessed frequently while not compressing the current partition(s) that are accessed and manipulated more frequently. If I/O cost is dominant for your workload, or you need to reduce disk space costs, compressing all data using PAGE compression may be the best choice.

MCT USE ONLY. STUDENT USE PROHIBITED

Implementing a Microsoft SQL Server 2008 Database

2-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 2
Creating Data Types and Tables
Contents:
Lesson 1: Creating Data Types Lesson 2: Creating Tables Lesson 3: Creating Partitioned Tables Lab: Creating Data Types and Tables 2-3 2-8 2-17 2-23

2-2

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

Objects that contain data have an associated data type that defines the kind of data the object can contain, and all data stored in Microsoft SQL Server 2008 must be compatible with base data types. Tables are database objects that contain all the data in a database. In tables, data is organized in a row-and-column format similar to a spreadsheet. Finally, partitioning makes large tables more manageable, because partitioning enables you to manage and access subsets of data quickly and efficiently, while maintaining data integrity. In this module you will be introduced to the concepts involved in creating data types and tables. You will also learn about partitioned tables.

Implementing a Microsoft SQL Server 2008 Database

2-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Creating Data Types

Many objects in Microsoft SQL Server 2008 contain data and can be assigned data types to better define the object attributes. In this lesson you will learn about system-supplied data types, learn how to use system-supplied data types, and discuss alias data types.

2-4

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

What Are System-Supplied Data Types?

Key Points
As was mentioned earlier, objects that contain data have an associated data type that defines the kind of data; for example, character, integer, or binary, the object can contain. Columns in tables and views, parameters in stored procedures, variables, TSQL functions that return data values and stored procedures that have a return code all have data types. All data stored in Microsoft SQL Server must be compatible with one of the base data types shown in the table.

Implementing a Microsoft SQL Server 2008 Database

2-5

MCT USE ONLY. STUDENT USE PROHIBITED

Using System-Supplied Data Types

Key Points
SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server. Data types in SQL Server are organized into several categories. Based on their storage characteristics, some data types are designated as belonging to the large value data type group or the large object data type group. All Unicode data uses the character set defined by the Unicode standard. Unicode collations used for Unicode columns are based on attributes such as case sensitivity, accent sensitivity, Kana sensitivity, width sensitivity and binary.

2-6

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Alias Data Types?

Key Points
Alias types are based on the system data types in SQL Server. Alias types can be used when several tables must store the same type of data in a column and you have to make sure that these columns have identical data type, length, and nullability. They can also be used in functions and stored procedures. If an alias type is created in the model database, it exists in all new userdefined databases. However, if the data type is created in a user-defined database, the data type exists only in that user-defined database.

Implementing a Microsoft SQL Server 2008 Database

2-7

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Data Types

Question: How is a user-defined data type implemented? Question: How can you create an alias data type based on a system-supplied data type?

2-8

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Creating Tables

Tables are database objects that contain all the data in a database. A table definition is a collection of columns. In tables, data is organized in a row-and-column format similar to a spreadsheet. In this lesson you will learn how SQL Server organizes data in rows, how SQL Server organizes large data values, the concept of table types, considerations for creating table types, and how to generate Transact-SQL scripts.

Implementing a Microsoft SQL Server 2008 Database

2-9

MCT USE ONLY. STUDENT USE PROHIBITED

How SQL Server Organizes Data in Rows

Key Points
A data row consists of a row header and a data portion. It is important to understand the elements of the data portion of each row to accurately estimate the size of a table. The data portion of a row can contain fixed-length data, a null block, a variable block, and variable-length data. Each row represents an individual occurrence of the object modeled by the table. For example, a computer parts table would have one row for each computer part carried by the company.

2-10

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

How SQL Server Organizes Large Data Values

Key Points
With large-value data types you can work with SQL Server in a way that was not possible using the text, ntext and image data types from earlier versions of SQL Server. varchar(max), nvarchar(max), and varbinary(max), and XML data types are collectively called large-value data types. Large-value data types can define variables that can store large amounts of data, up to 2^31 bytes of character, binary, and Unicode data. Large-value data are similar in behavior to their smaller counterparts, varchar, nvarchar and varbinary. This similarity enables SQL Server to store and retrieve large character, Unicode, and binary data more efficiently.

Implementing a Microsoft SQL Server 2008 Database

2-11

MCT USE ONLY. STUDENT USE PROHIBITED

Types of Tables

Key Points
Besides the standard role of basic user-defined tables, SQL Server provides the following types of tables that serve special purposes in a database: Partitioned tables: support all the properties and features associated with designing and querying standard tables, including constraints, defaults, identity and timestamp values, triggers, and indexes. Local temporary tables are visible only to the current connection and are deleted after a user disconnects from that instance of SQL Server. Global temporary tables are visible to any user after they are created and are deleted when all users referencing the table disconnect from that instance of SQL Server.

2-12

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

System tables: SQL Server stores the data that defines the configuration of the server and all its tables in a special set of tables known as system tables. You cannot directly work with the data in these tables.

Question: What properties do partitioned tables support?

Implementing a Microsoft SQL Server 2008 Database

2-13

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Creating Tables

Key Points
The most efficient way to create a table is to define everything needed in the table at the same time. This includes its data restrictions and additional components. Database collation for char, varchar, text, nchar, nvarchar, and ntext data can be overridden by specifying a collation for a particular column of the table and using either the COLLATE clause of CREATE TABLE and ALTER TABLE, SQL Server Management Studio, or the column.collation property. The nullability of a column determines whether that column can allow a null value (NULL) as the data in that column. Computed columns can be used in select lists, WHERE clauses, ORDER BY clauses, or any other locations in which regular expressions can be used, with some exceptions. Identity Property columns identify a row uniquely.

2-14

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Timestamp columns are generally used as a mechanism for version-stamping table rows. Uniqueidentifier columns are 16-byte Globally Unique Identifiers (GUID). Replication uses uniqueidentifier columns to guarantee that rows are uniquely identified across multiple copies of a table.

Implementing a Microsoft SQL Server 2008 Database

2-15

MCT USE ONLY. STUDENT USE PROHIBITED

Generating Transact-SQL Scripts

Key Points
You can create Transact-SQL scripts using the Generate SQL Server Scripts Wizard, or using Object Explorer. Use Object Explorer to quickly create scripts of an entire database, or a single database object using the default options. The Generate Scripts Wizard flows through the process of creating TransactSQL scripts, and provides a variety of objects to be scripted at once. To create combined scripts, save the first script to a Query Editor window and the second to the clipboard so it can be pasted into the window after the first script.

2-16

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Tables

Question: What options of a table can be changed after the table has been created?

Implementing a Microsoft SQL Server 2008 Database

2-17

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Creating Partitioned Tables

By using partitioning, the time taken to load data from an Online Transaction Processing (OLTP) system to an Online Analytical Processing (OLAP) system is significantly reduced. In this lesson you will be introduced to the concepts of partitioned tables, partition functions, partition schemes, and you will discuss what operations can be performed on partitioned data.

2-18

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Partitioned Tables?

Key Points
The data of partitioned tables and indexes is divided into units that can be spread across more than one filegroup in a database. The data is partitioned horizontally, so that groups of rows are mapped into individual partitions. Partitioned tables and indexes support all the properties and features associated with designing and querying standard tables and indexes, including constraints, defaults, identity and timestamp values, and triggers. Partitioning a table or index might improve query performance if the partitions are designed correctly, based on the types of queries frequently run and on hardware configuration.

Implementing a Microsoft SQL Server 2008 Database

2-19

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Partition Functions?

Key Points
A partition function specifies how the table or index is partitioned. The scope of a partition function is limited to the database that it is created in. Within the database, partition functions reside in a separate namespace from the other functions. Any rows whose partitioning column has null values are placed in the left-most partition, unless NULL is specified as a boundary value and RIGHT is indicated. boundary_value is a constant expression that can reference variables. This includes user-defined type variables, or functions and user-defined functions. It cannot reference Transact-SQL expressions. To make sure the partition function definition behaves as expected for all session languages, use constants that are interpreted the same way for all language settings, such as the yyyymmdd format.

2-20

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Partition Scheme?

Key Points
A partition scheme is a scheme in the current database that maps the partitions of a partitioned table or index to filegroups. A partition function must first be created in a CREATE PARTITION FUNCTION statement before creating a partition scheme. Partitions created by the partition function are mapped to the filegroups specified in the partition scheme. In a partition scheme, only one filegroup can be designated NEXT USED. A filegroup that is not empty can be specified. This means the filegroup will accept a new partition that is created by using an ALTER PARTITION FUNCTION statement.

Question: What is the relationship between a partitioned table, a partition function, and a partition scheme?

Implementing a Microsoft SQL Server 2008 Database

2-21

MCT USE ONLY. STUDENT USE PROHIBITED

What Operations Can Be Performed on Partitioned Data?

Key Points
When you add a partition, you do so by "splitting" an existing partition into two partitions and redefining the boundaries of the new partitions. When you drop a partition, you do so by "merging" the boundaries of two partitions into one. Partition-aligned indexed views can be switched together with the partitioned tables the views are defined against. Maintenance operations on partitions or subsets of data are performed more efficiently because these operations target only the data that is required, instead of the entire table. ALTER PARTITION FUNCTION can only be used for splitting one partition into two, or for merging two partitions into one.

2-22

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating a Partitioned Table

Question: What is the scope of a partition function? Question: How are partitions mapped?

Implementing a Microsoft SQL Server 2008 Database

2-23

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating Data Types and Tables

Exercise 1: Creating Data Types


Scenario
The sales manager at Adventure Works has requested that the companys database be modified to include data about goods that have been returned and sales that have been refunded. In addition, the senior database developer has designed some new data types for the returns and refunds data and has assigned you the task of creating them in the database. The main tasks for this exercise are as follows: 1. 2. Create a data type based on the nvarchar system-supplied data type. Create a data type based on the decimal system-supplied data type.

2-24

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Task 1: Create a data type based on the nvarchar system-supplied data


type
Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. Create a new data type named ShortDescription in the dbo schema. This data type should be based on the nvarchar system-supplied data type and should have a maximum length of 100 characters.

Task 2: Create a data type based on the decimal system-supplied data


type
Create a new data type named CashValue in the dbo schema. This data type should be based on the decimal system-supplied data type and should have a precision of 8 and a scale of 2.
Results: After this exercise, you should have successfully created a new data type based on the nvarchar system-supplied data type. You should have also successfully created a new data type based on the decimal system-supplied data type.

Implementing a Microsoft SQL Server 2008 Database

2-25

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Using New Date and Time Data Types


Scenario
The sales manager at Adventure Works has requested that the company's database next be modified to show calendar data using a new format. The senior database developer at Adventure Works has designed data type conversions for the company's calendar data and has assigned you the task of reporting back with what the different output types will look like. You will then convert sample data into the datetime format as a test of the new data type conversions. The main tasks for this exercise are as follows: 1. 2. Obtain date and time formatting using T-SQL. Convert sample data into new data type formats using T-SQL.

Task 1: Obtain date and time formatting using T-SQL


Write a query using CAST and CONVERT to convert the time period of 200705-08 12:35:29 to multiple data formats. Be sure to include the conversion to time, date, smalldatetime, datetime, datetime2, and datetimeoffset data types in your query.

Task 2: Convert sample data into new data type formats using T-SQL
Use '2006-04-04T15:50:59.997' as your datetime sample. Use CAST and CONVERT to convert sample data into the date format and also into the time format.
Results: After this exercise, you should have successfully obtained date and time formatting using T-SQL and then converted sample data into the date and time formats using T-SQL.

2-26

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating Tables


Scenario
The sales department at Adventure Works needs two new tables to hold new data on returned goods and refunds paid. The senior database developer has given you the task of creating these two tables based on the specifications provided. The main tasks for this exercise are as follows: 1. 2. Create a table named ReturnedGoods. Create a table named Refunds.

Task 1: Create a table named ReturnedGoods


The table must be created in the Sales schema. The table must contain the following columns: ReturnID. An int identity column that cannot contain NULL values. ProductID. An int column that cannot contain NULL values. CustomerID. An int column that cannot contain NULL values. ReturnDate. A datetime column that cannot contain NULL values. ReturnReason. A ShortDescription column that can contain NULL values.

Task 2: Create a table named Refunds


The table must be created in the Sales schema. The Refunds table should contain the following columns: RefundID. An int identity column that cannot contain NULL values. ReturnID. An int column that cannot contain NULL values. Amount. A CashValue column that cannot contain NULL values.

Results: After this exercise, you should have created a table named ReturnedGoods, created a table named Refunds, and followed all provided specifications.

Implementing a Microsoft SQL Server 2008 Database

2-27

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 4: Creating Partitioned Tables


Scenario
The Director of IT at Adventure Works has received several complaints about database performance, specifically that the working with the Returns table is very slow. As part of the solution to this problem, the senior database developer has tasked you with the creation of a partitioned table that will be used to archive returns data at a later date. The main tasks for this exercise are as follows: 1. 2. 3. Prepare the database for partitioning. Create a partitioned table named ReturnsArchive. Review the partitioning implementation.

Task 1: Prepare the database for partitioning


Open the query located at E:\MOD02\Labfiles\Scripts\partition_prep.sql. Execute the query.

Task 2: Create a partitioned table named ReturnsArchive


Create a partitioned table that stores data in four partitions using the Test1FG, Test2FG, Test3FG, and Test4FG filegroups. The table must contain the following columns: ReturnID. An int identity column that cannot contain NULL values. ProductID. An int column that cannot contain NULL values. CustomerID. An int column that cannot contain NULL values. ReturnDate. A datetime column that cannot contain NULL values. ReturnReason. A ShortDescription column that can contain NULL values.

2-28

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Review the partitioning implementation


Review the Storage settings in the AdventureWorksDW2008 table properties. Note the new partitioning information under Compression, Filegroups, and Partitioning.
Results: After this exercise, you should have successfully prepared the database for partitioning, created a partitioned table named ReturnsArchive according to the specifications provided, and then reviewed the partitioning changes.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Implementing a Microsoft SQL Server 2008 Database

2-29

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. What are the two types of temporary tables and how do they differ from each other? How can you decide whether to implement partitioning? What must be defined when creating a partition scheme?

Best Practices related to creating and modifying tables


Supplement or modify the following best practices for your own work situations: Table and column names must follow the rules for identifiers; they must be unique within a specific table, but you can use the same column name in different tables in the same database. The name or schema of a table can be changed but, when you do this, you must be sure to also change the name of the table in any triggers, stored procedures, Transact-SQL scripts, or other programming code that uses the old name or schema of the table.

2-30

Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Best Practices related to partitioning


Supplement or modify the following best practices for your own work situations: A table is appropriate for partitioning if both of the following are true: The table contains, or is expected to contain, lots of data that are used in different ways. Queries or updates against the table are not performing as intended, or maintenance costs exceed predefined maintenance periods.

If you frequently run queries that involve an equi-join between two or more partitioned tables, their partitioning columns should be the same as the columns on which the tables are joined. Stripe the data files of your partitions across more than one disk by setting up a RAID. In this way, although SQL Server still sorts data by partition, it can access all the drives of each partition at the same time. This configuration can be designed regardless of whether all partitions are in one filegroup or multiple filegroups.

Implementing a Microsoft SQL Server 2008 Database

3-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 3
Creating and Tuning Indexes
Contents:
Lesson 1: Planning Indexes Lesson 2: Creating Indexes Lesson 3: Optimizing Indexes Lab: Creating and Optimizing Indexes 3-3 3-8 3-21 3-29

3-2

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

An index is a collection of pages associated with a table used to improve the performance of queries or enforce uniqueness. This module provides an overview of planning, creating, and optimizing indexes. It explains the differences between heaps, clustered indexes, and non-clustered indexes and when you would use each one. It describes how to create the different types of indexes, and how to configure and maintain them to optimize performance benefits.

Implementing a Microsoft SQL Server 2008 Database

3-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1:

Planning Indexes

Microsoft SQL Server 2008 can use indexes to point to the location of a row on a data page instead of having to look through all the data pages of a table. Planning useful indexes is one of the most important aspects of improving query performance. It requires an understanding of both index structure and how the data is used. Understanding the basics of how data is stored and accessed is the first step in understanding how indexes work, why you would want to use them, and the reasons you would want to use each of the different indexing options provided by SQL Server 2008. In this lesson, you will learn the three fundamental indexing options offered by SQL Server: heaps, clustered indexes, and non-clustered indexes. You will learn the benefits and disadvantages of each option and be able to identify when to use each option.

3-4

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

How SQL Server Accesses Data

Key Points
SQL Server first determines whether an index exists. Then the query optimizerthe component responsible for generating the optimal execution plan for a query determines whether scanning a table or using the index is more efficient for accessing data. SQL Server accesses data in one of two ways: By scanning all the data pages in a table, which is called a table scan. By using indexes.

Question: When might a table scan be more efficient than using the index?

Implementing a Microsoft SQL Server 2008 Database

3-5

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Heap?

Key Points
SQL Server uses Index Allocation Map (IAM) pages to maintain heaps. IAM pages: Contain information about where SQL Server stores the extents of a heap. The sys.partitions system table stores a pointer to the first IAM page associated with a heap. This will be a record with index_id = 0. Enable navigation through the heap to find available space when new rows are inserted into the table. Associate data pages with the table. The data pages and the rows within them are not in any specific order and are not linked. The only logical association between data pages is that which is recorded in the IAM pages.

Question: What is the order of data pages stored in a heap?

3-6

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Clustered Index?

Key Points
A clustered index sorts and stores the data rows of the table in order based on the clustered index key. The clustered index is implemented as a B-tree (balanced). Because a clustered index determines the order in which table rows are actually stored, each table can have only one clustered indexthe tables rows cannot be stored in more than one order.

Implementing a Microsoft SQL Server 2008 Database

3-7

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Non-clustered Index?

Key Points
Non-clustered indexes have the same B-tree structure as clustered indexes except that the data rows of the underlying table are not sorted and stored in the order based on their non-clustered keys. In the non-clustered index, the data and the index are stored separately, and the leaf level of the index consists of index pages instead of data pages. A table can have up to 249 non-clustered indexes. Non-clustered indexes can be defined on a table regardless of whether the table uses a clustered index or a heap, and can include extra columns without violating the 900 byte limit. Question: Under what circumstances would you want to use clustered or nonclustered indexes?

3-8

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2:

Creating Indexes

After you have decided what you want to index and whether to use a clustered or non-clustered index, you must create the index. Many options are available to you when you create an index, and these can have a major impact on the performance and maintainability of the index. In this lesson, you will learn how to create indexes and how to use some of the key index configuration options to improve the usefulness, performance, and maintainability of the indexes you create.

Implementing a Microsoft SQL Server 2008 Database

3-9

MCT USE ONLY. STUDENT USE PROHIBITED

Overview of Creating Indexes

Key Points
You can create an index by using Object Explorer in SQL Server Management Studio or with the CREATE INDEX Transact-SQL statement.

3-10

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Unique Indexes?

Key Points
A unique index is an index that ensures that all data in an indexed column is explicitly unique and does not contain duplicate values. When you create an index on a table that already contains data, the database engine ensures that there are no existing duplicate values. Question: What is the difference between a unique index and a clustered index?

Implementing a Microsoft SQL Server 2008 Database

3-11

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Creating Indexes with Multiple Columns

Key Points
A composite index specifies more than one column as the key value. You can enhance query performance by using composite indexes, especially when users regularly search for information in more than one way. However, wide keys increase the storage requirements of an index. Composite indexes have the following requirements and limitations: Up to 16 columns can be combined to form a single composite index. The sum of the lengths of the columns that make up the composite index cannot exceed 900 bytes, except included columns. The WHERE clause of a query must reference the first column of the composite index for the query optimizer to use the composite index. Covering indexes are not subject to this restriction.

3-12

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

The columns in a composite index must all be from the same table, except when an index is created on a view, in which case, they must all be from the same view. A composite index on (column1, column2) is not the same as an index on (column2, column1)each has a distinct column order.

Implementing a Microsoft SQL Server 2008 Database

3-13

MCT USE ONLY. STUDENT USE PROHIBITED

When to Create Indexes on Computed Columns

Key Points
You can create indexes on computed columns when: The computed column expression is deterministic and precise. The ANSI_NULLS connection-level option is ON when the CREATE TABLE statement is executed. The connection on which the index is createdand all connections attempting INSERT, UPDATE, or DELETE statements that will change values in the indexhave six SET options set to ON and one option set to OFF. The following options must be set to ON: ANSI_NULLS ANSI_PADDING ANSI_WARNINGS

3-14

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

CONCAT_NULL_YIELDS_NULL QUOTED_IDENTIFIER ARITHABORT

The NUMERIC_ROUNDABORT option must be set to OFF.

Question: What is ARITHABORT and why must it be set to ON?

Implementing a Microsoft SQL Server 2008 Database

3-15

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Partitioned Indexes?

Key Points
In SQL Server 2008, just as you can divide tables into partitions based on value ranges, you can also partition indexes. You partition indexes for the same reason that you partition tablesto improve performance and to make large indexes more manageableby enabling you to focus management tasks on individual partitions rather than on the entire index. Question: How might an application benefit from a partitioned index that is not aligned to the table?

3-16

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Options for Incorporating Free Space in Indexes

Key Points
The availability of free space in an index page can have a significant effect on the performance of index update operations. If an index record must be inserted and there is no free space, a new index page must be created and the contents of the old page split across the two pages. This can affect performance if it happens too frequently. The FILLFACTOR option allows you to allocate a percentage (1 to 100) of free space on the leaf-level index pages to reduce page splitting. This percentage determines how much the leaf-level pages should be filled. For example, a fill factor of 65 percent fills the leaf-level pages 65 percent, leaving 35 percent of the page space free for new rows.

Implementing a Microsoft SQL Server 2008 Database

3-17

MCT USE ONLY. STUDENT USE PROHIBITED

The PAD_INDEX option enables you to specify whether or not the fill factor applied to the leaf pages also applies to the non-leaf pages. You can use the PAD_INDEX option only when FILLFACTOR is specified, because the PAD_INDEX percentage value is determined by the percentage value specified for FILLFACTOR.

Question: When would you use a high FILLFACTOR setting?

3-18

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Methods for Obtaining Index Information

Key Points
You might require information about existing indexes before you create, modify, or remove an index. SQL Server 2008 provides many ways to obtain information about indexes: SQL Server Management Studio System stored procedures: the sp_helpindex stored procedure returns details of the indexes created on a specified table. Catalog views provide the following information about indexes: sys.indexes: Index type, filegroup or partition scheme ID, and the current setting of index options that are stored in metadata. sys.index_columns: Column ID, position within the index, type (key or nonkey), and sort order (ASC or DESC).

Implementing a Microsoft SQL Server 2008 Database

3-19

MCT USE ONLY. STUDENT USE PROHIBITED

sys.stats: Statistics associated with an index, including statistic name and whether it was created automatically or by a user. sys.stats_columns: Column ID associated with the statistic.

System functions provide the following information about indexes: sys.dm_db_index_physical_stats: Index size and fragmentation statistics. sys.dm_db_index_operational_stats: Current index and table I/O statistics. sys.dm_db_index_usage_stats: Index usage statistics by query type. INDEXKEY_PROPERTY: Index column position within the index and column sort order (ASC or DESC). INDEXPROPERTY: Index type, number of levels, and current setting of index options that are stored in metadata. INDEX_COL: Name of the key column of the specified index.

3-20

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Indexes

Question: What permissions are required to create an index?

Implementing a Microsoft SQL Server 2008 Database

3-21

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3:

Optimizing Indexes

The overall performance of your database is determined largely by the effectiveness of your indexes. Therefore, it is important to make sure that your indexes are designed and implemented in a way that best supports your applications. Once the indexes are implemented, you must maintain the indexes to ensure their continued optimal performance. As data is added, changed, and deleted in the database, indexes become fragmented. Depending on your business environment and the purpose of the database application, fragmentation can be either good or bad for performance, but it needs to be managed appropriately to suit your needs. This lesson looks at the main tools provided in SQL Server 2008 that help you to optimize your index design and maintain those indexes to control fragmentation at an appropriate level.

3-22

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

What Is the Database Engine Tuning Advisor?

Key Points
The Database Engine Tuning Advisor analyzes the performance effects of workloads run against one or more databases. A workload is a set of Transact-SQL statements that executes against databases that you want to tune. The workload source can be a file containing Transact-SQL statements, a trace file generated by SQL Profiler, or a table of trace information, again generated by SQL Profiler. After analyzing the effects of a workload on your databases, the Database Engine Tuning Advisor provides its recommendations. These recommendations include suggested changes to the database such as new indexes, indexes that should be dropped, and depending on the tuning options you set, partitioning recommendations. Recommendations are provided as a set of Transact-SQL statements that would effect the suggested changes. You can view the TransactSQL and save it for later review and application, or you can choose to implement the recommended changes immediately.

Implementing a Microsoft SQL Server 2008 Database

3-23

MCT USE ONLY. STUDENT USE PROHIBITED

Question: What databases in your organization could benefit from tuning and how would you collect the workload for analysis?

3-24

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using the Database Engine Tuning Advisor

Question: If you want to compare recommendations and implement them later, what can you do?

Implementing a Microsoft SQL Server 2008 Database

3-25

MCT USE ONLY. STUDENT USE PROHIBITED

Index Fragmentation

Key Points
Index fragmentation is the inefficient use of pages within an index. Fragmentation occurs over time as data is modified. For example, when rows of data are added to or deleted from a table, or when values in the indexed columns are changed, SQL Server adjusts the index pages to accommodate the changes and to maintain the storage of the indexed data. The adjustment of the index pages is known as a page split. The splitting process increases the size of a table and the time that is needed to process queries. You can use SQL Server Management Studio or the sys.dm_db_index_physical_stats dynamic management function to determine the extent to which your indexes are fragmented. Question: Why does fragmentation affect performance?

3-26

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Options for Defragmenting Indexes

Key Points
There are two options for defragmenting an index: reorganizing and rebuilding. In general, you should reorganize an index if there is less than 30 percent fragmentation, and rebuild the index if the fragmentation is greater than 30 percent. Reorganizing an index defragments the leaf level of clustered and nonclustered indexes on tables by physically reordering the leaf-level pages to match the logical order (left to right) of the leaf nodes. Rebuilding an index drops the index and creates a new one. By rebuilding, fragmentation is removed, disk space is reclaimed by compacting the pages using the specified or existing fill factor setting, and the index rows are reordered in contiguous pages (allocating new pages as needed). This can improve disk performance by reducing the number of page reads required to obtain the requested data.

Implementing a Microsoft SQL Server 2008 Database

3-27

MCT USE ONLY. STUDENT USE PROHIBITED

Question: What steps would you take to decide when to reorganize or rebuild an index?

3-28

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Defragmenting Indexes

Question: Which option for defragmenting requires the index to be offline?

Implementing a Microsoft SQL Server 2008 Database

3-29

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating and Optimizing Indexes

Exercise 1: Creating Indexes


Scenario
You must use SQL Server Management Studio to create a SQL Server Scripts project for the modifications in the E:\MOD03\Labfiles\Starter folder. You must implement a new unique, non-clustered index named Ix_Product_Supply_Chain on the Production.Product table to support queries that include stock-level management information. Use the following settings: Key columns: ProductNumber, Color, ReorderPoint, SafetyStockLevel Included columns: DaysToManufacture Locking: Allow row locks but not page locks. Fill factor: Set the fill factor to 90 percent on both leaf and non-leaf nodes.

3-30

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

This exercises main tasks are: 1. 2. 3. Start the 6432A-NY-SQL-01 virtual machine and log on as Student. Create a SQL Server Scripts project. Create the Ix_Product_Supply_Chain index.

Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as


Student
Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project


1. 2. 3. Open SQL Server Management Studio, and connect to the server you want to manage (NY-SQL-01). On the File menu, click New, and then click Project. Select the SQL Server Scripts template and enter the name and location for the project (E:/MOD03/Labfiles/Starter).

Task 3: Create the Ix_Product_Supply_Chain index


1. In the query window, enter the Transact-SQL code to create the Ix_Product_Supply_Chain index on Production.Product, columns ProductNumber, Color, ReorderPoint, and SafetyStockLevel. Include DaysToManufacture. Make sure to allow row locks, do not allow page locks, use a FILLFACTOR of 90, and pad the index. On the toolbar, click Execute.
Results: After this exercise, you should have successfully created a SQL Server Scripts project and created the Ix_Product_Supply_Chain index.

2.

Implementing a Microsoft SQL Server 2008 Database

3-31

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Optimizing Indexes


Scenario
You have been asked to add 1000 new sample products to the Adventure Works 2008 database. A script has been provided to add these records. After you add the records, you need to check the indexes for fragmentation and reorganize or rebuild as needed. This exercises main tasks are: 1. 2. 3. Add the sample products to the database. Reorganize AK_Product_ProductNumber. Rebuild AK_Product_Name.

Task 1: Add the sample products to the database


In SQL Server Management Studio, open aw2008sampleproductadd.sql from the E:\Mod03\Labfiles\Starter\ folder, and then execute it. o You may ignore any errors about duplicate keys.

Task 2: Reorganize AK_Product_ProductNumber


Use SQL Server Management Studio to reorganize the AK_Product_ProductNumber index which is associated to the Production.Product table of the AdventureWorks2008 database.

3-32

Creating and Tuning Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Rebuild AK_Product_Name


Use SQL Server Management Studio to reorganize the AK_Product_Name index which is associated to the Production.Product table of the AdventureWorks2008 database.
Results: After this exercise, you should have successfully optimized the Production.Product table indexes using both reorganize and rebuild.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Implementing a Microsoft SQL Server 2008 Database

3-33

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. What is the difference between a clustered index and a non-clustered index? Why does fragmentation occur in an index? What is the difference between rebuilding and reorganizing?

Best Practices and Troubleshooting


You should keep the length of the index key short for clustered indexes. Additionally, clustered indexes benefit from being created on unique or nonnull columns. Frequently, a long-running query is caused by indexing a column with few unique values, or by performing a join on such a column. This is a fundamental problem with the data and query, and generally cannot be resolved without identifying this situation. For example, a physical telephone directory sorted alphabetically on last name will not expedite locating a person if all people in the city are named Smith or Jones.

MCT USE ONLY. STUDENT USE PROHIBITED

Implementing a Microsoft SQL Server 2008 Database

4-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 4
Implementing Data Integrity by Using Constraints and Triggers
Contents:
Lesson 1: Data Integrity Overview Lesson 2: Implementing Constraints Lesson 3: Implementing Triggers Lab: Implementing Data Integrity by Using Constraints and Triggers 4-3 4-7 4-14 4-27

4-2

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

The quality of data in your database largely determines the usefulness and effectiveness of applications (and people) that rely on it, and it 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 2008 provides a variety of features that simplify the enforcement of data integrity. This module begins with an overview of the types of data integrity and summarizes the features provided by SQL Server 2008. It then discusses constraints and triggers in detail.

Implementing a Microsoft SQL Server 2008 Database

4-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1:

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 2008 to enforce data integrity.

4-4

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Types of Data Integrity

Key Points
Enforcing data integrity ensures the quality of the data in the database. The three types of data integrity that you must plan for are: Domain 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.

Implementing a Microsoft SQL Server 2008 Database

4-5

MCT USE ONLY. STUDENT USE PROHIBITED

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.

Question: When might more than one type of integrity apply to a scenario?

4-6

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Options for Enforcing Data Integrity

Key Points
The table summarizes the mechanisms provided by SQL Server 2008 for enforcing data integrity. Question: In your organization, which data integrity features are currently implemented in one of your databases?

Implementing a Microsoft SQL Server 2008 Database

4-7

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2:

Implementing Constraints

Constraints are the preferred method of enforcing data integrity. In this lesson, you 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.

4-8

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Constraints?

Key Points
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 the relationships between tables are maintained. Question: Under what circumstances would you want to use table instead of column constraints?

Implementing a Microsoft SQL Server 2008 Database

4-9

MCT USE ONLY. STUDENT USE PROHIBITED

Key Constraints

Key Points
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. 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. Question: Is a foreign key always unique? Why or why not?

4-10

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Other Constraints

Key Points
A DEFAULT constraint enters a value in a column when one is not specified in an INSERT statement. DEFAULT constraints enforce domain integrity. 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.

Implementing a Microsoft SQL Server 2008 Database

4-11

MCT USE ONLY. STUDENT USE PROHIBITED

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 employees tax number, are also unique. Question: How would you create constraints for different columns to ensure that a person's calculated age is never a negative value?

4-12

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Cascading Referential Integrity

Key Points
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. Question: Think of a scenario involving data for a human resources department. What types of cascading options would be appropriate for updating or deleting records?

Implementing a Microsoft SQL Server 2008 Database

4-13

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Constraint Checking

Key Points
You should specify meaningful names for constraints when you create them. If you do 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 recreate a table. You must build error-checking logic into your applications and transactions to test whether a constraint has been violated. You must specify whether you want SQL Server to enforce FOREIGN KEY and CHECK constraints for existing data when you add new constraints to an existing table. Any triggers on the table will not execute if a constraint is violated,

4-14

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Constraints

Question: Why are check restraints so important? Think of an example where a postal code is entered with a missing character and a customer does not receive a shipment. What are some other examples?

Implementing a Microsoft SQL Server 2008 Database

4-15

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3:

Implementing Triggers

Data manipulation language (DML) triggers are a powerful tool that enables 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.

4-16

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Triggers?

Key Points
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. 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.

Implementing a Microsoft SQL Server 2008 Database

4-17

MCT USE ONLY. STUDENT USE PROHIBITED

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. Triggers also allow the use of custom error messages for when constraint violations occur.

Question: Why would you choose to use a trigger with an application instead of or in addition to a foreign key constraint?

4-18

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

How an INSERT Trigger Works

Key Points
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. When an INSERT trigger fires, new rows are added to both the trigger table and the 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. Question: When would you use an insert trigger?

Implementing a Microsoft SQL Server 2008 Database

4-19

MCT USE ONLY. STUDENT USE PROHIBITED

How a DELETE Trigger Works

Key Points
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. When a DELETE trigger is fired, deleted rows from the affected table are placed in a special deleted table. The deleted table is a logical table that holds a copy of the rows that have been deleted. The deleted table enables you to reference logged data from the initiating DELETE statement. Question: What performance and archival considerations should you think about when planning how to handle deleted records?

4-20

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

How an UPDATE Trigger Works

Key Points
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. An UPDATE trigger can be thought of as two steps: 1. 2. The DELETE step that captures the before image of the data. The INSERT step that captures the after image of the data.

Question: When would you use an update trigger?

Implementing a Microsoft SQL Server 2008 Database

4-21

MCT USE ONLY. STUDENT USE PROHIBITED

How an INSTEAD OF Trigger Works

Key Points
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. This trigger executes instead of the original triggering action. INSTEAD OF triggers 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. Question: What databases in your organization could benefit from INSTEAD OF triggers and how?

4-22

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

How Nested Triggers Work

Key Points
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. Consider the following facts when you use nested triggers: By default, a nested triggers configuration option is on at the server level. 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.

Implementing a Microsoft SQL Server 2008 Database

4-23

MCT USE ONLY. STUDENT USE PROHIBITED

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.

Question: How might nested triggers work in an Employee database?

4-24

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Recursive Triggers

Key Points
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.

Implementing a Microsoft SQL Server 2008 Database

4-25

MCT USE ONLY. STUDENT USE PROHIBITED

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.

Question: Think of a database containing genealogy data. How might a recursive trigger be used when a relationship between two people is corrected (such as from child and parent, to grandchild and grandparent, with an intermediate generation inserted)?

4-26

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Triggers

Question: Where does the old record get temporarily stored when the trigger executes?

Implementing a Microsoft SQL Server 2008 Database

4-27

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Data Integrity by using Constraints and Triggers

Exercise 1: Creating Constraints


Scenario
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 the column must be unique. 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.

4-28

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

BusinessEntityID. An int column that can contain null values. This column is a foreign key to the BusinessEntityID column in the Person.BusinessEntity table. Create a SQL Server Scripts project for the modifications by using SQL Server Management Studio, and then store the project in the E:\MOD04\Labfiles\Starter folder.

This exercises main tasks are: 1. 2. 3. 4. Start the 6232A-NY-SQL-01 virtual machine and log on as Student. Create a SQL Server Scripts project. Create the JobCandidateHistory table and constraints. Test the JobCandidateHistory table and constraints.

Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as


Student
Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project


1. 2. 3. Open SQL Server Management Studio, and connect to the server you want to manage (NY-SQL-01). On the File menu, click New, and then click Project. Select the SQL Server Scripts template and enter the name and location for the project (E:/MOD04/Labfiles/Starter).

Task 3: Create the JobCandidateHistory table and constraints


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

2 3.

Implementing a Microsoft SQL Server 2008 Database

4-29

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: Test the JobCandidateHistory table and constraints


1. 2. 3. In SQL Server Management Studio, open the TestConstraints.sql script file in the E:\MOD04\Labfiles\Starter folder. Use the INSERT statement to test inserting invalid data. Use the INSERT statement to test inserting valid data.
Results: After this exercise, you should have successfully created a SQL Server Scripts project, created the HumanResources.JobCandidateHistory table, and tested the constraints.

4-30

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Disabling Constraints.


Scenario
Now that you have enabled constraints on your table, you need to test the effect on performance by running a test script against the table with constraints both enabled and disabled, and then compare the results. This exercises main tasks are: 1. 2. 3. Insert multiple rows into the JobCandidateHistory table. Disable constraints on the JobCandidateHistory table. Enable constraints on the JobCandidateHistory table.

Task 1: Insert multiple rows into the JobCandidateHistory table


In SQL Server Management Studio, open InsertTestData.sql from the E:\Mod04\Labfiles\Starter\ folder, and then execute it with statistics enabled. Examine the performance statistics.

Task 2: Disable constraints on the JobCandidateHistory table


1. 2. 3. 4. Add a new query to the project. 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 compare the performance statistics for the INSERT statements before and after the constraints were disabled.

Implementing a Microsoft SQL Server 2008 Database

4-31

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Enable constraints on the JobCandidateHistory table


1. 2. 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.
Results: After this exercise, you should have successfully compared performance results with constraints enabled and disabled.

4-32

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating Triggers.


Scenario
To further assist in maintaining historical information about job candidates for the Human Resources department, the senior database developer has asked you to create a new DELETE trigger named dJobCandidate on the HumanResources.JobCandidate table that copies the candidates information to the HumanResources.JobCandidateHistory table when somebody deletes a candidate. The JobCandidateId column 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. This exercises main tasks are: 1. 2. Create the dJobCandidate trigger. Test the dJobCandidate trigger.

Task 1: Create the dJobCandidate trigger


1. 2. Add a new query to the project. Change the query file name to Trigger.sql. In the query window, type the appropriate Transact-SQL to create the dJobCandidate trigger on the HumanResources.JobCandidate table in the AdventureWorks database. Execute the query, and then save the query file. Use Object Explorer to verify that the trigger has been created.

3. 4.

Implementing a Microsoft SQL Server 2008 Database

4-33

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Test the dJobCandidate trigger


1. 2. In SQL Server Management Studio, open the TestTrigger.sql query file from the E:\MOD04\Labfiles\Starter folder. Execute the query script, and look in the results pane to verify that the record deleted from the HumanResources.JobCandidate table has been inserted into the HumanResources.JobCandidateHistory table.
Results: After this exercise, you should have successfully created and tested the dJobCandidate trigger.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

4-34

Implementing Data Integrity by Using Constraints and Triggers

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. What is the difference between a constraint and a trigger? Why implement check constraints if an application is already checking the input data? What are some scenarios in which you may want to temporarily disable constraint checking?

Best Practices
In many business scenarios, it makes sense to mark records as deleted with a status column and use a trigger or stored procedure to update an audit trail table. The changes can then be audited, the data is not lost, and the IT staff can perform purges or archival of the deleted records. When you create a constraint on a column, if you do not specify a name for the constraint, SQL will generate a unique name for the constraint. However, you may want to be sure to always name constraints to adhere to your naming conventions.

Implementing a Microsoft SQL Server 2008 Database

5-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 5
Using XML
Contents:
Lesson 1: Using the XML Data Type Lesson 2: Retrieving XML by Using FOR XML Lesson 3: Shredding XML by Using OPENXML Lab 5A: Using XML Lesson 4: Introducing XQuery Lesson 5: Creating XML Indexes Lesson 6: Implementing XML Schemas Lab 5B: Using XML 5-3 5-12 5-21 5-27 5-37 5-43 5-48 5-54

5-2

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

Extensible Markup Language (XML) is a simple and flexible mechanism for describing structured and semi-structured data in a platform and software independent way. XML was originally developed as a derivation of SGML (ISO 8879) by the World Wide Web Consortium (W3C). It provides access to a rich family of technologies for processing such data files. Microsoft SQL Server 2008 provides many powerful tools and techniques for working with XML data.

Implementing a Microsoft SQL Server 2008 Database

5-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Using the XML Data Type

The xml data type lets you store XML documents and fragments in a SQL Server database. An XML fragment is an XML instance that is missing a single top-level element. You can create columns and variables of the xml type and store XML instances in them. It is important to understand the many methods and tools for managing XML data in order to build more powerful SQL Server databases.

5-4

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Is XML?

Key Points
An XML structure is self-describing and can be used across platforms and technologies. XML is a plain-text, Unicode-based meta-language: a language for defining markup languages. XML provides access to a wide range of technologies for manipulating, structuring, transforming and querying data. XML is not only useful for describing new document formats for the Web but is also suitable for describing structured data.

Implementing a Microsoft SQL Server 2008 Database

5-5

MCT USE ONLY. STUDENT USE PROHIBITED

XML is preferable to previous data formats because XML can easily represent both tabular data (such as relational data from a database or spreadsheets) and semi-structured data (such as a Web page or business document).

Question: In what areas of your organization do you currently use XML?

5-6

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Is the XML Data Type?

Key Points
The xml data type is a built-in data type in SQL Server. You can use the xml data type as a column type when creating a table; as a variable type, a parameter type, or a function-return type. The xml data type lets you store XML documents and fragments in a SQL Server database. You can optionally associate an XML schema collection with a column, a parameter, or a variable of the xml data type.

Implementing a Microsoft SQL Server 2008 Database

5-7

MCT USE ONLY. STUDENT USE PROHIBITED

The schemas in the collection are used to validate and type the XML instances. In this case, the XML is said to be typed.

Question: What aspects of your organizations data enterprise would benefit from the use of the xml data type?

5-8

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

The Query, Value, and Exist Methods

Key Points
SQL Server 2008 includes native XML functions that can be used against XML instances to extract or check data values. The query() method takes the XML Query (XQuery) expression that evaluates to a list of XML nodes and allows the user to extract fragments of an XML document. The value() method is useful for extracting scalar values from XML documents as a relational value. The exist() method allows the user to perform checks on XML documents to determine if the result of an XQuery expression is empty or nonempty. The xml data type methods query(), value(), and exist() return NULL if executed against a NULL XML instance.

Implementing a Microsoft SQL Server 2008 Database

5-9

MCT USE ONLY. STUDENT USE PROHIBITED

The Modify Method

Key Points
Data manipulation operations can be performed on an XML instance using the modify() method. Use this method to modify the content of an xml type variable or column. This method takes an XML DML statement to insert, update, or delete nodes from XML data.

5-10

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

The Nodes Method

Key Points
The nodes() method is useful when you want to shred an xml data type instance into relational data. The result of the nodes() method is a rowset that contains logical copies of the original XML instances. You can retrieve multiple values from the rowset. For example, you can apply the value() method to the rowset returned by nodes() and retrieve multiple values from the original XML instance.

Implementing a Microsoft SQL Server 2008 Database

5-11

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using the XML Data Type

Question: Is the XML column in this example typed or untyped XML?

5-12

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Retrieving XML by Using FOR XML

A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in sub queries. There are many modes and techniques for using the FOR XML clause that improve your ability to manage XML data.

Implementing a Microsoft SQL Server 2008 Database

5-13

MCT USE ONLY. STUDENT USE PROHIBITED

Introduction to the FOR XML Clause

Key Points
The FOR XML clause provides the ability to aggregate the relational rowset returned by the SELECT statement into XML. The RAW mode generates a single <row> element per row in the rowset that is returned by the SELECT statement. You can generate XML hierarchy by writing nested FOR XML queries. The AUTO mode generates nesting in the resulting XML by using heuristics based on the way the SELECT statement is specified. The EXPLICIT mode allows more control over the shape of the XML. You can mix attributes and elements at will in deciding the shape of the XML.

5-14

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

The PATH mode together with the nested FOR XML query capability provides the flexibility of the EXPLICIT mode in a simpler manner.

Question: In what ways do you see the FOR XML clause streamlining SQL Server application development?

Implementing a Microsoft SQL Server 2008 Database

5-15

MCT USE ONLY. STUDENT USE PROHIBITED

What Are RAW Mode Queries?

Key Points
The RAW mode generates a single <row> element per row in the rowset that is returned by the SELECT statement. You can generate the XML hierarchy by writing nested FOR XML queries. If the ELEMENTS directive is added to the FOR XML clause, each column value is mapped to a subelement of the <row> element.

5-16

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Are AUTO Mode Queries?

Key Points
AUTO mode determines the shape of returned XML based on the query. The AUTO mode gives you more control over the returned XML. You have minimal control over the shape of the XML generated. The nested FOR XML queries can be written to generate XML hierarchy beyond the XML shape that is generated by AUTO mode heuristics. Using the EXPLICIT mode and using the PATH mode provide more control and flexibility in deciding the shape of the XML from a query result.

Implementing a Microsoft SQL Server 2008 Database

5-17

MCT USE ONLY. STUDENT USE PROHIBITED

What Are EXPLICIT Mode Queries?

Key Points
The EXPLICIT mode query must be written in a specific way so that the additional information about the required XML, such as expected nesting in the XML, is explicitly specified as part of the query. The EXPLICIT mode requires more complex query syntax but gives you the greatest control over the resulting XML. The Tag column uniquely identifies the XML tag that will be used to represent each row in the results, and the Parent column is used to control the nesting of elements. The PATH mode, together with the nesting of FOR XML queries and the WITH XMLNAMESPACES clause, gives enough power to replace most of the EXPLICIT mode queries in a simpler way.

5-18

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Are PATH Mode Queries?

Key Points
In PATH mode, column names or column aliases are treated as XML Path Language (XPath) expressions. The PATH mode provides a simpler way to mix elements and attributes. PATH mode is a simpler way to introduce additional nesting for representing complex properties.

Implementing a Microsoft SQL Server 2008 Database

5-19

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Retrieving Nested XML

Key Points
Nested FOR XML queries give you more control in defining the shape of the resulting XML data. The xml data type and the TYPE directive in FOR XML queries enable the XML returned by the FOR XML queries to be additionally processed on the server.

5-20

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using FOR XML

Question: Which of these modes demonstrated here offer the most power and flexibility in querying the data for the resulting XML?

Implementing a Microsoft SQL Server 2008 Database

5-21

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Shredding XML by Using OPENXML

The process of converting XML data into a format that can be used by a relational database is called Shredding. One can either use the NODES method on an XML data type or, from a Document Object Model, use the OpenXML function. Shredding XML is an important technique for working with XML data.

5-22

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Overview of Shredding XML Data

Key Points
The process of converting XML data into a format that can be used by a relational database is called Shredding, or decomposition. OpenXML is retained in SQL 2008 and can be used for shredding. The NODES method is generally preferable because of its simplicity and performance.

Implementing a Microsoft SQL Server 2008 Database

5-23

MCT USE ONLY. STUDENT USE PROHIBITED

Stored Procedures for Managing In-Memory Node Trees

Key Points
In order to work with XML documents, you must use included stored procedures in order to load and prepare as well as unload the document. To write queries against an XML document by using OPENXML, you must first call sp_xml_preparedocument. This parses the XML document and returns a handle to the parsed document that is ready for consumption. sp_xml_preparedocument reads the XML text provided as input, parses the text by using the MSXML parser (Msxmlsql.dll), and provides the parsed document in a state ready for consumption. sp_xml_removedocument removes the internal representation of the XML document specified by the document handle and invalidates the document handle

5-24

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

OPENXML Syntax

Key Points
OPENXML provides a rowset over in-memory XML documents that are similar to a table or a view. OPENXML allows access to XML data as though it is a relational rowset. In order to use OPENXML on an XML document, sp_xml_preparedocument must be used to create an in-memory representation of the XML document. This stored procedure parses the XML document using the MSXML parser and returns a handle to the XML document that can be used with OPENXML. Parameters such as XML document handle, rowpattern, which is an XPath expression that maps nodes of XML data to rows, rowset schema, and mapping between the rowset columns and the XML nodes can be passed to OPENXML to obtain the rowset. ColPattern is an optional, general XPath pattern that describes how the XML nodes should be mapped to the columns.

Implementing a Microsoft SQL Server 2008 Database

5-25

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Working with XML Namespaces

Key Points
SQLCLR opens up a whole new world that can be used for decomposing XML data into tables or property promotion, and querying XML data using managed classes in the system.xml namespace.

5-26

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using OPENXML to Shred XML

Question: How is element-centric mapping different from attribute-only mapping?

Implementing a Microsoft SQL Server 2008 Database

5-27

MCT USE ONLY. STUDENT USE PROHIBITED

Lab 5A: Using XML

Exercise 1: Mapping Relational Data and XML


Scenario
Adventure Works currently generates order manifests by performing a query in the AdventureWorks database. The organization intends to deploy a new Pocket PC based application to its warehouse employees, which they will then use when picking items from the warehouse for an order delivery. The item-choosing application requires the order manifest to be downloaded as XML. You must modify the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML. Adventure Works is also creating a new ordering system for specific customers so that they can send orders as XML documents. This system is still in the initial testing phase. You must create the appropriate Transact-SQL required to store the XML order details in the existing database tables. You must also write Transact-SQL code for a delivery scheduling application that retrieves information from the XML data and modifies the information by using xml methods.

5-28

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

The senior database developer has provided you with the following requirements for the modifications: Two different FOR XML queries are required to produce two different XML formats. The first FOR XML query should produce attribute-centric XML, as shown in the following example:
<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item ProductID="776" OrderQty="1" /> <Item ProductID="777" OrderQty="3" /> <Item ProductID="778" OrderQty="1" /> <Item ProductID="771" OrderQty="1" /> <! -- remaining items go here. --> </SalesOrder>

The second FOR XML query should produce a mixture of element-centric and attribute-centric XML, as shown in the following example:
<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item> <ProductID>776</ProductID> <OrderQty>1</OrderQty> </Item> <Item> <ProductID>777</ProductID> <OrderQty>3</OrderQty> </Item> <Item> <ProductID>778</ProductID> <OrderQty>1</OrderQty> </Item> <Item> <!-- more items here --> </SalesOrder>

In the FOR XML queries, the SalesOrder attributes come from the Sales.SalesOrderHeader table. The Item attributes and elements come from the Sales.SalesOrderDetail table.

Implementing a Microsoft SQL Server 2008 Database

5-29

MCT USE ONLY. STUDENT USE PROHIBITED

Two OPENXML queries are required to shred the XML document into the appropriate tables. The first query will insert data into the Sales.SalesOrderHeader table and should use the following schema declaration:
Column name CustomerID OrderDate DueDate AccountNumber ContactID BillToAddressID ShipToAddressID ShipMethodID SubTotal TaxAmt Data type int datetime datetime nvarchar(15) int int int int money money

The second OPENXML query will insert data into the Sales.SalesOrderDetail table and should use the following schema declaration:
Column name OrderQty ProductID UnitPrice Data type Int Int Money

A set of five queries are required that use xml methods to retrieve and modify the delivery schedule information.
Note: XML is case sensitive, so attention needs to be placed on casing of the characters when completing these labs.

5-30

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 1: Create the FOR XML queries to return the order manifest
documents
Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd. Start the Server Management Studio and connect to the server. Open the project XML.ssmssln. Execute the FORXML.sql query. Modify the SELECT statement to include the FOR XML clause and return attribute-centric XML by using AUTO mode.
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, Item.ProductID, Item.OrderQty FROM Sales.SalesOrderHeader SalesOrder JOIN Sales.SalesOrderDetail Item ON SalesOrder.SalesOrderID = Item.SalesOrderID WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

Execute the modified code and examine the XML data. Modify the query statement.
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, (SELECT Item.ProductID, Item.OrderQty FROM Sales.SalesOrderDetail Item WHERE SalesOrder.SalesOrderID = Item.SalesOrderID FOR XML AUTO, ELEMENTS, TYPE) FROM Sales.SalesOrderHeader SalesOrder WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

Execute the modified code and examine the XML data.

Implementing a Microsoft SQL Server 2008 Database

5-31

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Use the OPENXML function to insert the XML data into the
tables
Open the OPENXML.sql query. Locate the comment Call stored procedure to create the memory tree, and then add a call to the sp_xml_preparedocument stored procedure.
EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc

Locate the comment Add OPENXML function for SalesOrderHeader table INSERT, and then add an OPENXML function to retrieve the relevant attributes from the SalesOrder node.
OPENXML(@docHandle, '/SalesOrder', 1) WITH ( CustomerID int, OrderDate datetime, DueDate datetime, AccountNumber nvarchar(15), SalesPersonID int, BillToAddressID int, ShipToAddressID int, ShipMethodID int, SubTotal money, TaxAmt money)

Locate the comment Add OPENXML function for SalesOrderDetail table INSERT, and then add an OPENXML function to retrieve the relevant subelements from the Item node.
OPENXML(@docHandle, '/SalesOrder/Item', 2) WITH ( OrderQty int, ProductID int, UnitPrice money)

5-32

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Locate the comment Call stored procedure to clean up memory tree, and then add a call to the sp_xml_removedocument stored procedure.
EXEC sp_xml_removedocument @docHandle

Execute the code and examine the results, and confirm that a new record was added to the SalesOrderHeader table and two records were added to the SalesOrderDetail table.
Results: After this exercise, you should have modified the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML.

Implementing a Microsoft SQL Server 2008 Database

5-33

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Storing XML Natively in the Database


Scenario
The Human Resources department has decided that it wants to keep a historical record of job candidates so that it can contact past unsuccessful candidates if new positions come up, and compare the information provided by candidates if they apply for different positions over time. After consulting with the Human Resources team, the senior database developer has decided a new table is required to store this historical information. The senior database developer has provided you with the Transact-SQL to create the HumanResources.JobCandidateHistory table. The senior database developer has asked you to: Create an XML schema collection named HumanResources.HistoricResumeSchemaCollection. The Human Resources department will supply the XML schema, which is a variant of the schema that the department currently uses for the resumes of active candidates. Apply the schema collection to the JobCandidateHistory.Resume column to make it typed xml data. Create a SQL Server Scripts project for the modifications by using SQL Server Management Studio, and then store the project in the E:\Mod05\Labfiles\Starter folder. A file named HistoricResumeSchema.xml containing the schema for the HistoricResumeSchemaCollection XML schema collection is provided in the E:\Mod05\Labfiles\Starter folder.

Task 1: Create a SQL Server Scripts project in SQL Server Management


Studio
Create a new project. Name: Job Candidate History Location: E:\Mod05\Labfiles\Solution

5-34

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create the HumanResources.JobCandidateHistory table


Create a table named HumanResources.JobCandidateHistory in the AdventureWorks2008 database.
USE AdventureWorks2008 GO CREATE TABLE HumanResources.JobCandidateHistory ( JobCandidateID int IDENTITY PRIMARY KEY, BusinessEntityID int NULL, Rating int NOT NULL Default (5), RejectedDate datetime NOT NULL, NationalIDNumber nvarchar (15) NOT NULL, ModifiedDate DateTime, Resume xml ) GO

Execute the code, and then verify that the HumanResources.JobCandidateHistory table is listed. Verify that the necessary columns have been successfully created.

Task 3: Create a new query file


Create a new query file. File name: XMLSchema.sql

Task 4: Create an XML schema collection named


HumanResources.HistoricResumeSchemaCollection
Add this item to the solution. File of type: XML Files Folder: E:\Mod05\Labfiles\Starter File name: HistoricResumeSchema.xml

Examine this file.

Implementing a Microsoft SQL Server 2008 Database

5-35

MCT USE ONLY. STUDENT USE PROHIBITED

Add this item to the solution. File of type: SQL Server files Folder: E:\Mod05\Labfiles\Starter File name: CreateXMLSchema.sql

Examine this file. Execute the code. Examine Messages box and verify that the script completed without any errors.

Task 5: Apply the schema collection to the


JobCandidateHistory.Resume column
Create a new query. File name: AlterCandiateTable.sql

Enter the following code to alter the JobCandidateHistory table:


ALTER TABLE HumanResources.JobCandidateHistory ALTER COLUMN Resume xml (HumanResources.HistoricResumeSchemaCollection) GO

Execute the code and examine Messages box and verify that the script completed without any errors. Confirm that the HumanResources.HistoricResumeSchemaCollection is associated with the Resume column.

Task 6: Test the HistoricResumeSchema XML schema


Open the TestXMLSchema.sql file. Below the comment This should fail, select the INSERT code. Execute the code and examine the error message in the Messages pane. Below the comment This should succeed, select the code. Execute the code and verify that the script completed without any errors.

5-36

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Create a new query. File name: SelectCandiates.sql

Enter the following code:


USE AdventureWorks2008 GO SELECT * FROM HumanResources.JobCandidateHistory GO

Execute the code and verify that the script completed without any errors. Examine the XML record to confirm that it is complete and accurate.

Task 7: Populate the HumanResources.JobCandidateHistory table with


additional sample data
Open the AddCandidate.sql file. Execute the code and verify that the script completed without any errors. Open the SelectCandidates.sql file. Execute the code and verify that the script completed without any errors. Examine the xml record to confirm that it is accurate.
Results: After this exercise, the student has created and applied an XML schema and stored XML natively in the database.

Implementing a Microsoft SQL Server 2008 Database

5-37

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 4

Introducing XQuery

XQuery is a declarative, typed, functional language designed from scratch by the XML Query Working Group specifically for the purpose of querying data stored in XML format. XQuery shares the same data model and the same XML Schemabased type system with other members of the XML standards family. XQuery is designed to work with XML documents that are untyped (no schema associated with the data), typed with XML schemas, or a combination of both.

5-38

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Is XQuery?

Key Points
XQuery is a language that can query structured or semi-structured XML data. XQuery is based on the existing XPath query language, with support added for better iteration, better sorting results, and the ability to construct the necessary XML. When queries are written in XQuery, they require less code as compared to queries written in XSL Transformations (XSLT). XQuery can be used as a strongly typed language when the XML data is typed. This can improve the performance of the query by avoiding implicit type casts and provide type assurances that can be used when performing query optimization.

Implementing a Microsoft SQL Server 2008 Database

5-39

MCT USE ONLY. STUDENT USE PROHIBITED

XQuery can be used as a weakly typed language for untyped data to provide high usability.

Question: Why do you think it is important to learn XPath query language?

5-40

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

XQuery Basics

Key Points
XQuery is a declarative, typed, functional language designed from scratch by the XML Query Working Group specifically for the purpose of querying data stored in XML format. XQuery is designed to work with XML documents that are untyped (no schema associated with the data), typed with XML schemas, or a combination of both. XQuery 1.0 is basically a superset of XPath 2.0. XQuery provides a way to specify static context items in the query prolog (such as namespace prefix bindings).

Implementing a Microsoft SQL Server 2008 Database

5-41

MCT USE ONLY. STUDENT USE PROHIBITED

XQuery Expressions

Key Points
XQuery expressions consist of XQuery primary expressions, path expressions, sequence expressions, arithmetic comparison and logical expressions, XQuery construction, FLWOR expression, conditional and quantified expressions, and various expressions on sequence types. An XQuery expression in SQL Server 2008 consists of two sections - a prolog and a body. A prolog can contain a namespace declaration subsection. Namespace declarations are used to define a mapping between prefix and namespace URI. The body of an XQuery expression contains query expressions that define the result of the query.

5-42

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using XQuery Expressions

Question: What does the XMLNAMESPACES function do?

Implementing a Microsoft SQL Server 2008 Database

5-43

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 5

Creating XML Indexes

XML indexes can be created on xml data type columns. They index all tags, values and paths over the XML instances in the column and benefit query performance. Since an XML index is somewhat different than a relational index, it is necessary to know their implementation before understanding how to use them for maximum effectiveness.

5-44

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Are XML Indexes?

Key Points
XML indexes can be created on xml data type columns. They index all tags, values and paths over the XML instances in the column and benefit query performance. SQL Server 2008 supports four different types of XML indexes. The query processor uses the primary XML index to execute every query except for the case where the entire document will have to be output. Although having the primary XML index is a vast improvement over creating it afresh during each query. The size of the node table is usually around three times that of the XML data type in the base table.

Implementing a Microsoft SQL Server 2008 Database

5-45

MCT USE ONLY. STUDENT USE PROHIBITED

What Are the Benefits of XML Indexes?

Key Points
Your application may benefit from an XML index if queries on XML columns are common in your workload. XML index maintenance cost during data modification must be considered. Your application may benefit from an XML index if your XML values are relatively large and the retrieved parts are relatively small. Building the XML index avoids parsing the whole data at run time and benefits index lookups for efficient query processing.

5-46

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Types of XML Indexes

Key Points
There are two types of XML indexes: Primary and Secondary. The primary XML index indexes all tags, values, and paths within the XML instances in an XML column. Secondary indexes are used to enhance search performance. The first index on the xml type column must be the primary XML index. The primary XML index is a B+tree and its usefulness is due to the way that the optimizer creates a plan for the entire query. The secondary XML indexes can only be created through scripts. The secondary XML indexes assist in certain types of XQuery processing. These are called the PATH, PROPERTY, and VALUE indexes.

Implementing a Microsoft SQL Server 2008 Database

5-47

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating XML Indexes

Question: In what scenarios do you think using a secondary index would be most useful?

5-48

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 6

Implementing XML Schemas

Microsoft SQL Server provides native storage for XML document instances. XML schemas let you define complex XML data types, which can be used to validate XML documents to ensure data integrity. The XML schema is defined in the XmlSchemaCollection object.

Implementing a Microsoft SQL Server 2008 Database

5-49

MCT USE ONLY. STUDENT USE PROHIBITED

What Are XML Schemas?

Key Points
An XML schema provides validation constraints. Whenever a typed xml instance is assigned to or modified, SQL Server validates the instance. The purpose of an XML Schema is to define the legal building blocks of an XML document. An XML schema provides data type information. Schemas provide information about the types of attributes and elements in the xml data type instance. The type information provides more precise operational semantics to the values contained in the instance than is possible with untyped xml.

5-50

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

XML Schema Validation

Key Points
A schema defines the permissible XML elements and attributes for a particular XML data structure, and is often used to ensure that XML documents contain all of the required data elements in the correct structure. You can validate XML data by enforcing compliance with one or several XSD schemas. If the XML does not match the schema then an error results, similar to a constraint violation.

Question: When would it be most useful to validate an XML schema?

Implementing a Microsoft SQL Server 2008 Database

5-51

MCT USE ONLY. STUDENT USE PROHIBITED

What Is an XML Schema Collection?

Key Points
The XML schema collection stores the imported XML schemas and is then used to validate XML instances and type the XML data as it is stored in the database. SQL Server provides native storage of XML data with the xml data type. You can optionally associate XSD schemas with an xml data type through an XML schema collection. To use an XML schema collection and the schemas it contains, you must first create the collection and the schemas by using the CREATE XML SCHEMA COLLECTION statement. After the schema collection is created, you can then create variables and columns of xml type and associate the schema collection with them.

5-52

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

What Is Typed and Untyped XML?

Key Points
You can optionally associate a collection of XML schemas with a variable, parameter, or column of XML type. In this case, the xml data type instance is called typed. If the XML schema is not associated, the XML instance is called untyped. If the XML data does not conform to the schema an error is generated.

Implementing a Microsoft SQL Server 2008 Database

5-53

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using Typed XML

Question: Can you think of any scenarios in your organization where you might use untyped XML data?

5-54

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Lab 5B: Using XML

Exercise 3: Using XQuery with XML Methods


Scenario
Adventure Works currently generates order manifests by performing a query in the AdventureWorks database. The organization intends to deploy a new Pocket PC based application to its warehouse employees, which they will then use when picking items from the warehouse for an order delivery. The item-choosing application requires the order manifest to be downloaded as XML. You must modify the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML. Adventure Works is also creating a new ordering system for specific customers so that they can send orders as XML documents. This system is still in the initial testing phase. You must create the appropriate Transact-SQL required to store the XML order details in the existing database tables.

Implementing a Microsoft SQL Server 2008 Database

5-55

MCT USE ONLY. STUDENT USE PROHIBITED

You must also write Transact-SQL code for a delivery scheduling application that retrieves information from the XML data and modifies the information by using xml methods. You need to use XQuery expressions to retrieve and modify delivery schedule data.

Task 1: Retrieve the resume elements


Create a new query. File name: xmlMethods.sql

Enter the following code to retrieve the resume elements:


USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT NationalIDNumber, Resume.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources.JobCandidateHistory GO

Execute the code and verify that the desired results are returned.

Task 2: Retrieve the address for a specified candidate


Below the SELECT statement, type the following Transact-SQL:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT Resume.value( '(/RES:Resume/RES:Address/RES:Addr.Street)[1]', 'nvarchar(100)') As ResumeAddress FROM HumanResources.JobCandidateHistory WHERE JobCandidateID = 2 GO

Execute the statements, and then verify that the desired results are returned.

5-56

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Update a candidate's address


Below the previous SELECT statement, type the following Transact-SQL:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") UPDATE HumanResources.JobCandidateHistory SET Resume.modify('replace value of (/RES:Resume/RES:Address/RES:Addr.Street)[1] with "7194 Fourth St. Rockhampton"') WHERE JobCandidateID = 2 GO

Execute the statements, and then verify that the desired results are returned.

Task 4: Verify the updated candidate's address


Select the statements from Task 2. Execute the statements, and then verify that the desired results are returned as 7194 Fourth St. Rockhampton.
Results: After this exercise, you should have you have used XQuery with XML methods to view the selected contents of an XML schema and modified an XML object.

Implementing a Microsoft SQL Server 2008 Database

5-57

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 4: Creating XML Indexes


Scenario
The Production department is also considering adopting the new industry standard XML schema to describe Adventure Works products. They want to pilot the aspect of the schema used to describe illustrations of products in XML format. They hope to be able to provide XML-based illustrations of all products and to be able to retrieve data based on the property values of the XML data. This will mean a dramatic increase in the use of the Production.Illustration table and the amount of XML data stored there. You need to create the following indexes to accommodate the increased use: Primary XML index on the Diagram column. Use the following settings: Index name: PXML_Illustration_Diagram Index type: Clustered, nonunique Fill factor: Set the fill factor to 60 percent on both leaf and non-leaf nodes

Secondary path index on the Diagram column. Use these settings: Index name: XMLPATH_Illustration_Diagram Index type: Nonclustered, nonunique Fill factor: Set the fill factor to 70 percent on leaf nodes

Task 1: Create a new query file


Create a new query. File name: CreateXMLIndexes.sql

5-58

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create XML indexes


In the query window, type the following code to create the primary XML index on the Diagram column of the Production.Illustration table:
USE AdventureWorks2008 GO SET ARITHABORT ON CREATE PRIMARY XML INDEX PXML_Illustration_Diagram ON Production.Illustration (Diagram) WITH (FILLFACTOR = 60, PAD_INDEX = ON)

In the query window, below the existing code, type the following code to create the secondary path XML index on the Diagram column of the Production.Illustration table:
CREATE XML INDEX XMLPATH_Illustration_Diagram ON Production.Illustration (Diagram) USING XML INDEX PXML_Illustration_Diagram FOR PATH WITH (FILLFACTOR = 70, PAD_INDEX = OFF) GO

Execute the code and verify that the script completed without any errors. Verify that the new XML indexes are listed and are correct.
Results: After this exercise, you have created XML indexes.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Implementing a Microsoft SQL Server 2008 Database

5-59

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. What is XML? What does the nodes() method do? What are RAW Mode Queries? What are AUTO Mode Queries? What are EXPLICIT Mode Queries? What are PATH Mode Queries? What is the purpose of an XML schema? When would you use untyped XML? When would you use typed XML?

5-60

Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Best Practices related to using XML


Supplement or modify the following best practices for your own work situations: To improve concurrency in a high update scenario, the XML data can be shredded into relational rows in one or more tables. Severe decomposition of this kind may lose object encapsulation and the structure of the XML data, and raises reassembly cost. XML indexes can be created on XML data type columns. It indexes all tags, values and paths over the XML instances in the column and benefits query performance. Your application may benefit from an XML index under the following conditions: Queries on XML columns are common in your workload. XML index maintenance cost during data modification must be taken into account. Your XML values are relatively large and the retrieved parts are relatively small. Building the index avoids parsing the whole data at runtime and benefits index lookups for efficient query processing.

The XML schema processor does not support lax validation in wildcard sections (xs:any and xs:anyAttribute) and xs:anyType. Strict validation ensures that more precise type information regarding the XML nodes instantiating these schema components is known during validation and used during query compilation. If the encoding is not Unicode and is implicit (due to the source code page), the string code page in the database should be the same as or compatible with the code points that you want to load (use COLLATE if necessary). If no such server code page exists, you have to add an explicit XML declaration to specify the proper encoding.

Implementing a Microsoft SQL Server 2008 Database

5-61

MCT USE ONLY. STUDENT USE PROHIBITED

Tools
Tool SQL Server Management Studio Microsoft Visual Studio 2008 Use for Where to find it Start | All Programs | Microsoft SQL Server 2008 Start | All Programs | Microsoft Visual Studio 2008 Start | All Programs | Microsoft SQL Server 2008

Integrated management
and development console

Comprehensive
development platform

SQL Server Configuration Manager

SQL Server, Services, and


networking protocols

MCT USE ONLY. STUDENT USE PROHIBITED

Implementing a Microsoft SQL Server 2008 Database

6-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 6
Implementing Views
Contents:
Lesson 1: Introduction to Views Lesson 2: Creating and Managing Views Lesson 3: Optimizing Performance by Using Views Lab: Implementing Views 6-3 6-9 6-19 6-24

6-2

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

Views are called virtual tables because the result set of a view is not usually saved in the database. The result set for a view is dynamically incorporated into the logic of the statement and the result set is built dynamically at run time. The data accessed through a view can come from many different base tables and other views from the same or different databases, even on other servers. A user can use this virtual table by referencing the view name in Transact-SQL (TSQL) statements the same way a table is referenced, which includes all the Data Manipulation Language (DML) statements. Modifying data through a view however has certain restrictions.

Implementing a Microsoft SQL Server 2008 Database

6-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Introduction to Views

A view is a virtual or logical table composed of the result set of a query. Unlike ordinary tables (base tables) in a relational database, a view is not part of the physical schemait is a dynamic, virtual table computed or collated from data in the database. Effective use of views in database system design helps improve performance and manageability. In this module you will learn about viewsthe different types of views, and how to use them.

6-4

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a View?

Key Points
A view can be thought of as a virtual table or a stored query. The data accessible through a view is not stored in the database as a distinct object. What is stored in the database is a SELECT statement. The data tables referenced by the SELECT statement are known as the base tables for the view.

Implementing a Microsoft SQL Server 2008 Database

6-5

MCT USE ONLY. STUDENT USE PROHIBITED

Types of Views

Key Points
You can create three different types of views depending on what you need. Standard views combine data from one or more base tables (or views) into a new virtual table. Any computations, such as joins or aggregations, are done during query execution for each query referencing the view. Indexed views materialize the view through the creation of a clustered index on the view.

6-6

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Partitioned views join data from one or more base tables across one or more servers. A partitioned view joins horizontally partitioned data from a set of member tables across one or more servers.

Question: Do you think your organization would benefit from implementing partitioned views?

Implementing a Microsoft SQL Server 2008 Database

6-7

MCT USE ONLY. STUDENT USE PROHIBITED

Advantages of Views

Key Points
Views are generally used to focus, simplify, and customize the perception each user has of the database. Frequently occurring aggregations and joins are the best candidates for indexed views. The query optimizer uses the pre-computed results stored in the indexed view, which substantially reduces the cost of the execution. Views can be used as security mechanisms by letting users access data through the view, without granting the users permissions to directly access the underlying base tables of the view. Views can be used to provide a backward compatible interface to emulate a table that previously existed but whose schema has changed.

6-8

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Views can also be used when you copy data to and from Microsoft SQL Server to improve performance and to partition data.

Question: What do you see as being the greatest advantage to using views in your organization?

Implementing a Microsoft SQL Server 2008 Database

6-9

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Creating and Managing Views

When querying through a view, the Database Engine checks to make sure that all the database objects referenced anywhere in the statement exist and that they are valid in the context of the statement, and that data modification statements do not violate any data integrity rules. With certain restrictions, you can modify the data of an underlying base table through a view, in the same manner as you modify data in a table by using UPDATE, INSERT and DELETE statements or by using the bcp utility and BULK INSERT statement.

6-10

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Creating Views

Key Points
To create a view you must be granted permission to do so by the database owner and, if the view is created with the SCHEMABINDING clause, you must have appropriate permissions on any tables or views referenced in the view definition. These are the required and optional fields used in the CREATE VIEW T-SQL statement: schema_name is the name of the schema to which the view belongs. view_name is the name of the view. View names must follow the rules for identifiers. Column is the name to be used for a column in a view. AS specifies the actions the view is to perform. select_statement is the SELECT statement that defines the view. The statement can use more than one table and other views.

Implementing a Microsoft SQL Server 2008 Database

6-11

MCT USE ONLY. STUDENT USE PROHIBITED

CHECK OPTION forces all data modification statements executed against the view to follow the criteria set within select_statement. ENCRYPTION encrypts the entries in sys.syscomments that contain the text of the CREATE VIEW statement. SCHEMABINDING binds the view to the schema of the underlying table or tables. VIEW_METADATA specifies that the instance of SQL Server will return to the DB-Library, ODBC, and OLE DB APIs the metadata information about the view.

6-12

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating a View

Question: How do you think you would deploy these tools and techniques in your organization?

Implementing a Microsoft SQL Server 2008 Database

6-13

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Altering and Dropping Views

Key Points
After a view is defined, you can change its name or modify its definition without dropping and re-creating the view. Dropping and re-creating a view causes the permissions associated with the view to be lost. ALTER VIEW modifies a previously created view. This includes an indexed view. DROP VIEW removes one or more views from the current database.

These are the required and optional fields used in the ALTER VIEW and DROP VIEW T-SQL statement: schema_name is the name of the schema to which the view belongs. view_name is the view to change. Column is the name of one or more columns, separated by commas, which are to be part of the specified view.

6-14

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

ENCRYPTION encrypts the entries in sys.syscomments that contain the text of the ALTER VIEW statement. SCHEMABINDING binds the view to the schema of the underlying table or tables. VIEW_METADATA specifies that the instance of SQL Server will return to the DB-Library, ODBC, and OLE DB APIs the metadata information about the view. AS are the actions the view is to take. select_statement is the SELECT statement that defines the view. WITH CHECK OPTION forces all data modification statements that are executed against the view to follow the criteria set within select_statement.

Implementing a Microsoft SQL Server 2008 Database

6-15

MCT USE ONLY. STUDENT USE PROHIBITED

View Encryption

Key Points
By encrypting a view, you can protect your view creation logic. ENCRYPTION encrypts the entries in sys.syscomments that contain the text of the CREATE VIEW statement. Using WITH ENCRYPTION prevents the view from being published as part of SQL Server replication.

Question: Do you think you might be deploying encrypted views in your organization?

6-16

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

How Ownership Chains Affect Views

Key Points
When an object such as a view, a stored procedure, or a user-defined function references another object, an ownership chain is established. By default, all database objects have owners. Cross-database ownership chaining occurs when the source object depends on objects in another database. Applications that rely on cross-database ownership chaining may generate permission denied errors if cross-database ownership chaining option is turned off.

Implementing a Microsoft SQL Server 2008 Database

6-17

MCT USE ONLY. STUDENT USE PROHIBITED

Sources of Information About Views

Key Points
You can gain information about the definition of a view if it is not encrypted. Views are queried the same way that ordinary tables are queried. You may need to see the definition of the view to understand how its data is derived from the source tables or to see the data defined by the view. Any table hints used when querying the view are ignored. If you change the name of an object referenced by a view, you must modify the view so that its text reflects the new name. Therefore, before renaming an object, display the dependencies of the object first to determine if any views are affected by the proposed change.

6-18

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Modifying Data in a View

Key Points
You can modify the data of an underlying base table through a view, in the same manner as you modify data in a table by using UPDATE, INSERT and DELETE statements or by using the bcp utility and BULK INSERT statement. Views do not maintain a separate copy of data (indexed views are an exception). Updates to views modify base tables.

Implementing a Microsoft SQL Server 2008 Database

6-19

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Optimizing Performance by Using Views

Performance of SQL Server can be optimized by using an indexed view that physically stores the materialized results of the query. There are certain prerequisites and limitations of indexed views, but if one can be used, it can improve performance. Keep in mind that indexed views carry a higher maintenance cost than standard indexes. As a result, you should be careful about when you use them.

6-20

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Performance Considerations for Views

Key Points
While views offer a great deal of flexibility, they should be used carefully as they might introduce performance costs in some scenarios. Indexed views can increase query performance in the following ways: Aggregations can be precomputed and stored in the index to minimize expensive computations during query execution. Tables can be prejoined and the resulting data set stored. Combinations of joins or aggregations can be stored.

Applications that benefit from the implementation of indexed views include: Decision support workloads Data marts

Implementing a Microsoft SQL Server 2008 Database

6-21

MCT USE ONLY. STUDENT USE PROHIBITED

Data warehouses Online analytical processing (OLAP) stores and sources Data mining workloads

6-22

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Performance Considerations for Indexed Views

Key Points
View Indexes are dynamic in that changes to the data in the base tables are automatically reflected in the indexed view. SQL Server query optimizer will try to use an indexed view even if the view is not referenced in the from clause of a T-SQL command. You can then treat the view like any other table by adding additional nonclustered indexes.

Question: How can indexed views improve performance of your organization?

Implementing a Microsoft SQL Server 2008 Database

6-23

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Partitioned View?

Key Points
A partitioned view joins horizontally partitioned data from a set of member tables across one or more servers, making the data appear as if from one table. A partitioned view is not to be confused with an indexed view created on a partition scheme. In a local partitioned view, all participating tables and the view reside on the same instance of SQL Server. In a distributed partitioned view, at least one of the participating tables resides on a different (remote) server. Distributed partitioned views can be used to implement a federation of database servers.

6-24

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Views

Exercise 1: Creating Views


Scenario
Adventure Works finds that their database systems arent performing as well as they would like. After consultation with the Human Resources department, the senior database developer has identified a number of views that will improve database performance and simplify future development. It was also found that indexed views and partitioned views will also improve performance. The senior database developer has decided to start by creating views to simplify the analysis of employee details and contact information. The senior database developer has asked you to perform the following task: Create a new view named HumanResources.vEmployeeDetails that uses the following SELECT logic. Remember to use the SCHEMABINDING option when you create the view, because you will need to create an index on the view later.

Implementing a Microsoft SQL Server 2008 Database

6-25

MCT USE ONLY. STUDENT USE PROHIBITED

In this exercise, you must add a new view to SQL Server at the New York City location. The main tasks for this exercise are as follows: 1. 2. 3. Create a SQL Server Scripts project. Create the HumanResources.vEmployeeDetails view. Test the HumanResources.vEmployeeDetails view.

Task 1: Create a SQL Server Scripts project


1. 2. 3. Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd. Start the Server Management Studio and connect to the server. Create a new project. 4. Name: AW_Views Location: E:\Mod06\Labfiles\Starter

Create a new query file. File name: CreateEmployeeView.sql

6-26

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create the HumanResources.vEmployeeDetails view


1. Type the following Transact-SQL code to create the HumanResources.vEmployeeDetails view:

USE AdventureWorks2008 GO CREATE VIEW HumanResources.vEmployeeDetails WITH SCHEMABINDING AS SELECT e.BusinessEntityID ,c.Title ,c.FirstName ,c.MiddleName ,c.LastName ,c.Suffix ,e.JobTitle ,c.EmailPromotion ,a.AddressLine1 ,a.AddressLine2 ,a.City ,sp.Name AS StateProvinceName ,a.PostalCode ,cr.Name AS CountryRegionName ,c.AdditionalContactInfo FROM HumanResources.Employee e INNER JOIN Person.Person c ON c.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.BusinessEntityAddress ea ON e. BusinessEntityID = ea. BusinessEntityID INNER JOIN Person.Address a ON ea.AddressID = a.AddressID INNER JOIN Person.StateProvince sp ON sp.StateProvinceID = a.StateProvinceID INNER JOIN Person.CountryRegion cr ON cr.CountryRegionCode = sp.CountryRegionCode

2. 3. 4. 5.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that the HumanResources.vEmployeeDetails view is listed in the Object Explorer. Verify that the correct columns are listed in the view.

Implementing a Microsoft SQL Server 2008 Database

6-27

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Test the HumanResources.vEmployeeDetails view


1. Create a new query file. 2. File name: TestEmployeeView.sql

In the blank query window, type the following code:

Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails

3. 4. 5.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that correct data is returned from the view.
Results: After this exercise, you should have created and tested of a new view for the database.

6-28

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Creating Indexed Views


Scenario
After testing the HumanResources.vEmployeeDetails view, the senior database developer has asked you to perform the following task: Turn the HumanResources.vEmployeeDetails view into an indexed view by creating a unique clustered index named IX_vEmployeeDetails on the EmployeeID column.

In this exercise, you need to create an indexed view for the SQL Server database. The main tasks for this exercise are as follows: 1. 2. Create a new query file. Create the IX_vEmployeeDetails index.

Task 1: Create a new query file


Create a new query file. File name: CreateViewIndex.sql

Task 2: Create the IX_vEmployeeDetails index


1. In the query window, type the following Transact-SQL code to create the IX_vEmployeeDetails index on the HumanResources.vEmployeeDetails view:

USE AdventureWorks2008 GO CREATE UNIQUE CLUSTERED INDEX IX_vEmployeeDetails ON HumanResources.vEmployeeDetails (BusinessEntityID)

2. 3. 4.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that the the IX_vEmployeeDetails index is listed in Object Explorer.
Results: After this exercise, you should have created a new view index.

Implementing a Microsoft SQL Server 2008 Database

6-29

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating Partitioned Views


Scenario
After testing the HumanResources.vEmployeeDetails view, the senior database developer has asked you to perform the following task: Create a distributed partitioned view named Person.vContact on the AW_Contacts database. The view should union the sets of data contained in the following source servers and tables: [NY-SQL-01].AW_Contacts.Person.Contact [NY-SQL-01 \SQLINSTANCE2].AW_Contacts.Person.Contact [NY-SQL-01 \SQLINSTANCE3].AW_Contacts.Person.Contact

In this exercise, you need to configure the SQL Server databases and create a new partitioned view. The main tasks for this exercise are as follows: 1. 2. 3. Prepare the SQL Server instances. Create a new query file. Create the Person.vContact distributed partitioned view.

Task 1: Prepare the SQL Server instances


Execute the following code: E:\Mod06\Labfiles\Starter\ LabSetup.cmd

Task 2: Create a new query file


Create a new query file. File name: CreatePartitionedView.sql

6-30

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create the Person.vContact distributed partitioned view


1. In the query window, type the following code to create the distributed partitioned view named Person.vContact on the AW_Contacts database:

USE AW_Contacts GO CREATE VIEW Person.vContact AS SELECT * FROM [NY-SQL-01].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE2].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE3].AW_Contacts.Person.Contact

2. 3. 4. 5. 6.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that the Person.vContact view is listed in the Object Explorer. Verify that the correct columns are listed in the view. Create a new query file. File name: ViewPersonContact.sql

7.

In the query window, type the following code to select the contents of the Person.vContact view:

USE AW_Contacts GO SELECT * FROM Person.vContact

8. 9.

Examine this code. Execute the code. Examine Messages box and verify that the script completed without any errors.

10. Verify that the result set of the Person.vContact view contains the data from the Person.Contact tables on all three SQL Server instances.
Results: After this exercise, you should have configured and tested a new partitioned view for the SQL Server.

Implementing a Microsoft SQL Server 2008 Database

6-31

MCT USE ONLY. STUDENT USE PROHIBITED

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

6-32

Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. 4. How does SQL Server store the view in the database? What is a Standard non-indexed view? What is an unbroken ownership chain? Are SQL Server View Indexes static or dynamic?

Best Practices related to a particular technology area in this module


Supplement or modify the following best practices for your own work situations: Analyze your database workload before implementing indexed views. Use your knowledge of the queries as well as various tools (for example SQL Profiler) to identify the queries that can benefit from indexed views. Frequently occurring aggregations and joins are the best candidates for indexed views. Whether or not a query is asked frequently, it may be a candidate for an indexed view if it takes significant time to answer, and the value of getting the answer quickly is high.

Implementing a Microsoft SQL Server 2008 Database

6-33

MCT USE ONLY. STUDENT USE PROHIBITED

Indexed views work best when the underlying data is infrequently updated. The maintenance of an indexed view can be higher than the cost of maintaining a table index. If the underlying data is updated frequently, then the cost of maintaining the indexed view data may outweigh the performance benefits of using the indexed view. Indexes on tables and indexed views should be designed concurrently to obtain the best results from each construct. Because both indexes and indexed views may be useful for a given query, designing them separately can lead to redundant recommendations that incur high storage and maintenance overhead. While tuning the physical design of a database, trade offs must be made between the performance requirements of a diverse set of queries and updates that the database system must support. Therefore, identifying an appropriate physical design for indexed views is a challenging task, and the Database Tuning Advisor should be used wherever it is possible. Query optimization cost can increase substantially if there are many indexed views that the query optimizer may consider for a particular query. A query optimizer may consider all indexed views that are defined on any subset of tables in the query. Each view has to be investigated for the potential substitution before it is rejected. This may take some time, especially if there are hundreds of such views for a given query.

Tools
Tool SQL Server Management Studio Microsoft Visual Studio 2008 SQL Server Configuration Manager Use for Where to find it Microsoft SQL Server 2008 Microsoft Visual Studio 2008 Microsoft SQL Server 2008

Integrated management and


development console

Comprehensive development
platform

SQL Server, Services, and


networking protocols

MCT USE ONLY. STUDENT USE PROHIBITED

Implementing a Microsoft SQL Server 2008 Database

7-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 7
Implementing Stored Procedures
Contents:
Lesson 1: Using Stored Procedures Lesson 2: Creating Parameterized Stored Procedures Lesson 3: Working with Execution Plans Lesson 4: Handling Exceptions Lab: Implementing Stored Procedures 7-3 7-12 7-17 7-24 7-28

7-2

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

As a database developer, you might be expected to design and implement logic within the database to enforce business rules or data consistency by using stored procedures or user-defined functions. Alternatively, you might be responsible for modifying and maintaining existing modules written by other developers. In this module, you will learn how to create stored procedures. You will also learn how to implement structured exception handling and deal with execution context.

Implementing a Microsoft SQL Server 2008 Database

7-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Using Stored Procedures

A stored procedure is a group of Transact-SQL statements compiled into a single execution plan. Stored procedures can assist you in achieving a consistent implementation of logic across applications. This lesson describes what stored procedures are and what benefits they can bring to your database applications. You will also learn how to alter and remove existing stored procedures.

7-4

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Discussion: What Is a Stored Procedure

Key Points
A stored procedure is a named collection of Transact-SQL statements that is stored on the server within the database itself. Stored procedures are a method of encapsulating repetitive tasks; they support user-declared variables, conditional execution, and other powerful programming features.

Implementing a Microsoft SQL Server 2008 Database

7-5

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Creating a Stored Procedure

Key Points
You can create stored procedures by using the CREATE PROCEDURE statement. Stored procedures can be created only in the current databaseexcept for temporary stored procedures, which are always created in the tempdb database. Creating a stored procedure is similar to creating a view. First write and test the Transact-SQL statements that you want to include in the stored procedure, then, if you receive the results that you expect, create the stored procedure.

7-6

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Guidelines for Creating Stored Procedures

Key Points
There are certain guidelines you should consider when creating Stored Procedures. Design each stored procedure to accomplish a single task. Create, test, and troubleshoot your stored procedure on the server, and then test it from the client. Avoid using the sp_ prefix when you name local stored procedures to easily distinguish system stored procedures. Minimize the use of temporary stored procedures to avoid contention on the system tables in tempdb, a situation that can adversely affect performance.

Implementing a Microsoft SQL Server 2008 Database

7-7

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Stored Procedures

Question: What uses can you think of for stored procedures?

7-8

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Altering Stored Procedures

Key Points
Stored procedures are often modified in response to requests from users or to changes in the underlying table definitions. To modify an existing stored procedure and retain permission assignments and encryption, use the ALTER PROCEDURE statement. SQL Server replaces the previous definition of the stored procedure when it is altered by using ALTER PROCEDURE. If you want to modify a stored procedure that was created by using an option, such as the WITH ENCRYPTION option, you must include the option in the ALTER PROCEDURE statement to retain the functionality that the option provides. ALTER PROCEDURE changes only a single procedure. If your procedure calls other stored procedures, the nested stored procedures are not affected.

Implementing a Microsoft SQL Server 2008 Database

7-9

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Dropping Stored Procedures

Key Points
Use the DROP PROCEDURE statement to remove user-defined stored procedures from the current database. Before you drop a stored procedure, execute the sp_depends stored procedure to determine whether objects depend on the stored procedure.

7-10

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Altering and Dropping Stored Procedures

Question: When might you have to alter a stored procedure in your organization?

Implementing a Microsoft SQL Server 2008 Database

7-11

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Switching Execution Context

Question: When would you use execution context switching in your organization?

7-12

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Creating Parameterized Stored Procedures

Stored procedures are more flexible when you include parameters as part of the procedure definition because you can create more generic application logic. In this lesson, you will learn how to include input and output parameters and how to use return values within stored procedures.

Implementing a Microsoft SQL Server 2008 Database

7-13

MCT USE ONLY. STUDENT USE PROHIBITED

Stored Procedures Parameters

Key Points
A stored procedure communicates with the program that calls the procedure through a list of up to 2,100 parameters. To define a stored procedure that accepts input parameters, you declare one or more variables as parameters in the CREATE PROCEDURE statement. Consider the following guidelines when using input parameters: Provide default values for a parameter where appropriate. If a default is defined, a user can execute the stored procedure without specifying a value for that parameter. As a best practice validate all incoming parameter values at the beginning of a stored procedure to trap missing and invalid values early. This might include checking whether the parameter is NULL.

7-14

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating a Parameterized Stored Procedure

Question: When would you use a Parameterized Stored Procedure in your organization?

Implementing a Microsoft SQL Server 2008 Database

7-15

MCT USE ONLY. STUDENT USE PROHIBITED

Table-valued Parameters

Key Points
Table-valued parameters are a new parameter type in Microsoft SQL Server 2008. Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

7-16

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using Table Value Parameters

Question: What uses can you think of for parameterized tables?

Implementing a Microsoft SQL Server 2008 Database

7-17

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Working with Execution Plans

SQL Server is capable of handling multiple requests to read and write data simultaneously from multiple users. SQL Server uses execution plans as a way of caching frequently used requests for later use. In this way SQL Server is able to scale to meet the demands of many users and frequent requests. In this lesson you will learn what execution plans are and how to work with them.

7-18

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

What Is an Execution Plan?

Key Points
A query execution plan shows how SQL Server navigates the tables and views, and how it uses indexes to execute a query. SQL Server execution plans have two main components: Query Plan and Execution Context. The bulk of the execution plan is a re-entrant, read-only data structure used by any number of users. This is referred to as the query plan. Each user that is currently executing the query has a data structure that holds the data specific to their execution, such as parameter values. This data structure is referred to as the execution context.

Implementing a Microsoft SQL Server 2008 Database

7-19

MCT USE ONLY. STUDENT USE PROHIBITED

Viewing an Execution Plan

Key Points
Execution Plans can be viewed graphically or text based. You can view the estimated and actual execution plans for a query graphically by using SQL Server Management Studio. You can use the Transact-SQL SET statement options to generate an estimated or actual execution plan. Execution plans are not displayed for encrypted stored procedures or for triggers.

7-20

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Execution Plan Caching

Key Points
When SQL Server compiles a query, there are a number of factors that affect whether the query is cached. SQL Server marks each statement in the query as cacheable, fixed-cost on reuse, cache even though zero-cost, not cacheable, or not cacheable because of sensitive information. If at least one of the statements in the query is marked as cacheable, then the query is cached, unless any one statement in the query contains sensitive information, then that statement is marked as not cacheable because of sensitive information. This causes the whole query to be marked not cacheable.

Implementing a Microsoft SQL Server 2008 Database

7-21

MCT USE ONLY. STUDENT USE PROHIBITED

Query Compilation

Key Points
When SQL Server receives a query for execution, its execution plan may already be present in memory (the procedure cache); if not, SQL Server will have to compile the query before executing it. The compilation process is comprised of these four phases: parsing, Algebrizer Tree, compilation and optimization. This process is what happens when the Execution Plan for a query is not cached.

7-22

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Forced Stored Procedure Recompilation

Key Points
SQL Server automatically recompiles stored procedures and triggers when it is advantageous to do this. You can however, force a stored procedure to recompile. When SQL Server recompiles stored procedures, only the statement that caused the recompilation is compiled, rather than the entire procedure. You can force recompilation by using the sp_recompile system stored procedure or by adding the WITH RECOMPILE option to the stored procedure.

Question: When might you want to force a stored procedure to recompile?

Implementing a Microsoft SQL Server 2008 Database

7-23

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Using Execution Plans

Question: When would you want to save an Execution plan as XML?

7-24

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 4

Handling Exceptions

This lesson introduces the Microsoft SQL Server 2008 structured exceptionhandling technique. Exception handling is an important requirement for many Transact-SQL statements, particularly those that involve transactions. Structured exception handling reduces the amount of work required to handle exceptions and can help make your code more reliable.

Implementing a Microsoft SQL Server 2008 Database

7-25

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Structured Exception Handling

Key Points
Structured exception handling is a common way to handle exceptions in many popular programming languages, such as Microsoft Visual Basic and Visual C#. SQL Server 2008 allows you to use structured exception handling in any transactional situation, such as a stored procedure. Use TRYCATCH blocks to implement structured exception handling. The TRY block contains the transactional code that could potentially fail. The CATCH block contains the code that executes if an error occurs in the TRY block.

7-26

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Guidelines for Handling Exceptions

Key Points
When you use the TRYCATCH construct, consider the following guidelines and suggestions. To handle an exception that occurs within a given CATCH block, write a TRY...CATCH block within the specified CATCH block. Attentions will terminate a batch even if the batch is within the scope of a TRYCATCH construct. This includes an attention sent by the Microsoft Distributed Transaction Coordinator (MS DTC) when a distributed transaction fails. MS DTC manages distributed transactions.

Implementing a Microsoft SQL Server 2008 Database

7-27

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Handling Exceptions

Question: When would you add exception handling to a stored procedure in your organization?

7-28

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Stored Procedures

Exercise 1: Creating Stored Procedures


Scenario
The senior database developer has provided you with a SQL Server Scripts project named AWProgrammability. in the E:\MOD07\Labfiles\Starter folder and has specified the following requirements for the modifications you must make: Create a stored procedure named GetDiscounts within the Sales schema that retrieves the following columns from Sales.SpecialOffer: Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, and MaxQty. The procedure should return all rows sorted by StartDate and EndDate. Create a stored procedure named GetDiscountsForCategory within the Sales schema that accepts an input parameter named @Category, which is an nvarchar data type accepting up to 50 characters. The procedure should retrieve the same columns as for GetDiscounts, but should filter the rows based on the @Category parameter.

Implementing a Microsoft SQL Server 2008 Database

7-29

MCT USE ONLY. STUDENT USE PROHIBITED

Create a stored procedure named GetDiscountsForCategoryAndDate within the Sales schema that accepts the @Category parameter as for GetDiscountsForCategory, but includes an additional @DateToCheck datetime input parameter. The @DateToCheck parameter must be able to accept a NULL default value. If a NULL value is specified for the @DateToCheck parameter, set the parameter value to the current date and time by using the GETDATE function. The procedure should retrieve the same columns as for GetDiscounts, but should filter the rows based on the @Category and @DateToCheck parameters. Create a stored procedure named AddDiscount within the Sales schema that inserts new records into the Sales.SpecialOffer table.

In this exercise, you must use SQL Server Management Studio to open a SQL Scripts project and create the stored procedures specified within. The main tasks for this exercise are as follows: 1. 2. 3. 4. Create and test the GetDiscounts stored procedure. Create and test the GetDiscountsForCategory stored procedure. Create and test the GetDiscountsForCategoryAndDate stored procedure. Create and test the AddDiscount stored procedure.

Task 1: Create and test the GetDiscounts stored procedure


1. 2. 3. Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. Open the AWProgrammability.ssmssln solution in the E:\MOD07\Labfiles\Starter folder. Open the InitilizeData.sql query file, and then execute it, confirming that no errors occur. Always connect to the NY-SQL-01 SQL server when performing these tasks. 4. Create the Sales.GetDiscounts stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur.

7-30

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create and test the GetDiscountsForCategory stored procedure


1. Create the Sales.GetDiscountForCategory stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Test the Sales.GetDiscountsForCategory stored procedure using 'Reseller' for the @Category value, and then review the results.

2.

Task 3: Create and test the GetDiscountsForCategoryAndDate stored


procedure
1. Create the Sales.GetDiscountsForCategoryAndDate stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Test the Sales.GetDiscountsForCategoryAndDate stored procedure using 'Reseller' for the @Category value and the default value for the @DateToCheck parameter. Review the results. Test the Sales.GetDiscountForCategoryAndDate stored procedure using 'Reseller' for the @Category value and a date one month from now for the @DateToCheck value. Review the results.

2.

3.

Task 4: Create and test the AddDiscount stored procedure


1. Create the Sales.AddDiscount stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Test the Sales.AddDiscount stored procedure by using the following parameter values: Parameter @Description @DiscountPct @Type @Category @StartDate @EndDate @MinQty @MaxQty Value 'Half price of everything' .5 'Seasonal Discount' 'Customer' Local variable with current date from GETDATE function Local variable with date one month from current date 0 20

2.

Implementing a Microsoft SQL Server 2008 Database

7-31

MCT USE ONLY. STUDENT USE PROHIBITED

3. 4.

Confirm that a new special offer was create by displaying the @NewProductID OUTPUT parameter value. Copy the previous test, and change the @DiscountPct value to -0.5. Use the return value from the stored procedure to determine whether the insert succeeded or failed. If the insert failed, select the latest record from the dbo.ErrorLog table to confirm the error.

Results: After this exercise, you should have created and tested 4 stored procedures.

7-32

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Working with Execution Plans


Scenario
The senior database developer has identified some queries that may not be performing as well as they could be. These queries are provided for you in the ExecutionPlans.sql query file in the AWProgrammability.ssmssln project. You must investigate the execution plans for the queries to identify problem areas. In this exercise, students will view text-based execution plans, graphical execution plans, tune the database to improve performance and view revised execution plans. The main tasks for this exercise are as follows: 1. 2. 3. 4. View text-based execution plans. View graphical execution plans. Tune the database to improve performance. View the revised execution plans.

Task 1: View the text-based execution plan


Select and execute the code between comments --Test the text-based execution plan and --Test the graphical execution plan. Observe the text-based execution plan in the results pane

Task 2: View the graphical execution plan


Select and execute the code below the comment --Test the graphical execution plan. Observe the percentages of the execution plan involved in each operation

Task 3: Tune the database to improve performance


Create an index on the Production.Product.Name column using the TransactSQL below the comment --Tune the database. Create an index on name.

Implementing a Microsoft SQL Server 2008 Database

7-33

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: View the revised execution plan


Select and execute the code below the comment --retest the graphical execution plan. Observe the percentages involved in each operation of the query. Results: After this exercise, you should have created and viewed both text-based and graphical execution plans.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

7-34

Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. If a nonqualified user-defined stored procedure is specified, in which order does the Database Engine searches for the procedure? How can execution plans be used to improve query performance?

Real-world Issues and Scenarios


You have a complex query involving multiple tables where the compiled or recompiled query plan is occasionally not optimal.

Best Practices related to a particular technology area in this module


Supplement or modify the following best practices for your own work situations: Use fully qualified names when referring to database objects in stored procedures. Assign clear, self-documenting names to input parameters.

Implementing a Microsoft SQL Server 2008 Database

8-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 8
Implementing Functions
Contents:
Lesson 1: Introducing Functions Lesson 2: Working with Functions Lesson 3: Controlling Execution Context Lab: Implementing Functions 8-3 8-9 8-13 8-17

8-2

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

Functions are routines that are used to encapsulate frequently performed logic. Rather than having to repeat all the function logic, any code that must perform the logic can call the function. In this lesson, you will learn the design and implementation of user-defined functions that enforce business rules or data consistency, or to modify and maintain existing functions written by other developers.

Implementing a Microsoft SQL Server 2008 Database

8-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Introducing Functions

Functions are routines made up of one or more Transact-SQL statements that can be used to encapsulate code for reuse. A function takes zero or more input parameters and returns either a scalar value or a table. Input parameters can be any data type except timestamp, cursor, or table. Functions do not support output parameters, but do return results, either a single value or a table. This lesson provides an overview of functions and explains why and how you use them, in addition to the syntax for creating them.

8-4

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Types of Functions

Key Points
SQL Server has 4 Main Types of Functions Scalar Functions Scalar functions return a single data value of the type defined in a RETURNS clause. Inline table-valued functions An inline table-valued function returns a table that is the result of a single SELECT statement. Multi-statement table-valued functions A multi-statement table-valued function returns a table built by one or more Transact-SQL statements and is similar to a stored procedure. Built-in Functions Built-in functions are provided by SQL Server to help you perform a variety of operations. They cannot be modified.

Implementing a Microsoft SQL Server 2008 Database

8-5

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Scalar Function?

Key Points
You use scalar functions to return information from a database. A scalar function returns a single data value of the type defined in a RETURNS clause. The body of the function, defined in a BEGINEND block, contains the series of Transact-SQL statements that return the value.

8-6

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

What Is an Inline Table-Valued Function?

Key Points
You can use inline functions to achieve the functionality of parameterized views. One of the limitations of a view is that you are not allowed to include a userprovided parameter within the view when you create it. You can achieve the functionality of a parameterized view by using an inline table-valued function.

Implementing a Microsoft SQL Server 2008 Database

8-7

MCT USE ONLY. STUDENT USE PROHIBITED

What Is a Multi-Statement Table-Valued Function?

Key Points
A multi-statement table-valued function is a combination of a view and a stored procedure. You can use user-defined functions that return a table to replace stored procedures or views. A table-valued function (like a stored procedure) can use complex logic and multiple Transact-SQL statements to build a table. In the same way that you use a view, you can use a table-valued function in the FROM clause of a Transact-SQL statement.

Question: Can you think of a situation in which it might be practical to use a Multi-Statement Table-Valued Function?

8-8

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Functions

Question: What are some commonly used SQL Scalar functions that you can think of?

Implementing a Microsoft SQL Server 2008 Database

8-9

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Working with Functions

In order to effectively employ functions in SQL Server it is important to understand the properties of functions and when to use them. This lesson provides guidelines for creating functions and explains the difference between deterministic and nondeterministic functions and the effect this has on the ability of SQL Server 2008 to index the results of a function. This lesson also provides guidance on how to rewrite stored procedures as functions.

8-10

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Deterministic and Nondeterministic Functions

Key Points
Both built-in and user-defined functions fall into one of two categories: deterministic and nondeterministic. A deterministic function is one that will always return the same result when provided with the same set of input values and for the same database state. A nondeterministic function is one that may return different results for the same set of input values each time it is called, even if the database remains in the same state.

Implementing a Microsoft SQL Server 2008 Database

8-11

MCT USE ONLY. STUDENT USE PROHIBITED

Guidelines for Creating Functions

Key Points
User-defined functions are created using the CREATE FUNCTION statement, modified using the ALTER FUNCTION statement, and removed using the DROP FUNCTION statement. Consider the following guidelines when you create userdefined functions: Each fully qualified user-defined function name (schema_name.function_name) must be unique. Avoid Transact-SQL errors that cause a statement to be canceled and continue with the next statement in the module (such as triggers or stored procedures) because they are treated differently inside a function. In functions, such errors cause the execution of the function to stop.

8-12

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Rewriting Stored Procedures as Functions

Key Points
If a stored procedure meets the following criteria, it is a good candidate for being rewritten as a table-valued function: You can use a user-defined function in an expression in a SELECT or WHERE clause where you cannot easily use a stored procedure. You may find it useful to rewrite a stored procedure or parts of stored procedure as one or more user-defined functions so that it can be used in an expression. It may also improve code reuse to refactor certain stored procedures, or parts of them, as user-defined functions. Generally speaking you should use a table-valued function if the stored procedure returns a single resultset and you should use a scalar function if the stored procedure returns a single scalar value.

Implementing a Microsoft SQL Server 2008 Database

8-13

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Controlling Execution Context

In this lesson, you will learn about execution context and how it affects the way your stored procedures and functions run. You will also learn how to modify the execution context by using the EXECUTE AS clause and about the issues involved in cross-database impersonation.

8-14

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

What Is Execution Context?

Key Points
Execution context is determined by the user or login connected to the session, or executing (calling) a module. Execution context establishes the identity against which permissions are checked. The user or login calling a module, such as a stored procedure or function, usually determines execution context.

Implementing a Microsoft SQL Server 2008 Database

8-15

MCT USE ONLY. STUDENT USE PROHIBITED

The EXECUTE AS Clause

Key Points
The EXECUTE AS clause sets the execution context of a session. You can use the EXECUTE AS clause in a stored procedure or function to set the identity used in its execution context. Understanding how to use the EXECUTE AS clause can help you implement security in scenarios in which you need to access dependent objects but you do not want to rely on unbroken ownership chains.

8-16

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Extending Impersonation Context

Key Points
When you use the EXECUTE AS clause to change the execution context so that a code module executes as a user other than the caller, the code is said to impersonate the alternative user. You can selectively extend the scope of the database impersonation established within a database by establishing a trust model between the two databases.

Implementing a Microsoft SQL Server 2008 Database

8-17

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Functions

Exercise 1: Creating Functions


Scenario
The senior database developer has provided you with a SQL Server Scripts project named AWProgrammability.ssmssln in the E:\MOD08\Labfiles\Starter folder and has specified the following requirements for the modifications you must make: Create a scalar user-defined function named GetMaximumDiscountForCategory within the Sales schema that retrieves the maximum discount percentage currently available for a specific category. Create an @Category nvarchar(50) parameter to limit the results based on the category, and use the GETDATE function to limit the rows based on whether the discount is currently available.

8-18

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Create an inline table-valued user-defined function named GetDiscountsForDate within the Sales schema that retrieves the same columns as the GetDiscounts stored procedure. The function accepts an @DateToCheck datetime parameter to filter the discounts based on the provided date. This allows Adventure Works to test what discounts will be available on a specific date. Create a multi-statement table-valued user-defined function named GetDiscountedProducts within the Sales schema that uses a complex query to retrieve products that have a discount. This complex query will be provided to you. The function accepts an @IncludeHistory bit parameter to filter the returned table based on whether the discount history information is required or only the current information is needed. Create a scalar user-defined function named GetCurrencyRate within the Sales schema that retrieves the latest currency conversion rate for a specific currency. The function accepts an @CurrencyCode nchar(3) parameter to specify the currency to return the conversion rate for. The currency data is located in the AdventureWorksDW2008 database and must be accessed by using the NY-SQL-01\Adam account. Create a multi-statement table-valued user-defined function named GetCurrencyDiscountedProducts within the Sales schema that is similar in functionality to the GetDiscountedProducts function but includes the price and discounted price in an alternate currency. The function accepts an @CurrencyCode nvarchar(3) parameter to specify the currency to be used.

In this exercise, you must use SQL Server Management Studio to open a SQL Scripts project and create the stored procedures specified within. The main tasks for this exercise are as follows: 1. 2. 3. Create and test the GetMaximumDiscountsForCategory user-defined function. Create and test the GetDiscountsForDate user-defined function. Create and test the GetDiscountedProducts user-defined function.

Implementing a Microsoft SQL Server 2008 Database

8-19

MCT USE ONLY. STUDENT USE PROHIBITED

Task 1: Create and test the GetMaximumDiscountForCategory userdefined function


1. 2. 3. 4. 5. 6. 7. 8. 9. Start the NY-SQL-01 virtual machine. Logon as Administrator with the password: Pa$$w0rd. Run the createnewuser.vbs script located at E:\MOD8\Labfiles\Starter. Open Command Prompt. Browse to E:\MOD08\Labfiles\Starter. Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER. Log off Administrator and then logon as Student with the password: Pa$$w0rd. Open the SQL Server Management Studio scripts project located at E:\MOD8\Labfiles\Starter\AWProgrammability.ssmssln. In Solution Explorer open the query file InitilizeData.sql and execute its complete contents, ensure that it executes successfully. Connect to server NY-SQL-01 using Windows Authentication.

10. In Solution Explorer open the query file UserDefinedFunctions.sql. 11. Connect to server NY-SQL-01 using Windows Authentication. 12. Execute the Use AdventureWorks2008 statement. 13. Execute the CREATE FUNCTION statement as show in the example below:
CREATE FUNCTION Sales.GetMaximumDiscountForCategory (@Category nvarchar(50)) RETURNS smallmoney AS BEGIN DECLARE @Max smallmoney SELECT @Max = MAX(DiscountPct) FROM Sales.SpecialOffer WHERE Category = @Category AND GetDate() BETWEEN StartDate AND EndDate GROUP BY Category IF (@Max IS NULL) SET @Max = 0 RETURN @Max END

8-20

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

14. Execute the statement below the comment Test Sales.GetMaximumDiscountForCategory as shown in the example below:
SELECT Sales.GetMaximumDiscountForCategory('Reseller')

15. Verify that a discount value is returned.

Task 2: Create and test the GetDiscountsForDate user-defined function


1. 2. In the UserDefinedFunctions.sql query locate the Create Sales.GetDiscountsForDate comment. Execute the CREATE FUNCTION statement as shown in the example below:

CREATE FUNCTION Sales.GetDiscountsForDate (@DateToCheck datetime) RETURNS TABLE AS RETURN ( SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer WHERE @DateToCheck BETWEEN StartDate AND EndDate )

3. 4.

Locate the Test Sales.GetDiscountsForDate comment. Test the function by executing the SELECT statement as show in the example below:

SELECT * FROM Sales.GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC

5.

Verify that data is returned.

Implementing a Microsoft SQL Server 2008 Database

8-21

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create and test the GetDiscountedProducts user-defined


function
1. 2. In the UserDefinedFunctions.sql query locate the Create Sales.GetDiscountedProducts comment. Execute the CREATE FUNCTION statement as show in the example below.

CREATE FUNCTION Sales.GetDiscountedProducts (@IncludeHistory bit) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money) AS BEGIN IF (@IncludeHistory = 1) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct FROM Sales.SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) ORDER BY ProductID ELSE INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct

8-22

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

(continued)
Sales.SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END FROM

3. 4.

Locate the Test Sales.GetDiscountedProducts comment. Test the function by executing the SELECT statements as shown in the example below.

SELECT * FROM Sales.GetDiscountedProducts(0) SELECT * FROM Sales.GetDiscountedProducts(1)

5.

Save UserDefinedFunctions.sql.

Results: After this exercise, you should have created and tested 3 user-defined functions.

Implementing a Microsoft SQL Server 2008 Database

8-23

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Controlling Execution Context


Scenario
Create a scalar user-defined function named GetCurrencyRate within the Sales schema that retrieves the latest currency conversion rate for a specific currency. The function accepts an @CurrencyCode nchar(3) parameter to specify the currency to return the conversion rate for. The currency data is located in the AdventureWorksDW database and must be accessed by using the NY-SQL01\Adam account. You must establish a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008 databases to enable the GetCurrencyRate function to retrieve the currency data. Create a multi-statement table-valued user-defined function named GetCurrencyDiscountedProducts within the Sales schema that is similar in functionality to the GetDiscountedProducts function but includes the price and discounted price in an alternate currency. The function accepts an @CurrencyCode nvarchar(3) parameter to specify the currency to be used. In this exercise, you must use SQL Server Management Studio to open a SQL Scripts project and create the stored procedures specified within. The main tasks for this exercise are as follows: 1. 2. 3. Create the GetCurrencyRate user-defined function. Establish a database trust relationship between the AdventureWorks2008 database and the AdventureWorksDW2008 database. Create and test the GetCurrencyDiscountedProducts user-defined function.

Task 1: Create the GetCurrencyRate user-defined function


1. 2. 3. 4. In Solution Explorer open the query file ExecutionContext.sql. Connect to server NY-SQL-01 using Windows Authentication. Select and Execute the USE AdventureWorks2008 statement. Locate the Create Sales.GetCurrencyRate comment.

8-24

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

5.

Execute the CREATE FUNCTION statement as shown in the example below:

CREATE FUNCTION Sales.GetCurrencyRate (@CurrencyCode nchar(3)) RETURNS float WITH EXECUTE AS 'Adam' AS BEGIN DECLARE @CurrencyRate float SELECT @CurrencyRate = (SELECT TOP (1) EndOfDayRate FROM AdventureWorksDW2008.dbo.DimCurrency C INNER JOIN AdventureWorksDW2008.dbo.FactCurrencyRate CR ON C.CurrencyKey = CR.CurrencyKey WHERE C.CurrencyAlternateKey = @CurrencyCode ORDER BY CR.DateKey DESC) IF (@CurrencyRate IS NULL) SET @CurrencyRate = 1.0 RETURN @CurrencyRate END GO

6. 7.

Locate the Test Sales.GetCurrencyRate comment. Test the function by executing the SELECT statement as shown in the following example:

SELECT Sales.GetCurrencyRate('GBP')

Note: At this stage you have not established a trust relationship between the database, so you should expect to receive the following error message: The server principal "NY-SQL-01\Adam" is not able to access the database AdventureWorksDW2008 under the current security context.

8.

Save the ExecutionContext.sql query file.

Task 2: Establish a database trust relationship


1. 2. 3. In Solution Explorer open the TrustRelationship.sql query file. Execute the USE AdventureWorksDW2008 statement. Locate the Create the user for the NY-SQL-01\Adam login comment.

Implementing a Microsoft SQL Server 2008 Database

8-25

MCT USE ONLY. STUDENT USE PROHIBITED

4.

Execute the CREATE USER statement as shown in the example below:

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = 'Adam' AND type = 'U') CREATE USER Adam FOR LOGIN [NY-SQL-01\Adam] GO

5. 6.

Locate the Grant Authenticate permission on the database comment. Execute the Transact-SQL code required to grant the mapped user AUTHENTICATE permission in the AdventureWorksDW2008 database as show in the example below:

GRANT AUTHENTICATE TO Adam GO

7. 8.

Locate the Grant SELECT permission to Adam comment. Execute the GRANT statement as show in the example below:

GRANT SELECT TO Adam GO

9.

Locate the Set the TRUSTWORTHY database option on the AdventureWorks2008 database comment.

10. Execute the ALTER DATABASE statement as show in the example below:
ALTER DATABASE AdventureWorks2008 SET TRUSTWORTHY ON GO

11. Verify that the statement executes successfully. 12. Save the TrustRelationship.sql query file.

Task 3: Create and test the GetCurrencyDiscountedProducts userdefined function


1. 2. 3. In Solution Explorer open the ExecutionContext.sql query file. Select and execute the USE AdventureWorks2008 statement. Locate the Test Sales.GetCurrencyDiscountedProducts comment.

8-26

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

4.

Execute the CREATE FUNCTION statement as show in the following example:

-- Sales.GetCurrencyDiscountedProducts CREATE FUNCTION Sales.GetCurrencyDiscountedProducts (@CurrencyCode nchar(3)) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, CurrencyPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money, DiscountedCurrencyPrice money) AS BEGIN DECLARE @CurrencyRate float SET @CurrencyRate = Sales.GetCurrencyRate(@CurrencyCode) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, P.ListPrice * @CurrencyRate, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct, (P.ListPrice - P.ListPrice * SO.DiscountPct) * @CurrencyRate FROM Sales.SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END GO

5. 6.

Verify that the statement executes successfully. Locate the Test Sales.GetCurrencydiscountedProducts comment.

Implementing a Microsoft SQL Server 2008 Database

8-27

MCT USE ONLY. STUDENT USE PROHIBITED

7.

Test the function by execution the SELECT statement as shown in the following example:

SELECT * FROM Sales.GetCurrencyDiscountedProducts('GBP')

8. 9.

Review the query results and verify that the statement executes successfully. Save all open files and close Management Studio.

Results: After this exercise, you should have created two user-defined functions and created a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008..

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

8-28

Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. When using the EXECUTE AS clause, what privileges should the login or user have? What two purposes does the TRUSTWORTHY property serve?

Real-world Issues and Scenarios


User1 is the owner of the table MyTable. They want User2 to be able to truncate the table, but User2 has no direct permissions on the table.

Implementing a Microsoft SQL Server 2008 Database

9-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 9
Implementing Managed Code in a Database
Contents:
Lesson 1: Introduction to the SQL Server Common Language Runtime Lesson 2: Importing and Configuring Assemblies Lesson 3: Creating Managed Database Objects Lab: Implementing Managed Code in a Database 9-4 9-10 9-15 9-20

9-2

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

As a database professional, you are often asked to create databases and related objects to meet specific needs. Most of this can be accomplished using TransactSQL. However, there are times when the requirements go beyond the abilities of Transact-SQL. These requirements may include functionality such as: Complex/compound data types like currency values that include culture information, complex numbers, dates that include calendar system, spatial data or storing entire arrays of values in a single column. Accessing image files on the operating system and reading them or copying them into the database. Adding logic that verifies data such as available quantities within a database transaction and completes or rolls back the transaction based on specific criteria.

Implementing a Microsoft SQL Server 2008 Database

9-3

MCT USE ONLY. STUDENT USE PROHIBITED

In this module, you will learn about using CLR integrated code to create userdefined database objects that are managed by the .NET Framework. Integrated code is used to create user-defined functions, stored procedures, aggregates, types, and triggers. These objects can be developed using any .NET language and can be highly specialized.

9-4

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Introduction to the SQL Server Common Language Runtime

In this lesson, you will learn what the SQL Server Common Language Runtime (CLR) is and how it relates to the .NET Framework. You will also identify the advantages of using managed code and when it is most appropriate to use it instead of Transact-SQL statements and procedures.

Implementing a Microsoft SQL Server 2008 Database

9-5

MCT USE ONLY. STUDENT USE PROHIBITED

Introduction to the .NET Framework

Key Points
The .NET Framework is the foundation for developing Microsoft Windows applications and services including Microsoft SQL Server. The .NET Framework offers the developer tools that make application and service development easier by: Offering a consistent environment for development. Allowing development in most common languages such as Microsoft C++ and Visual Basic .NET. Supplying tools and libraries for common tasks and functions.

9-6

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

What Is the .NET Common Language Runtime?

Key Points
The .NET Common Language Runtime (CLR) is the layer in the .NET Framework that allows you to create programs and procedures in any .NET language and deploy it for use. The resulting resources are referred to as managed code. The CLR Integration feature withinMicrosoft SQL Server 2008 allows you to use .NET assemblies to customize your SQL databases. The .NET CLR offers: Access to existing managed code. Security features to ensure managed code will not compromise the server. The ability to create new resources using .NET languages like Microsoft Visual C# and Microsoft Visual Basic .NET.

Implementing a Microsoft SQL Server 2008 Database

9-7

MCT USE ONLY. STUDENT USE PROHIBITED

Advantages of Managed Code

Key Points
Managed code allows SQL Server to use thousands of available .NET libraries and assemblies created by third parties as well as those you develop. These libraries and assemblies allow complex logic and calculations to be used within standard Transact-SQL statements and stored procedures. Some other advantages include: Use any .NET language such as VB or C# to develop managed code. Object oriented code provides type safety. All managed code can be accessed through T-SQL.

Question: What do you think is the biggest advantage to using managed code in SQL Server 2008 within your organizations database?

9-8

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

CLR Managed Code Database Objects

Key Points
SQL CLR Integration allows you to create database objects that enhance your ability to provide custom functionality and package them into .NET assemblies. The Integrated CLR assemblies provide a way to customize the behavior and structure of SQL Server 2008 database objects. Custom assemblies can be created to integrate custom user-defined types, aggregates, stored procedures, triggers and functions.

Implementing a Microsoft SQL Server 2008 Database

9-9

MCT USE ONLY. STUDENT USE PROHIBITED

Managed Code vs. Transact-SQL

Key Points
While Transact-SQL is the primary method for manipulating database objects, managed code offers advantages by allowing the utilization of different resources. This includes being able to offload the process to a .NET client application or middle tier component. The assemblies can be processed off the server for CPU intensive processing. Other reasons to use these include: Transact SQL can only be executed within the SQL Server environment. Transact SQL is best for intensive data access with little or no procedural logic. Managed code works well for complex logic or CPU intensive operations.

Question: In your work, what situations do you see that managed code would have been an appropriate or more efficient solution?

9-10

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Importing and Configuring Assemblies

In this lesson, you will gain an understanding of the various considerations involved with using an assembly in SQL Server 2008. You will learn how to determine the appropriate trust level as you begin the process of integrating custom assemblies with the SQL Server 2008 CLR.

Implementing a Microsoft SQL Server 2008 Database

9-11

MCT USE ONLY. STUDENT USE PROHIBITED

What Is an Assembly?

Key Points
Assemblies are DLLs created and compiled with a .NET language such as VB or C# and contain logic to add custom database objects to SQL Server 2008 via CLR integration. Advantages include: Assemblies are developed using any preferred .NET language. Being external to SQL Server 2008, assemblies are easily shared.

9-12

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Assembly Trust Levels

Key Points
Using the CLR offers several levels of trust that can be set within policies for the machine and host that the assembly runs on. Trust levels can also be set for the Windows account that the SQL Server service runs under. There are three SQL Server permission sets that allow the administrator to control the server's exposure to security and integrity risks: SAFE, EXTERNAL_ACCESS, and UNSAFE. Remember that CLR integration must be explicitly enabled on the SQL Server to use these features. The following are some important security features of managed code: Trust levels control access of assembly code to external resources. A number of levels of security policies are available to ensure system integrity. Policy levels for assemblies should allow for the highest level of safety possible while allowing the assembly to perform its programmed tasks.

Implementing a Microsoft SQL Server 2008 Database

9-13

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Importing an Assembly

Key Points
The syntax for creating an assembly in SQL Server 2008 is shown above. Note that the assembly_name is a required parameter. The client_assembly_specifier is the easiest parameter for specifying the location of the DLL file using the full path. Important things to remember are: An assembly must first be created in SQL Server 2008 before the objects it contains can be used. The PERMISSION_SET parameter is optional. However, if it is omitted the default value is SAFE.

9-14

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Importing and Configuring an Assembly

Question: Of the three trust levels the UNSAFE level is the least protected. What situations can you think of that would warrant the risk of using this trust level? Is it wise to set a company policy to never use this level? Why or why not?

Implementing a Microsoft SQL Server 2008 Database

9-15

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Creating Managed Database Objects

In this lesson you will learn how easy it is to create CLR integrated database objects. After the managed code objects are created, they become available for use in Transact SQL statements. Because CLR Integrated database objects are transparent to the user, they are simple to use in Transact SQL statements. This provides an extensive custom library that you can create and use for the manipulation of data whether in Transact SQL statements, stored procedures or triggers.

9-16

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Overview of Managed Database Objects

Key Points
Because managed database objects are .NET Framework routines they have the same structure as any other .NET routine. The routines all have a Namespace, contain classes, and use methods. Managed database objects can be addressed directly in Transact-SQL code or in stored procedures.

Implementing a Microsoft SQL Server 2008 Database

9-17

MCT USE ONLY. STUDENT USE PROHIBITED

Managed Stored Procedures, Triggers and Functions

Key Points
By using the CREATE PROCEDURE, CREATE TRIGGER or CREATE FUNCTION statements you can easily import your managed code. When you create these objects you are not required to use the same name that is in the assembly. You can also define input and output parameters. Once the object is created you can use it in an Execute statement or as part of a Transact-SQL statement.

9-18

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Managed Aggregates and User-Defined Types

Key Points
Managed aggregates and user-defined types can be created to extend the existing SQL aggregates and types. This affords the opportunity to create complex calculations and data types to accommodate special requirements that are not addressed in SQL Server 2008. Key advantages to CLR aggregates and types are: CLR aggregates allow the creation of specialized aggregates that go beyond the available SQL aggregates such as SUM, MAX, and AVG. CLR Types allow storage and handling of custom types such as complex variables and spatial data.

Implementing a Microsoft SQL Server 2008 Database

9-19

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Managed Database Objects

9-20

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Implementing Managed Code in a Database

Exercise 1: Importing an Assembly


Scenario
The senior database developer has created the managed assembly named AWorksUtilities.dll; you will only need to import, configure, and test the assembly. The AWorksUtilities.dll managed assembly is located in the E:\MOD09\Labfiles\Starter folder. The AWorksUtilities.dll managed assembly contains the following items: A stored procedure named SaveXM A user-defined function named GetLongDate A trigger named EmailChange An aggregate named Concatenate A user-defined type named IPAddress

Implementing a Microsoft SQL Server 2008 Database

9-21

MCT USE ONLY. STUDENT USE PROHIBITED

In this exercise you will import the custom assembly: AWorksUtilities. The main tasks for this exercise are as follows: 1. 2. Start the NY-SQL-01 virtual machine and log on as Administrator. Import the AWorksUtilities assembly.

Task 1: Start the NY-SQL-01 virtual machine and log on as


Administrator
Start 6232A-NY-SQL-01, and log on as Administrator with the password of Pa$$w0rd.

Task 2: Import the AWorksUtilities assembly


1. 2. 3. 4. 5. Open the AWorks_CLR.ssmssln solution. Execute the Initialize.sql query file. Open the ImportAssembly.sql query file and add and run the code to enable CLR Integration. Add and run the code to create the AWorksUtilities assembly. Save the changed ImportAssembly.sql query file.
Results: After this exercise, you should have the managed database objects in the AWorksUtilities assembly available for use within the AdventureWorks2008 database.

9-22

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Creating Managed Database Objects


Scenario
Now that you have imported the AWorksUtilities assembly for use in your company database, the senior database developer has requested that you create links to and test the new managed database objects. The senior database developer has provided you with a SQL Server Scripts solution named AWorks_CLR.ssmssln in the E:\MOD09\Labfiles\Starter folder and the following requirements for the modifications you must make. The SaveXML stored procedure should accept one xml parameter named @XmlData and one nvarchar(100) parameter named @FileName. The external name of the managed stored procedure is AWorksUtilities.StoredProcedures.SaveXML. The GetLongDate user-defined function should accept one datetime parameter named @DateVal and should return an nvarchar(50) value. The external name of the managed function is AWorksUtilities.UserDefinedFunctions.GetLongDate. The EmailChange trigger should fire only on updates to the Person.EmailAddress table. The external name of the trigger is AWorksUtilities.Triggers.EmailChange. The Concatenate aggregate accepts one nvarchar(4000) parameter named @input and returns an nvarchar(4000) value. The external name of the aggregate is AWorksUtilities.Concatenate. The IPAddress user-defined type has the external name AWorksUtilities.IPAddress.

In this exercise you will test each of the new managed database objects. The main tasks for this exercise are as follows: 1. 2. 3. Create the SaveXML managed stored procedure referencing the external assembly. Create the GetLongDate managed user-defined function referencing the external assembly. Create the EmailChange managed trigger on the Person.EmailAddress table referencing the external assembly.

Implementing a Microsoft SQL Server 2008 Database

9-23

MCT USE ONLY. STUDENT USE PROHIBITED

4. 5.

Create the Concatenate managed aggregate function referencing the external assembly. Create the IPAddress managed user-defined type referencing the external assembly.

Task 1: Create the SaveXML managed stored procedure referencing


the external assembly
1. 2. 3. 4. 5. 6. 7. 8. 9. Open the SaveXML.sql query file and add the code to create the SaveXML stored procedure. Highlight and run the new code. Highlight and run the DECLARE, SET, and EXEC statements. Add code to change the security permissions. Highlight and run the ALTER ASSEMBLY statement. Highlight and run the DECLARE, SET, and EXEC statements. Save the SaveXML.sql file. Using Windows Explorer check for the existence of the Output.xml file in the E:\MOD09\Labfiles\Starter folder. Open the Output.xml file and verify that the file contains XML.

Task 2: Create the GetLongDate managed user-defined function


referencing the external assembly
1. 2. 3. 4. 5. Open the GetLongDate.sql query file. Add the code to create the GetLongDate function then highlight and run the code. Select and run the SELECT statement and execute it. Confirm that the records returned display with a long OrderDate value. Save the GetLongDate.sql file.

9-24

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create the EmailChange managed trigger on the


Person.EmailAddress table referencing the external assembly
1. 2. 3. 4. 5. Open the EmailChange.sql query file. Add and execute the code to create the EmailChange trigger. Highlight and execute the first UPDATE statement Highlight and execute the second UPDATE statement. Save the EmailChange.sql file.

Task 4: Create the Concatenate managed aggregate function


referencing the external assembly
1. 2. 3. 4. 5. Open the Concatenate.sql query file. Add and execute the code to create the Concatenate aggregate. Highlight and execute the SELECT statement. Confirm that orders are displayed as a concatenated string. Save the Concatenate.sql file.

Task 5: Create the IPAddress managed user-defined type referencing


the external assembly
1. 2. 3. 4. 5. Open the IPAddress.sql query file. Add and execute the code to create the new IPAddress type Highlight and execute the SELECT statements. Confirm that three result sets are displayed that show the IPAddress value in various forms. Save the IPAddress.sql file.
Results: After this exercise, you should have successfully imported assembly code and created managed database objects.

Implementing a Microsoft SQL Server 2008 Database

9-25

MCT USE ONLY. STUDENT USE PROHIBITED

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

9-26

Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. When is CLR integration of managed code the best option for creating database objects? When is Transact-SQL the best choice? Given what you know of CLR Integration, are there some previous projects in your organization that could have benefited by using managed code?

Implementing a Microsoft SQL Server 2008 Database

9-27

MCT USE ONLY. STUDENT USE PROHIBITED

A Common Issue related to CLR integration in SQL Server 2008


Identify the most likely causes for the following common issue related to using CLR Integration in SQL Server 2008 and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module.
Issue When using a managed database object you get an error indicating that the execution of user code in the .NET framework is disabled. Troubleshooting tip

Real-world Issues and Scenarios


Scenario 1: You are working with an international company that wants to store date and time data along with time zone information and what calendar system to use. They specifically want the information in a particular format and all in a single column in the database. Scenario 2: Your company has a large number of files that they wish to index within a SQL Server database. The number of files has made the file system sluggish and inefficient. You have been asked to create managed code that will copy the files from the file system and place them into Large Object Binary (LOB) columns in the database. You will also need to create a way to select the row with the LOB column and copy the saved file out to the file system for access by an application.

MCT USE ONLY. STUDENT USE PROHIBITED

Implementing a Microsoft SQL Server 2008 Database

10-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 10
Managing Transactions and Locks
Contents:
Lesson 1: Overview of Transactions and Locks Lesson 2: Managing Transactions Lesson 3: Understanding SQL Server Locking Architecture Lesson 4: Managing Locks Lab: Managing Transactions and Locks 10-3 10-11 10-25 10-34 10-49

10-2

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

It is the responsibility of an enterprise database system to provide mechanisms ensuring the physical integrity of each transaction. A transaction is a sequence of operations performed as a single logical unit of work, and Microsoft SQL Server provides locking facilities that preserve transaction isolation. In this module, you will learn how to manage transactions and locks. This module explains how to use transactions and the SQL Server locking mechanisms to meet the performance and data integrity requirements of your applications.

Implementing a Microsoft SQL Server 2008 Database

10-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Overview of Transactions and Locks

Transactions use locking to prevent other users from changing or reading data in a transaction that has not completed. SQL Server uses the transaction log to ensure that updates are complete and recoverable. This lesson introduces the concept of transactions and locks in SQL Server.

10-4

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Transactions?

Key Points
A transaction is a sequence of steps that perform a logical unit of work. They must exhibit four properties that are collectively known as ACID. Atomicity either all the steps in the transaction must succeed or none of them should be performed. Consistency when the transaction is complete, data must be in a consistent state. Isolation changes made by a transaction must be isolated from other concurrent transactions. Durability when the transaction is complete, the changes must be made permanent in the database and survive even system failures.

Transactions ensure that multiple data modifications are processed as a unit. For example, a banking transaction might credit one account and debit another. Both steps must be completed together or not at all. SQL Server supports transaction processing to manage multiple transactions.

Implementing a Microsoft SQL Server 2008 Database

10-5

MCT USE ONLY. STUDENT USE PROHIBITED

Transaction Log
Every transaction is recorded in a transaction log to maintain database consistency and to aid in transaction recovery. When changes are made to data in SQL Server, the changes are recorded in the transaction log on disk as they are executed and then written to the database. If any part of the transaction fails, all of the changes made so far are rolled back to leave the database in its original state. This system ensures that updates are complete and recoverable. By default, all changes to the database are logged. However, you can change the SQL Server recovery mode to allow certain bulk operations to be minimally logged. For more information, see Minimally Logged Operations in SQL Server Books Online. Transactions use locking to prevent other users from changing or reading data in a transaction that has not completed. Locking is required in online transaction processing (OLTP) for multi-user systems. Question: Can you think of database operations in your organization where database transactions are especially critical?

10-6

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Locks?

Key Points
Locks prevent update conflicts. Users cannot read or modify data that other users are in the process of changing. For example, if you want to compute an aggregate and ensure that another transaction does not modify the set of data that is used to compute the aggregate, you can request that the system hold locks on the data. There are two main types of lock: Read locks, which ensure that other users do not change the data you are reading, but allow other users to read that data. Write locks, which ensure that no other users can read or update the data that you are updating.

Consider the following facts about locks: Locks make the serialization of transactions possible, so that only one person at a time can change a data element. For example, locks in an airline reservation system ensure that only one person is assigned a particular seat.

Implementing a Microsoft SQL Server 2008 Database

10-7

MCT USE ONLY. STUDENT USE PROHIBITED

SQL Server dynamically sets and adjusts the appropriate level of locking during a transaction. It also is possible to control how some of the locks are used manually. Locks are necessary for concurrent transactions to allow users to access and update data at the same time. High concurrency means that there are a number of users who are experiencing good response time with little conflict. From the system administrators perspective, the primary concerns are the number of users, the number of transactions, and the throughput. From the users perspective, the overriding concern is response time.

Question: If a doctor's office uses a database application to manage patient records, how might locks play a role in that application?

10-8

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

What Is Concurrency Control?

Key Points
Concurrency control ensures that modifications made by one person do not adversely affect modifications that others make. There are two types of concurrency control; pessimistic and optimistic. Pessimistic. Pessimistic concurrency control locks data when data is read in preparation for an update. Other users cannot then perform actions that would alter the underlying data until the user who applied the lock is done with the data. Optimistic. Optimistic concurrency control does not lock data when data is initially read. Rather, when an update is performed, SQL Server checks to determine whether the underlying data was changed since it initially read it. If so, the user receives an error, the transaction rolls back, and the user must start over.

Implementing a Microsoft SQL Server 2008 Database

10-9

MCT USE ONLY. STUDENT USE PROHIBITED

SQL Server supports a wide range of optimistic and pessimistic concurrency control mechanisms. Users specify the type of concurrency control by specifying the transaction isolation level for a connection. Question: Can you think of an application in your organization that might work well with optimistic concurrency control?

10-10

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Introducing Transactions

Question: What happens when a transaction is rolled back?

Implementing a Microsoft SQL Server 2008 Database

10-11

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Managing Transactions

Data integrity is vital to a database server. Multiple users may try to update the same record with different data, or someone may attempt to read data that has been removed from the database. To help manage data integrity SQL Server uses transactions when reading and writing data. This section describes how to define transactions, what to consider when you use them, how to set an implicit transaction option, and the restrictions on using transactions. It also discusses transaction processing and recovery.

10-12

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Autocommit Transactions

Key Points
The default transaction management mode in SQL Server is autocommit mode. In this mode, SQL Server automatically commits or rolls back each Transact-SQL statement as it completes. If a transaction completes successfully, it is committed; if it fails, it is rolled back. A connection to SQL Server operates in this mode unless it is overridden by the start of an explicit transaction or implicit transaction mode is set on. When an explicit transaction ends or implicit transaction mode is switched off, SQL Server reverts to using autocommit mode.

Implementing a Microsoft SQL Server 2008 Database

10-13

MCT USE ONLY. STUDENT USE PROHIBITED

Compile Errors
When working in autocommit mode, compile time errors can cause more than one Transact-SQL statement to fail. In this mode, a batch of statements is compiled as a unit and if a compile error is found, nothing in the batch is compiled or executed. The following example shows how this might happen.
USE AdventureWorks2008; GO CREATE TABLE NewTable (Id INT PRIMARY KEY, Info CHAR(3)); GO INSERT INTO NewTable VALUES (1, 'aaa'); INSERT INTO NewTable VALUES (2, 'bbb'); INSERT INTO NewTable VALUSE (3, 'ccc'); -- Syntax error. GO SELECT * FROM NewTable; -- Returns no rows. GO

Because there is a typographical error in the third INSERT statement, the batch cannot compile, and so none of the three INSERT statements run. Question: When might autocommit mode not be appropriate in a database application?

10-14

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Explicit Transactions

Key Points
You can use explicit transactions to define your own units of business logic. For example, in a bank transfer function, you might enclose the withdrawal of funds from one account and the deposit of those funds in another account within one logical unit of work.

Starting a Transaction
You start a transaction by using the BEGIN TRANSACTION statement. You can specify a name for the transaction, and you can use the WITH MARK option to specify a description for the transaction to be marked in the transaction log. This transaction log mark can be used when restoring a database to indicate the point to which you want to restore.

Committing a Transaction
You can commit the work contained in a transaction by issuing the COMMIT TRANSACTION statement. Use this to end a transaction if no errors have occurred and you want the contents of the transaction to be committed to the database.

Implementing a Microsoft SQL Server 2008 Database

10-15

MCT USE ONLY. STUDENT USE PROHIBITED

Rolling Back a Transaction


You can cancel the work contained in a transaction by issuing the ROLLBACK TRANSACTION statement. Use this to end a transaction if errors have occurred and you want the contents of the transaction to be undone and the database to remain in the state it was before the transaction began.

Example
The following example shows how to use transactions.
BEGIN TRANSACTION fund_transfer EXEC debit_checking 100, 'account1' EXEC credit_savings 100, 'account2' IF @@error <> 0 ROLLBACK TRANSACTION fund_transfer ELSE COMMIT TRANSACTION fund_transfer

If the debit_checking procedure fails because of low funds, an error will be raised and the transaction will be rolled back. Similarly, if the credit_savings procedure fails because of an invalid account name, the transaction will roll back and the funds will not be taken from the checking account. For more information about using explicit transactions, see BEGIN TRANSACTION, COMMIT TRANSACTION, and ROLLBACK TRANSACTION in SQL Server Books Online.

Saving a Transaction
By using savepoints, you can roll back a transaction to a named point in the transaction, instead of the beginning of the transaction. You create a savepoint by issuing the SAVE TRANSACTION statement and specifying the name of the savepoint. You can then use the ROLLBACK TRANSACTION statement and specify the savepoint name to roll the changes back to that point. Use savepoints when an error is unlikely to occur and the cost of checking the data before the error occurs is much higher than testing for the error after the data modifications have been submitted. For example, if you do not expect stock levels to be too low to fulfill an order, you could create a trigger that raises an error when stock levels fall below zero on a stock table. In your ordering code, you can create a savepoint, submit the order, and then check for a negative stock level error from the trigger. If that error is raised, you can roll back the transaction to before the savepoint and notify the customer accordingly.

10-16

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

For more information about savepoints, see SAVE TRANSACTION in SQL Server Books Online. Question: When might you want to use a savepoint?

Implementing a Microsoft SQL Server 2008 Database

10-17

MCT USE ONLY. STUDENT USE PROHIBITED

Implicit Transactions

Key Points
In most cases, it is best to work in autocommit mode and define transactions explicitly using the BEGIN TRANSACTION statement. However for applications that were originally developed on systems other than SQL Server, the implicit transaction mode can be useful. Implicit transaction mode automatically starts a transaction when you issue certain statements, and the transaction then continues until you issue a commit statement or a rollback statement.

Setting Implicit Transaction Mode


You use the SET statement to switch implicit transaction mode on and off, as shown in the following example.
SET IMPLICIT_TRANSACTIONS ON -- Do some work in implicit transaction mode. SET IMPLICIT TRANSACTIONS OFF -- Return to autocommit mode.

By default, implicit transaction mode is off and the database works in autocommit mode.

10-18

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Starting Implicit Transactions


When using implicit transaction mode, a transaction is automatically started when any of the following statements are executed: ALTER TABLE CREATE DELETE DROP FETCH GRANT INSERT OPEN REVOKE SELECT TRUNCATE TABLE UPDATE

Nested transactions are not allowed in implicit transaction mode. If the connection is already in a transaction, these statements do not start a new transaction.

Ending Implicit Transactions


If you do not explicitly end an implicit transaction, none of the changes will be committed to the database when the user disconnects. You must use the COMMIT TRANSACTION statement to make the changes permanent or the ROLLBACK TRANSACTION statement to delete the changes and release any locks that are being held. Question: Can you think of an application in your organization where implicit transactions might be appropriate?

Implementing a Microsoft SQL Server 2008 Database

10-19

MCT USE ONLY. STUDENT USE PROHIBITED

Transaction Recovery

Key Points
SQL Server automatically guarantees that all committed transactions are reflected in the database in the event of a failure. It uses the transaction log and checkpoints to do this.

Checkpoints
As each Transact-SQL statement is executed, it is recorded to the transaction log on disk before it is written to the database. SQL Server performs checkpoints at defined intervals. Checkpoints are marked in the transaction log to identify which transactions have already been applied to the database. When a new checkpoint occurs, all transactions since the last checkpoint are written to the database. This frees up log space and shortens recovery time.

10-20

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Transaction Recovery
The recovery process runs automatically every time that SQL Server starts, such as after an intended shutdown or a power failure. The automatic recovery process uses the transaction log to roll forward any committed transactions and roll back any incomplete transactions. The log uses the last checkpoint as a starting marker knowing that all transactions committed before this were written to the database. In the slide example: Transaction 1 is committed before the checkpoint, so it is reflected in the database.Error! Bookmark not defined. Transactions 2 and 4 were committed after the checkpoint, so they must be reconstructed from the log (rolled forward). Transactions 3 and 5 were not committed, so SQL Server rolls them back.

Data Cache
Initially, pages in the data cache are the same as the pages on disk. However, as changes occur in the cache, they are committed to disk and checkpoints are written into the log. As the cache become full, the lazywriter process writes committed changes to disk and removes the associated page from the cache, which frees space. Question: A server crash occurs while two transactions are running. Transaction A is an autocommit transaction that has been written to the transaction log, but not written to the disk. Transaction B is an explicit transaction that has not been committed, though a checkpoint was written while Transaction B was running. What will happen to each transaction when the server is recovered?

Implementing a Microsoft SQL Server 2008 Database

10-21

MCT USE ONLY. STUDENT USE PROHIBITED

Considerations for Using Transactions

Key Points
Transactions should be as short as possible. Longer transactions increase the likelihood that users will not be able to access locked data. Some methods to keep transactions short include the following: Do not require input from users during a transaction. Address issues that require user interaction before you start the transaction. For example, if you are updating a customer record, obtain the necessary information from the user before you begin the transaction. Do not open a transaction while browsing through data, if at all possible. Transactions should not start until all preliminary data analysis has been completed. INSERT, UPDATE, and DELETE should be the primary statements in a transaction, and they should be written to affect the fewest number of rows. A transaction should never be smaller than a logical unit of work. Access the least amount of data possible while in a transaction. This decreases the number of locked rows and reduces contention.

10-22

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Issues with Nested Transactions


Consider the following issues regarding nesting transactions: You should use nesting carefully, if at all, because the failure to commit or roll back a transaction leaves locks in place indefinitely. You can use the @@trancount global variable to determine whether any open transactions exist and how deeply they are nested.

Question: When would nested transactions be appropriate?

Implementing a Microsoft SQL Server 2008 Database

10-23

MCT USE ONLY. STUDENT USE PROHIBITED

Restricted Statements

Key Points
Certain statements may not be included inside an explicit transaction. For example, some are long-running operations that you are not likely to use within the context of a transaction. Restricted statements include the following: ALTER DATABASE BACKUP CREATE DATABASE DROP DATABASE RECONFIGURE RESTORE UPDATE STATISTICS

10-24

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

You cannot use full-text system stored procedures in explicit transactions. You also cannot execute the sp_dboption stored procedure to set database options, or use any system stored procedures that modify the master database in implicit or explicit transactions. Use of sp_dboption is not recommended, because sp_dboption has been deprecated. Use ALTER DATABASE instead.

Implementing a Microsoft SQL Server 2008 Database

10-25

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Understanding SQL Server Locking Architecture

When multiple users attempt to access or modify data at the same time, unpredictable results can occur if the database server provides no way of managing which data can be modified, and when. To address these problems, SQL Server uses a variety of locks to determine when data can be read and modified. This lesson describes concurrency issues, the resource items that can be locked, the types of locks that can be placed on those resources, and how locks can be combined.

10-26

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

What Concurrency Problems Are Prevented by Locking?

Key Points
When users are accessing data concurrently, there is a risk that one user's actions might affect records that another user is accessing. Locks can prevent the following situations that compromise transaction integrity: Lost updates. An update can get lost when a transaction overwrites the changes from another transaction. For example, two users can update the same information, but only the last change saved is reflected in the database. Uncommitted dependencies (dirty read). An uncommitted dependency occurs when a second transaction reads uncommitted data from another transaction. The second transaction can potentially make changes based on data that is either inaccurate or nonexistent. Inconsistent analysis (nonrepeatable read). An inconsistent analysis occurs when a transaction reads the same row more than one time and when, between the two (or more) readings, another transaction modifies that row. Because the row was modified between readings, each reading produces different values, which introduces inconsistency.

Implementing a Microsoft SQL Server 2008 Database

10-27

MCT USE ONLY. STUDENT USE PROHIBITED

Phantom reads. Phantom reads can occur when transactions are not isolated from one another. For example, you could perform an update on all records in a region at the same time that another transaction inserts a new record for the region. The next time that the original transaction reads the data, an additional record is present.

Question: Has your organization experienced concurrency problems with database applications? If so, what behavior did you see?

10-28

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Lockable Resources

Key Points
For optimal performance, the number of locks that SQL Server maintains must be balanced with the amount of data that each lock holds. To minimize the cost of locking, SQL Server automatically locks resources at a level that is appropriate to the task. Question: If a database needs to lock several rows of data at once, what resources might be locked?

Implementing a Microsoft SQL Server 2008 Database

10-29

MCT USE ONLY. STUDENT USE PROHIBITED

Types of Locks

Key Points
SQL Server locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions. SQL Server has two main types of locks: basic locks and locks for special situations.

Basic Locks
In general, read operations acquire shared locks, and write operations acquire exclusive locks. Shared locks. SQL Server typically uses shared (read) locks for operations that neither change nor update data. If SQL Server has applied a shared lock to a resource, a second transaction also can acquire a shared lock, even though the first transaction has not completed. Consider the following facts about shared locks: They are used for read-only operations; data cannot be modified. SQL Server releases shared locks on a record as soon as the next record is read.

10-30

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

A shared lock will exist until all rows that satisfy the query have been returned to the client.

Exclusive locks. SQL Server uses exclusive (write) locks for the INSERT, UPDATE, and DELETE data modification statements. Consider the following facts about exclusive locks: Only one transaction can acquire an exclusive lock on a resource. A transaction cannot acquire a shared lock on a resource that has an exclusive lock. A transaction cannot acquire an exclusive lock on a resource until all shared locks are released.

Special Situation Locks


Depending on the situation, SQL Server can use other types of locks: Intent locks. SQL Server uses intent locks internally to minimize locking conflicts. Intent locks establish a locking hierarchy so that other transactions cannot acquire locks at more inclusive levels. For example, if a transaction has an exclusive row-level lock on a specific customer record, the intent lock prevents another transaction from acquiring an exclusive lock at the tablelevel. Intent locks include intent share (IS), intent exclusive (IX), and shared with intent exclusive (SIX). Update locks. SQL Server uses update locks when it will modify a page at a later point. Before it modifies the page, SQL Server promotes the update page lock to an exclusive page lock to prevent locking conflicts. Consider the following facts about update locks. Update locks are: Acquired during the initial portion of an update operation when the pages are first being read. Compatible with shared locks.

Schema locks. SQL Server uses these to ensure that a table or index is not dropped, or its schema modified, when it is referenced by another session. SQL Server provides two types of schema locks: Schema stability (Sch-S), which ensures that a resource is not dropped.

Implementing a Microsoft SQL Server 2008 Database

10-31

MCT USE ONLY. STUDENT USE PROHIBITED

Schema modification (Sch-M), which ensures that other sessions do not reference a resource that is under modification.

Bulk update locks. SQL Server uses these to enable processes to bulk copy data concurrently into the same table while preventing other processes that are not bulk-copying data from accessing the table. SQL Server uses bulk update locks when either of the following is used: the TABLOCK hint or the table lock on bulk load option.

Question: What happens if a query tries to read data from a row that is currently locked by an exclusive (X) lock?

10-32

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Lock Compatibility

Key Points
Some locks are compatible with other locks, and some locks are not. For example, two users can both hold shared locks on the same data at the same time, but only one update lock can be issued on a piece of data at any one time. Locks have a compatibility matrix that shows which locks are compatible with other locks that are established on the same resource. The locks in the following table are listed in order from the least restrictive (shared) to the most restrictive (exclusive).

Implementing a Microsoft SQL Server 2008 Database

10-33

MCT USE ONLY. STUDENT USE PROHIBITED

Existing granted lock Requested Lock Intent shared (IS) Shared (S) Update (U) Intent exclusive (IX) Shared with intent exclusive (SIX) Exclusive (X) IS Yes Yes Yes Yes Yes S Yes Yes Yes No No U Yes Yes No No No IX Yes No No Yes No SIX Yes No No No No X No No No No No

No

No

No

No

No

No

Note An IX lock is compatible with other IX locks because IX means the intention is to update only some, rather than all, of the rows.

In addition, compatibility for schema locks is as follows: The schema modification lock (Sch-M) is incompatible with all locks. The schema stability lock (Sch-S) is compatible with all locks except the schema modification lock (Sch-M).

Question: Can you think of situations where lock compatibility is important?

10-34

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 4

Managing Locks

This section describes locking options that you can specify at the session level. It also describes how SQL Server handles deadlocks, and how you can view information about locks.

Implementing a Microsoft SQL Server 2008 Database

10-35

MCT USE ONLY. STUDENT USE PROHIBITED

Session Level Locking Options

Key Points
SQL Server allows you to control locking options at the session level by setting the transaction isolation level.

Transaction Isolation Level


An isolation level protects a transaction from the effects of other concurrent transactions. Use the transaction isolation level to set the isolation level for all transactions during a session. When you set the isolation level, you specify the default locking behavior for all statements in your session. Setting transaction isolation levels allows programmers to accept increased risk of integrity problems in exchange for greater concurrent access to data. The higher the isolation level, the lower the risk of data integrity problems. This is at the cost of locks being held for longer, and the locks themselves being more restrictive with respect to concurrent transactions. You can override a session-level isolation level in individual statements by using lock specification. You also can use the DBCC USEROPTIONS statement to specify transaction isolation for a statement.

10-36

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

You can set the transaction isolation level for a session by using the SET statement.
SET TRANSACTION ISOLATION LEVEL {READ COMMITTED | READ UNCOMMITTED | REPEATABLE READ | SERIALIZABLE | SNAPSHOT}

The behavior of the READ COMMITTED option depends on the setting of the READ_COMMITTED_SNAPSHOT database option, which can be ON or OFF.
SET READ_COMMITTED_SNAPSHOT ON

The following table describes the locking isolation level options.


Option READ COMMITTED with READ_COMMITTED_SNAPSHOT OFF Description Directs SQL Server to use shared locks while reading. At this level, you cannot experience dirty reads. Directs SQL Server to use row versioning instead of locking. The data is not protected from updates made by other transactions. Directs SQL Server not to issue shared locks and does not honor exclusive locks. You can experience dirty reads. Indicates that dirty reads and nonrepeatable reads cannot occur. Shared locks are held until the end of the transaction. Prevents other users from updating or inserting new rows that match the criteria in the WHERE clause of the transaction. Phantoms cannot occur.

READ COMMITTED with READ_COMMITTED_SNAPSHOT ON

READ UNCOMMITTED

REPEATABLE READ

SERIALIZABLE

The following example sets the isolation level for the current session to READ UNCOMMITTED and then runs DBCC USEROPTIONS to verify that SQL Server has made the change.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED DBCC USEROPTIONS

Implementing a Microsoft SQL Server 2008 Database

10-37

MCT USE ONLY. STUDENT USE PROHIBITED

The following results show the output of these statements.


Set option textsize language dateformat datefirst ... isolation level (13 row(s) affected) read uncommitted Value 2147483627 us_english mdy 7

Note DBCC always prints the following message when it is executed: DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Lock Timeout
With the SET LOCK_TIMEOUT option, it is possible to set the maximum amount of time that SQL Server allows a transaction to wait for the release of a blocked resource. SET LOCK_TIMEOUT timeout_period The timeout_period indicates the number of milliseconds that pass before SQL Server returns a locking error. A value of -1 (the default) indicates no timeout period. After you change it, the new setting is in effect for the remainder of the session. This example sets the lock timeout period to 180,000 milliseconds.
SET LOCK_TIMEOUT 180000

10-38

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

To determine the current session value, query @@lock_timeout global variable. This example displays the current @@lock_timeout setting and displays the result of 180000.
SELECT @@lock_timeout

Question: Why might you want to change the lock timeout?

Implementing a Microsoft SQL Server 2008 Database

10-39

MCT USE ONLY. STUDENT USE PROHIBITED

Lock Escalation

Key Points
Lock escalation is the process of converting many fine-grain locks into fewer coarse-grain locks, reducing system overhead while increasing the probability of concurrency contention. As the SQL Server Database Engine acquires low-level locks, it also places intent locks on the objects that contain the lower-level objects. When locking rows or index key ranges, the Database Engine places an intent lock on the pages that contain the rows or keys. When locking pages, the Database Engine places an intent lock on the higher level objects that contain the pages. In addition to intent lock on the object, intent page locks are requested on the following objects: Leaf-level pages of nonclustered indexes Data pages of clustered indexes Heap data pages

10-40

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

The Database Engine might do both row and page locking for the same statement to minimize the number of locks and reduce the likelihood that lock escalation will be necessary. For example, the Database Engine could place page locks on a nonclustered index (if enough contiguous keys in the index node are selected to satisfy the query) and row locks on the data. To escalate locks, the Database Engine attempts to change the intent lock on the table to the corresponding full lock, for example, changing an intent exclusive (IX) lock to an exclusive (X) lock, or an intent shared (IS) lock to a shared (S) lock). If the lock escalation attempt succeeds and the full table lock is acquired, then all heap or B-tree, page (PAGE), or row-level (RID) locks held by the transaction on the heap or index are released. If the full lock cannot be acquired, no lock escalation happens at that time and the Database Engine will continue to acquire row, key, or page locks. Partitioned tables can have locks escalated to the partition level before escalating to the table level. Partition-level escalation can be set on a per-table basis.

Implementing a Microsoft SQL Server 2008 Database

10-41

MCT USE ONLY. STUDENT USE PROHIBITED

Dynamic Locking

Key Points
SQL Server uses a dynamic locking architecture to determine the most costeffective locks. It automatically determines which locks are most appropriate when a query is executed, based on the characteristics of the schema and query. SQL Server dynamically increases and decreases the granularity and types of locks. The query optimizer usually chooses the correct lock granularity at the time that the execution plan is compiled, thus minimizing the need to escalate locks. For example, if an update acquires a large number of row-level locks and has locked a significant percentage of a table, the row-level locks are escalated to a table lock. Then the transaction releases the row-level locks, thereby reducing lock overhead. SQL Server can also escalate locks to the partition level; if a table is partitioned, and a lock is requested for data that resides entirely with a single partition of the table, SQL Server can escalate the lock to the partition level, so that records in the other table partitions are not locked.

10-42

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Advantages of Dynamic Locking


Dynamic locking has the following advantages: Simplified database administration, because database administrators no longer have to be concerned with adjusting lock escalation thresholds. Increased performance, because SQL Server minimizes system overhead by using locks appropriate to the task.

Implementing a Microsoft SQL Server 2008 Database

10-43

MCT USE ONLY. STUDENT USE PROHIBITED

What Are Deadlocks?

Key Points
A deadlock occurs when two transactions have locks on separate objects and each transaction requests a lock on the other transactions object. For example: Transaction A holds a share lock on row 1. Transaction B holds a share lock on row 2. Transaction A requests an exclusive lock on row 2, but it cannot be granted until Transaction B releases the share lock. Transaction B requests an exclusive lock on row 1, but it cannot be granted until Transaction A releases the share lock.

Each transaction must wait for the other to release the lock. A deadlock can occur when several long-running transactions execute concurrently in the same database. A deadlock also can occur as a result of the order in which the optimizer processes a complex query, such as a join, in which you cannot necessarily control the order of processing.

10-44

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

How SQL Sever Ends a Deadlock


SQL Server ends a deadlock by automatically terminating one of the transactions. The process SQL Server uses is in the following list. 1. Rolls back the transaction of the deadlock victim. In a deadlock, SQL Server gives priority to the transaction that has been processing the longest; that transaction prevails. SQL Server rolls back the transaction with the least amount of time invested. 2. 3. 4. Notifies the deadlock victims application (with message number 1205). Cancels the deadlock victims current request. Allows the other transaction to continue.

Important In a multiuser environment, each client should check regularly for message number 1205, which indicates that the transaction was rolled back. If message 1205 is found, the application should attempt the transaction again.

Guidelines for Minimizing Deadlocks


While it is not always possible to eliminate deadlocks, you can reduce the risk of a deadlock by observing the following guidelines: Use resources in the same sequence in all transactions. For example, in all transactions that reference more than one table, reference the tables in the same order whenever possible. Shorten transactions by minimizing the number of steps. Shorten transaction times by avoiding queries that affect many rows. Set the DEADLOCK_PRIORITY setting to LOW. When this setting is set and the process encounters a deadlock, it will be chosen as the deadlock victim. This is useful for online analytical processing (OLAP) database or reporting processes that you do not want to interfere with higher-priority OLTP processes.

Implementing a Microsoft SQL Server 2008 Database

10-45

MCT USE ONLY. STUDENT USE PROHIBITED

Lock Timeout
If a transaction becomes locked while waiting for a resource and a deadlock results, SQL Server will terminate one of the participating transactions with no timeout. If no deadlock occurs, SQL Server blocks the transaction requesting the lock until the other transaction releases the lock. By default, there is no mandatory timeout period that SQL Server observes. The only way to test whether a resource that you want to lock is already locked is to attempt to access the data, which could result in getting locked indefinitely. The LOCK_TIMEOUT setting allows an application to set a maximum time that a statement waits on a blocked resource before the blocked statement is automatically cancelled. The cancellation does not roll back or cancel the transaction. The application must trap the error to handle the timeout situation and take remedial action, such as resubmitting the transaction or rolling it back. The following example shows how to set the lock timeout. The timeout_period is the number of milliseconds that SQL Server will wait before returning a locking error.
SET LOCK_TIMEOUT timeout_period

The KILL command terminates a user process based on the server process ID (spid).
KILL {spid | UOW} [WITH STATUSONLY]

Question: Have you experienced deadlocking problems in your current environment? If so, how did you determine that deadlocks were a problem, and how was it resolved?

10-46

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Methods to View Locking Information

Key Points
Typically, you use SQL Server Management Studio or the sp_lock system stored procedure to display a report of active locks. You can use SQL Server Profiler to obtain information on a specific set of transactions. You can also use Reliability and Performance Monitor to display SQL Server locking histories.

Activity Monitor
Use Activity Monitorin SQL Server Management Studio to display information about current locking activity. You can view server activity by user and locking information by process or object.

sys.dm_tran_locks Dynamic Management View


You can query the sys.dm_tran_locks dynamic management view to retrieve information about the locks currently held by an instance of the Database Engine. Each row returned describes a currently granted lock or a requested lock.

Implementing a Microsoft SQL Server 2008 Database

10-47

MCT USE ONLY. STUDENT USE PROHIBITED

The following example shows how to query this dynamic management view.
SELECT * FROM sys.dm_tran_locks

The columns returned are divided into two main groups; the resource group which describes the resource on which the request is made, and the request group which describes the lock request. For more information about the results, see sys.dm_tran_locks in SQL Server Books Online.

SQL Server Profiler


SQL Server Profiler is a tool that monitors server activities. You can collect information about a variety of events by creating traces, which provide a detailed profile of server events. You can use this profile to analyze and resolve server resource issues, monitor login attempts and connections, and correct deadlock problems. Use the Locks Event Category to capture locking information in a trace.

Reliability and Performance Monitor


You can view SQL Server locking information by using Reliability and Performance Monitor in Windows Server 2008. or System Monitor in Windows Server 2003.. Use the SQLServer:Locks objects to retrieve this information. Question: When would you want to choose one method of viewing locks over another?

10-48

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Viewing Locking Information

Question: What locking information does Activity Monitor provide?

Implementing a Microsoft SQL Server 2008 Database

10-49

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Managing Transactions and Locks

Exercise 1: Using Transactions


Scenario
You are a database developer in the IT department of Adventure Works Bicycle manufacturing company. In order to avoid data integrity issues that are occurring, you need to enclose some of your business logic in transactions. You will work with simple queries to ensure that you understand the issues before you implement this in the live database.

Task 1: Start the virtual machine and log on as Student


1. 2. In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd.

10-50

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create and commit a transaction


1. 2. 3. 4. 5. 6. 7. 8. 9. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Open the script E:\Mod10\Labfiles\Starter\Tran1.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the script. Add a statement to begin a transaction in the appropriate place. Execute the script. Notice that the transaction has not ended. Add a statement to commit the transaction in the appropriate place. Execute the statement that you have just added to end the transaction. Execute the last two statements of the script to verify that the changes have been committed to the database. Close the file.

Task 3: Create and rollback a transaction


1. 2. 3. 4. 5. Open the script E:\Mod10\Labfiles\Starter\Tran2.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the script. Add a statement to roll back the transaction in the appropriate place. Execute the script and verify that the changes are not made and the transaction is complete. Close SQL Server Management Studio.
Results: After this exercise, you should have committed and rolled back transactions.

Implementing a Microsoft SQL Server 2008 Database

10-51

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Managing Locks


Scenario
Now, you also need to solve some locking errors that are occurring in user applications, so you must test out some scenarios to identify and resolve the issues.

Task 1: View locking information


1. 2. 3. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Use the Activity Monitor window to review the current lock information. Create a new query to select the following columns from the sys.dm_tran_locks dynamic management view. 4. 5. 6. 7. 8. 9. resource_type request_mode request_type request_status request_session_id

Execute the query and review the results that show the lock on the master database. Open the script E:\Mod10\Labfiles\Starter\Lock1.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review and execute the script, noting the SPID of your connection. Execute the query against the sys.dm_tran_locks dynamic management view and note the new locks listed. Use the Activity Monitor window to review the additional locks held. In the Lock1 query window, execute a ROLLBACK TRANSACTION statement.

10. Execute the query against the sys.dm_tran_locks dynamic management view and note the new locks have been released.

10-52

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Set locking options


1. 2. 3. 4. 5. 6. 7. 8. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Open E:\Mod10\Labfiles\Starter\Lock1.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the contents of the file and execute the script. Open E:\Mod10\Labfiles\Starter\Lock2.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the contents of the file and execute the script. Open E:\Mod\10Labfiles\Starter\LockList.sql and connect to the NY-SQL01 instance by using Windows authentication. Execute the script and notice the WAIT entry in the request_status column. Cancel the Lock2.sql script and verify that the waiting transaction has been cancelled.

Task 3: Set the lock timeout


1. 2. 3. Add a SET statement to the start of the Lock2.sql script to change the lock timeout to five seconds. Execute the query and note that the query now times out. Close SQL Server Management Studio.
Results: After this exercise, you should have set locking options and set the lock timeout.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Implementing a Microsoft SQL Server 2008 Database

10-53

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. What is the default Transaction Isolation Level in SQL Server? How long is a lock held in a read operation when using the READ COMMITTED isolation level? What happens when an Update (U) lock needs to modify data.

10-54

Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Common Issues related to blocking


Identify the causes for the following common issues related to blocking and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module.
Issue How can I determine if my blocking problem is related to lock escalation? Operations involving a large number of table rows results in a lock escalation and table blocking. Troubleshooting tip

Real-world Issues and Scenarios


A stored procedure queries the same row of data twice. In the time between the first and second queries, another user updates the row, causing the second query to return different results (a non-repeatable read). How can you modify this behavior so that both queries in the stored procedure return the same data, and the row update is postponed until after the second query?

Best Practices related to designing transactions


Supplement or modify the following best practices for your own work situations: Keep transactions as short as possible, because this reduces the possibility of locking conflicts with other transactions. However, a transaction should never be smaller than a logical unit of work. Design transactions to minimize deadlocks, so that transactions do not have to be resubmitted. Regularly check for error number 1205, which signifies that a transaction has been rolled back as the victim of a deadlock. Set the LOCK_TIMEOUT option with care, ensuring that you trap timed-outtransaction errors and handle them accordingly. Monitor the locking information for your applications.

Implement a Microsoft SQL Server 2008 Database

11-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 11
Using Service Broker
Contents:
Lesson 1: Service Broker Overview Lesson 2: Creating Service Broker Objects Lesson 3: Sending and Receiving Messages Lab: Using Service Broker 11-3 11-14 11-22 11-27

11-2

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Module Overview

Microsoft SQL Server Service Broker provides a number of significant benefits to database applications. Database integration enhances application performance and simplifies administration, message ordering and coordination provides for simplified application development, and automatic activation allows applications to scale with the message volume. Integration with SQL Server allows transactional messaging without the added overhead and complexity of an external distributed transaction coordinator. In this module you will learn more about Service Broker, how to create Service Broker objects, and how to use Service Broker to send and receive messages.

Implement a Microsoft SQL Server 2008 Database

11-3

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 1

Service Broker Overview

Service Broker, a part of the Database Engine, provides a message-based communication platform that enables independent application components to perform as a functioning whole. In this lesson you will learn the system architecture, conversation architecture, conversation process, conversation priority, and security architecture of Service Broker. You will also learn several SQL Server Management Studio enhancements that pertain directly to Service Broker.

11-4

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

What Is Service Broker?

Key Points
Service Broker provides queuing and reliable messaging for SQL Server. Service Broker is used both for applications that use a single SQL Server instance and applications that distribute work across multiple instances. Service Broker includes infrastructure for asynchronous programming that can be used for applications within a single database or a single instance as well as for distributed applications. Service Broker reduces application development time by providing much of the infrastructure, as a key component of a Service Oriented Architecture (SOA) that is necessary to build a distributed application. Service Broker also makes it easy to scale your application up or down to accommodate the amount of traffic the application receives.

Implement a Microsoft SQL Server 2008 Database

11-5

MCT USE ONLY. STUDENT USE PROHIBITED

Service Broker System Architecture

Key Points
Service Broker applications consist of Service Broker database objects and one or more applications that use those objects. Conversation components. The run-time structure of the conversation. Applications exchange messages as part of a conversation. Service definition objects. These are design-time components that specify the basic design of the application. These components define the message types for the application, the conversation flow for the application, and the database storage for the application. Routing and security components. These components define the infrastructure for exchanging messages between databases and instances of the Database Engine.

11-6

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Service Broker Conversation Architecture

Key Points
All Service Broker applications communicate through conversations. Conversations are reliable, long-running, asynchronous exchanges of messages. Messages are the data that is exchanged between services. Each message belongs to one conversation, and has a specific message type. Dialogs let Service Broker provide exactly-once-in-order (EOIO) message delivery. Each dialog belongs to one conversation group, and follows a specific contract. Conversation groups identify conversations that work together to complete the same task. Service Broker uses conversation groups to manage message locking. Application developers use conversation groups to manage concurrency, and to help with state management.

Implement a Microsoft SQL Server 2008 Database

11-7

MCT USE ONLY. STUDENT USE PROHIBITED

Service Broker Conversation Process

Key Points
A program that uses Service Broker is typically composed of a number of components working together to accomplish a task. A program that initiates a conversation creates and sends a message to another service. That program may wait for a response, or exit immediately and rely on another program to process the response. For a service that is the target of a conversation, the program receives an incoming message from the queue for the service, reads the message data, does any necessary processing, and then creates and sends a response message if appropriate.

11-8

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

An application does not need a special object model or library to work with Service Broker. Instead, programs send Transact-SQL commands to SQL Server and process the results of those commands. An application can be activated by Service Broker, can run as a background service, can run as a scheduled job, or can be started in response to an event.

Implement a Microsoft SQL Server 2008 Database

11-9

MCT USE ONLY. STUDENT USE PROHIBITED

Service Broker Conversation Priority

Key Points
Conversation priorities are a set of user-defined rules, which are new to SQL Server 2008, each of which specifies a priority level and the criteria for determining which Service Broker conversations to assign the priority level. Conversation priorities are created in each database using the CREATE BROKER PRIORITY statement. Each conversation has two conversation endpoints: the initiator conversation endpoint and the target conversation endpoint. For the initiator conversation endpoint, the initiator service is the local service and the target service is the remote service. For the target conversation endpoint, the target service is the local service and the initiator service is the remote service. Conversation endpoints retain their priority level until the conversation ends.

11-10

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Service Broker sends messages between instances of the Database Engine using blocks of message fragments, so if there are several message fragments with different priorities ready to send to one instance, Service Broker may send all of the fragments in one block. Service Broker includes a starvation prevention mechanism to help keep large numbers of high priority messages from blocking low priority messages.

Implement a Microsoft SQL Server 2008 Database

11-11

MCT USE ONLY. STUDENT USE PROHIBITED

Service Broker Security Architecture

Key Points
Service Broker security allows services hosted by different SQL Server instances to communicate securely, even where the instances are on different computers that have no other trust relationship or where the source and destination computers are not connected to the same network at the same time. Dialog security encrypts messages in an individual dialog conversation and verifies the identities of participants in the dialog. Transport security prevents unauthorized databases from sending Service Broker messages to databases in the local instance. Transport security establishes an authenticated network connection between two databases.

11-12

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Management Studio Enhancements

Key Points
Several Management Studio enhancements have been made to this release of SQL Server. New Service Broker menu items have been added to the SQL Server Management Studio Object Explorer. New counters have been added to the Broker Statistics performance object. The new counters are: Activation Errors Total, Corrupted Messages Total, Dequeued TransmissionQ Msgs/sec, Dropped Messages Total, and Enqueued TransmissionQ Msgs/sec. Conversation priorities let administrators and developers specify that messages for important Service Broker conversations are sent and received before messages from less important conversations.

Implement a Microsoft SQL Server 2008 Database

11-13

MCT USE ONLY. STUDENT USE PROHIBITED

The ssbdiagnose utility analyzes the configuration between two Service Broker services, or for a single service. IntelliSense provides an array of options that make language references easily accessible. When coding, you do not need to leave the editor to perform searches on language elements.

11-14

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 2

Creating Service Broker Objects

An application uses Service Broker by executing Transact-SQL statements that operate on Service Broker objects defined in a database. In this lesson you will learn about enabling service broker, external activation support, and the syntax for creating message types, contracts, queues, and services.

Implement a Microsoft SQL Server 2008 Database

11-15

MCT USE ONLY. STUDENT USE PROHIBITED

Enabling Service Broker

Key Points
By default, when you attach or restore a database, the Service Broker identifier and message delivery status are unchanged. To correctly support message delivery, each Service Broker identifier should be unique across all instances of the Database Engine on the same network. You should not have multiple databases that are actively performing Service Broker operations and using the same identifiers. Enabling SQL Server Service Broker in any database require a database lock.

11-16

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

External Activation Support

Key Points
External activation works with programs that run independently of SQL Server. For external activation, Service Broker produces a SQL Server event indicating that the external program should start another queue reader. SQL Server cannot track the capacity or the number of external processes that are reading from the queue. Therefore, SQL Server produces queue activation events periodically for as long as activation is required. An external application that uses event-based activation typically creates an event notification on the queue that receives messages for the service. The external application creates a service and queue for receiving the activation messages and then monitors that queue for messages that report QUEUE_ACTIVATION events. Internal activation works with SQL Server stored procedures. In this case, Service Broker directly activates the stored procedure.

Implement a Microsoft SQL Server 2008 Database

11-17

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Creating Message Types

Key Points
Each message type specifies the validation that SQL Server performs for messages of that type. SQL Server can validate that the message contains valid XML, that the message contains XML that conforms to a particular schema, or that the message contains no data at all. Service Broker offers a built-in message type named DEFAULT. If the message type is not specified in a Service Broker SEND command, the system will use the DEFAULT message type.

11-18

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Creating Contracts

Key Points
CREATE CONTRACT creates a new contact in the current database that is owned by the principal specified in the AUTHORIZATION clause. Server, database, and schema names cannot be specified. The contract specifies which message types can be used to accomplish the desired work. The contract also specifies which participant in the conversation can use each message type. A contract must contain a message type sent by the initiator or a message type sent by either participant; otherwise, there is no way for the initiator to begin a conversation that uses the contract. If no contract is specified in the BEGIN DIALOG statement, Service Broker uses the DEFAULT contract.

Implement a Microsoft SQL Server 2008 Database

11-19

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Creating Queues

Key Points
CREATE QUEUE creates a new queue in the database. Queues store messages. When a message arrives for a service, Service Broker puts the message on the queue associated with the service. A queue can be the target of a SELECT statement. However, the contents of a queue can only be modified using statements that operate on Service Broker conversations, such as SEND, RECEIVE, and END CONVERSATION. A queue cannot be the target of an INSERT, UPDATE, DELETE, or TRUNCATE statement. Creating a queue in an inactive state lets you get the infrastructure in place for a service before allowing messages to be received on the queue. Permissions for the activation stored procedure are checked when Service Broker starts the stored procedure, not when the queue is created. The CREATE QUEUE statement does not verify that the user specified in the EXECUTE AS clause has permission to execute the stored procedure specified in the PROCEDURE NAME clause.

11-20

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Creating Services

Key Points
CREATE SERVICE creates a new service. Service Broker uses the name of the service to route messages, deliver messages to the correct queue within a database, and enforce the contract for a conversation. A service exposes the functionality provided by the contracts with which it is associated, so that they can be used by other services. The CREATE SERVICE statement specifies the contracts that this service is the target for. When Service Broker accepts a new conversation from a remote service, the name of the target service determines the queue where the broker places messages in the conversation. Permission for creating a service defaults to members of the db_ddladmin or db_owner fixed database roles and the sysadmin fixed server role.

Implement a Microsoft SQL Server 2008 Database

11-21

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Creating Service Broker Objects

Question: What must a contract contain and why?

11-22

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Lesson 3

Sending and Receiving Messages

In this lesson you will learn the syntax for sending messages using Service Broker. You will also learn the syntax for receiving messages. Finally, you will be introduced to several diagnostic tools available for use with SQL Server Service Broker.

Implement a Microsoft SQL Server 2008 Database

11-23

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Sending Messages

Key Points
SEND sends a message, using an existing conversation. The SEND statement transmits a message from the service on one end of a Service Broker conversation to the service on the other end of the conversation. Messages that are sent to a service in another instance of the SQL Server Database Engine are stored in a transmission queue in the current database until they can be transmitted to the service queue in the remote instance. The SEND statement locks the conversation group that the specified conversation handle belongs to.

Question: What permission or permissions must a user have to send a message?

11-24

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Syntax for Receiving Messages

Key Points
The RECEIVE statement reads messages from a queue and returns a result set. The result set consists of zero or more rows, each of which contains one message. The messages that are returned by the RECEIVE statement can be of different message types. Applications can use the message_type_name column to route each message to code that handles the associated message type. If the conversation handle or conversation group identifier specified in the WHERE clause does not exist, or is not associated with the specified queue, the RECEIVE statement returns an error. The RECEIVE statement has no priority starvation prevention. If a single RECEIVE statement locks a conversation group and retrieves a lot of messages from low priority conversations, no messages can be received from high priority conversations in the group.

Implement a Microsoft SQL Server 2008 Database

11-25

MCT USE ONLY. STUDENT USE PROHIBITED

Demonstration: Sending and Receiving Messages

Question: Where does the conversation handle supplied to the ON CONVERSATION clause come from?

11-26

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Diagnostic Tools for Sending\Receiving Messages

Key Points
Several tools are available for diagnosing Service Broker activities. Service Broker uses a transmission queue as a holding area for messages. Each database contains a separate transmission queue. The transmission queue is stored in the primary filegroup for the database. Service Broker includes multiple performance objects such as Broker Activation, Broker Statistics, and Broker Transport that can be used to monitor activity and diagnose issues with activation and message transmission. Service Broker includes multiple catalog views that can be used to return information useful to troubleshooting Service Broker message actions.

Implement a Microsoft SQL Server 2008 Database

11-27

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Using Service Broker

Exercise 1: Creating Service Broker Objects


Scenario
The Marketing department at Adventure Works wants to send a welcome e-mail message to new customers who register on the companys Web site. To minimize the impact to the sites scalability, the senior database developer has decided to implement this functionality through a service that will be invoked asynchronously when a new user registers. You will create two Service Broker services: CustomerService will initiate a conversation with an EmailService, which will send an e-mail message to a newly registered customer.

11-28

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

When your work is complete, the senior database developer will modify the customer registration process to use the services you create. The senior database developer has provided the following specifications for the solution: The EmailService service must be configured to send e-mail messages by using Database Mail. The database administrator has provided a batch file named LabSetup.cmd to configure Database Mail on your development computer. You must enable Service Broker in the AdventureWorks database by using the ALTER DATABASE statement. To enable secure communication between services, you must also create a master key with a secure password in the AdventureWorks database. You must create schemas named EmailSvc and CustomerSvc in the AdventureWorks database, and then create a table named EmailLog in the EmailSvc schema. The EmailLog table should have the following definition.
CREATE TABLE EMailSvc.EmailLog ( Date datetime NOT NULL, [Event] nvarchar(50) NOT NULL, CustomerData xml )

Use the following details to create a message type that will be used to pass customer data to the EmailService service.
Property Name Validation Value //AW/EMail/CustomerDetails WELL_FORMED_XML

Use the following details to create a contract that will be supported by the EmailService service.
Property Name Message type Message Direction Value //AW/EMail/SendCustomerDetails //AW/EMail/CustomerDetails SENT BY INITIATOR

Implement a Microsoft SQL Server 2008 Database

11-29

MCT USE ONLY. STUDENT USE PROHIBITED

Use the following details to create a queue that will be used by the CustomerService service.
Property Name Queue status Value CustomerSvc.NewCustomerQueue ON

Use the following details to create a queue that will be used by the EmailService service. The queue should initially be disabled until you create the stored procedure that the queue will activate.
Property Name Queue status Value EMailSvc.NewCustomerEmailQueue OFF

Use the following details to create the CustomerService service.


Property Name Queue Value //AW/Sales/CustomerService CustomerSvc.NewCustomerQueue

Use the following details to create the EmailService service.


Property Name Queue Contract Value //AW/EMail/EmailService EMailSvc.NewCustomerEmailQueue //AW/EMail/SendCustomerDetails

In this exercise, you will configure Database Mail, enable Service Broker in the AdventureWorks2008 database, and then create the message type, contract, queue and services required for the solution. The main tasks for this exercise are as follows: 1. 2. Launch SQL Server Management Studio. Create the AW_ServiceBroker SQL Server Scripts project.

11-30

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

3. 4.

Configure the AdventureWorks database for Service Broker. Create the Service Broker objects required for the customer e-mail solution.

Task 1: Launch SQL Server Management Studio


Launch 6232A-NY-SQL-01 and log on to NY-SQL-01 as Student using the password Pa$$w0rd.

Task 2: Create the AW_ServiceBroker SQL Server Scripts project


1. 2. Open SQL Server Management Studio and connect to the default database engine. Create a new project named AW_ServiceBroker in the E:\MOD11\Labfiles\Starter folder.

Task 3: Configure the AdventureWorks database for Service Broker


1. 2. Create a new query named PrepareDatabase.sql in the AdventureWorks2008 database. In the PrepareDatabase.sql query you should enable Service Broker, create a master key encryption with the password 23987hxJ#KL95234nl0zBe, create a schema named EMailSvc, create another schema named CustomerSvc, create a table to log details of the customer e-mails sent, and set the database to multi-user mode.

Task 4: Create the Service Broker objects required for the customer email solution
1. 2. Create a new query named CreateServiceBrokerObjects.sql in the AdventureWorks2008 database. In the CreateServiceBrokerObjects.sql query you should create message types, create contracts, create queues, and create services based on the information provided in the scenario section of this exercise.

Implement a Microsoft SQL Server 2008 Database

11-31

MCT USE ONLY. STUDENT USE PROHIBITED

Results: After this exercise, you should have created the AW_ServiceBroker SQL Server Scripts project. In addition, you should have configured the AdventureWorks database for Service Broker and then created the Service Broker objects required for the customer e-mail solution.

11-32

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Implementing the Initiating Service


Scenario
Now you have to create a stored procedure that sends messages from the CustomerService service to the EmailService service. The senior database developer has provided Transact-SQL scripts to create the CustomerSvc.uspEmailNewCustomer stored procedure used by the services. In this exercise, you will add an existing query file to the project and execute the code in it. This code creates a stored procedure that sends messages from the CustomerService service to the EmailService service. The main tasks for this exercise are as follows: 1 2. Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project. Implement the CustomerService service.

Task 1: Add the CreateEmailNewCustomerSP.sql query file to the


AW_ServiceBroker project
1. 2. Use the Add Existing Item option to add an item to the project. Add the CreateEmailNewCustomerSP.sql query file in the E:\MOD11\Labfiles\Starter folder to the project.

Task 2: Implement the CustomerService service


1. 2. Execute the CreateEmailNewCustomerSP.sql query. Verify that the CustomerSvc.uspEmailNewCustomer stored procedure is listed under the Stored Procedures list of the AdventureWorks2008 database.
Results: After this exercise, you should have created the CustomerSvc.uspEmailNewCustomer stored procedure used by the service.

Implement a Microsoft SQL Server 2008 Database

11-33

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Implementing the Target Service


Scenario
Now you have to create a stored procedure that receives and processes messages in the EmailService service. The senior database developer has provided TransactSQL scripts to create the EMailSvc.uspSendCustomerEmail stored procedure used by the services. After you have created the EMailSvc.uspSendCustomerEmail stored procedure, you must alter the queue used by the EmailService service to make it activate the EMailSvc.uspSendCustomerEmail stored procedure whenever a message is received. Use the following settings.
Property Name Queue status Activation status Procedure name Maximum readers Execute as Value EMailSvc.NewCustomerEmailQueue ON ON AdventureWorks.EMailSvc.uspSendCustomerEmail 5 OWNER

In this exercise, you will add an existing query file to the project and execute the code it contains. This code creates a stored procedure that receives and processes messages in the EmailService service. The main tasks for this exercise are as follows: 1. 2. 3. 4. Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project. Implement the EmailService service. Configure the target service for automatic activation. Test the EmailService service.

11-34

Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Task 1: Add the CreateSendEmailSP.sql query file to the


AW_ServiceBroker project
1. 2. Use the Add Existing Item option to add an item to the project. Add the CreateSendEmailSP.sql query file in the E:\MOD11\Labfiles\Starter folder to the project.

Task 2: Implement the EmailService service


1. 2. Execute the CreateSendEmailSP.sql query. Verify that the EMailSvc.uspSendCustomerEmail stored procedure is listed under the Stored Procedures list of the AdventureWorks2008 database.

Task 3: Configure the target service for automatic activation


1. 2. Create a new query named AlterServiceBrokerQueue.sql. In the query window, write a T-SQL statement to make the EMailSvc.NewCustomerEmailQueue queue activate the EMailSvc.uspSendCustomerEmail stored procedure using the settings provided in the scenario. Execute the query.

3.

Task 4: Test the EmailService service


1. 2. 3. Use the Add Existing Item option to add an item to the project. Add the TestEmailService.sql query file in the E:\MOD11\Labfiles\Starter folder to the project. Execute the query.
Results: After this exercise, you should have created a stored procedure that receives and processes messages in the EmailService service. You should have also tested the EmailService service.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Implement a Microsoft SQL Server 2008 Database

11-35

MCT USE ONLY. STUDENT USE PROHIBITED

Module Review and Takeaways

Review Questions
1. 2. 3. What does Service Broker security rely on and why? How can you ensure that message delivery is correctly supported? How can you access SQL Trace to monitor Service Broker events?

MCT USE ONLY. STUDENT USE PROHIBITED

Lab: Creating Databases and Database Files

L1-1

MCT USE ONLY. STUDENT USE PROHIBITED

Module 1: Creating Databases and Database Files

Lab: Creating Databases and Database Files


Exercise 1: Creating a Database
Task 1: Create a SQL Server Management Studio Scripts project
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, verify that Server type is set to Database Engine and Server name is set to NY-SQL-01, and then click Connect. Maximize Microsoft SQL Server Management Studio. In Object Explorer expand NY-SQL-01, right-click Databases, and then click New Database. The New Database window appears. Maximize the window. On the General page, in the Database name field, enter AW_IT_Assets. In the Database files pane, click the AW_IT_Assets logical name, enter AW_IT_Assets_Data1, and then press ENTER.

10. Click Add. A new database file is added to the Database files pane. 11. Click the logical name cell of the new database file, enter AW_IT_Assets_Data2, and then press ENTER. 12. Click the cell labeled PRIMARY at the intersection of the AW_IT_Assets_Data2 row and the Filegroup column, and then select <new filegroup> from the drop-down menu. 13. The New Filegroup for AW_IT_Assets dialog box appears. Enter SECONDARY in the Name field, select Default, and then click OK. 14. Enter 20 in the Initial Size column of the AW_IT_Assets_Data1 row.

L1-2

Module 1: Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

15. Enter 5 in the Initial Size column of the AW_IT_Assets_log row. 16. Enter 20 in the Initial Size column of the AW_IT_Assets_Data2 row. 17. Click () in the Autogrowth column of the AW_IT_Assets_Data1 row and the Change Autogrowth for AW_IT_Assets_Data1 dialog box appears. 18. Clear the Enable Autogrowth check box and then click OK. 19. Click () in the Autogrowth column of the AW_IT_Assets_log row and the Change Autogrowth for AW_IT_Assets_log dialog box appears. 20. Clear the Enable Autogrowth check box and then click OK. 21. Click () in the Autogrowth column of the AW_IT_Assets_Data2 row and the Change Autogrowth for AW_IT_Assets_Data2 dialog box appears. 22. Clear the Enable Autogrowth check box and then click OK. 23. Click () in the Path column of the AW_IT_Assets_Data1 row and the Locate Folder windows appears. 24. Expand E:\MOD01\, select the Labfiles folder, and then click OK. 25. Click () in the Path column of the AW_IT_Assets_log row and the Locate Folder windows appears. 26. Expand E:\MOD01\, select the Labfiles folder, and then click OK. 27. Click () in the Path column of the AW_IT_Assets_Data2 row and the Locate Folder windows appears. 28. Expand E:\MOD01\, select the Labfiles folder, and then click OK. 29. In the Select a page pane of the New Database window, click Options. 30. Click False in the Auto Close row of the Automatic options group and select True from the drop-down menu. 31. Click False in the Auto Shrink row of the Automatic options group and select True from the drop-down menu. 32. Click the down arrow next to Script at the top of the New Database window and select Script Action to File. 33. In the Save As dialog box, browse to E:\MOD01\Labfiles, enter AW_IT_Assets_DBScript in the File name field, and then click Save. 34. Close the New Database window.

Lab: Creating Databases and Database Files

L1-3

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create a new database by executing a SQL Server Management


Studio Scripts project
1. 2. 3. In Microsoft SQL Server Management Studio, click File, point to Open, and then click File. The Open File dialog box appears. Browse to E:\MOD01\Labfiles, select AW_IT_Assets_DBScript, and then click Open. Click Execute on the SQL Editor toolbar.

Note: The query may take several minutes to execute successfully. Once the status bar at the bottom of the query window displays FileGroup Property default has been set, move on to step 4.

4. 5. 6. 7.

Right-click NY-SQL-01 | Databases in Object Explorer and then click Refresh. Expand NY-SQL-01 | Databases. The AW_IT_Assets database has been added to the Databases folder. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created a new database with the appropriate options and filegroups and created a SQL Server Management Studio Scripts project.

Exercise 2: Creating a Schema


Task 1: Create a new database user
1. 2. In SQL Server Management Studio expand NY-SQL-01 | Databases | AW_IT_Assets | Security, right-click Users, and then click New User. In the Database User window, enter Katie in the User name field and NYSQL-01\Katie in the Login name field, and then click OK.

L1-4

Module 1: Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create a schema and assign ownership to a user


1. 2. Click New Query on the Standard toolbar. In the new, blank query window, type the following T-SQL statement:
CREATE SCHEMA TechSupport AUTHORIZATION Katie CREATE TABLE Hardware (source int, cost int, partnumber int) GRANT SELECT TO Katie; GO

3. 4.

On the toolbar, click Execute. Close the query editor without saving the query.

Task 3: Create a schema and assign ownership to a user


1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'TechSupport'; GO

3. 4. 5.

On the toolbar, click Execute. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created a schema and assigned ownership to a user. You should have also displayed ownership of the newly created schema.

Lab: Creating Databases and Database Files

L1-5

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating a Database Snapshot


Task 1: Create a database snapshot
1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE DATABASE AW_IT_Assets_Snapshot1 ON ( NAME = AW_IT_Assets_Data1, FILENAME = 'E:\MOD01\Labfiles\Snapshots\AW_IT_Assets_Data1.ss' ), ( NAME = AW_IT_Assets_Data2, FILENAME = E:\MOD01\Labfiles\Snapshots\AW_IT_Assets_Data2.ss ) AS SNAPSHOT OF AW_IT_Assets; GO

3. 4. 5. 6.

On the toolbar, click Execute. Close the query editor without saving the query. In Object Explorer, right-click NY-SQL-01 | Databases, and then click Refresh. Expand NY-SQL-01 | Databases | Database Snapshots and review the new database snapshot named AW_IT_Assets_Snapshot1.

Task 2: Alter the database


1. 2. 3. 4. Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables, right-click the TechSupport.Hardware table, and then click Delete. The Delete Object window appears. Click OK. Expand NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas, right-click the TechSupport schema, and then click Delete. The Delete Object window appears. Click OK.

L1-6

Module 1: Creating Databases and Database Files

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Revert the database to the previously created database


snapshot
1. 2. In Object Explorer, expand NY-SQL-01 | Databases, right-click the AW_IT_Assets database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
USE master; RESTORE DATABASE AW_IT_Assets FROM DATABASE_SNAPSHOT = AW_IT_Assets_Snapshot1'; GO

3. 4. 5.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases, and then click Refresh. Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables and NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas and note that both the TechSupport.Hardware table and the TechSupport schema have been restored. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have created a database snapshot, altered the database, and then reverted the database to the database snapshot.

6.

Lab: Creating Data Types and Tables

L2-7

MCT USE ONLY. STUDENT USE PROHIBITED

Module 2: Creating Data Types and Tables

Lab: Creating Data Types and Tables


Exercise 1: Creating Data Types
Task 1: Create a data types based on the nvarchar system-supplied
data type
1. 2. 3. 4. 5. 6. 7. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, verify that Server type is set to Database Engine and Server name is set to NY-SQL-01, and then click Connect. Maximize Microsoft SQL Server Management Studio. Expand NY-SQL-01 | Databases, right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TYPE ShortDescription FROM nvarchar(10) NOT NULL;

8. 9.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Programmability | Types | User-Defined Data Types, click Refresh, and then expand User-Defined Data Types to view the new dbo.ShortDescription data type.

10. Close the query editor without saving the query.

L2-8

Module 2: Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create a data type based on the decimal system-supplied data


type
1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TYPE CashValue FROM decimal(8,2) NOT NULL;

3. 4.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Programmability | Types | User-Defined Data Types, click Refresh, and then expand User-Defined Data Types to view the new dbo.CashValue data type. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully created a new data type based on the nvarchar system-supplied data type. You should have also successfully created a new data type based on the decimal system-supplied data type.

5. 6.

Lab: Creating Data Types and Tables

L2-9

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Using New Date and Time Data Types


Task 1: Obtain date and time formatting using T-SQL
1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
SELECT CAST('2007-05-08 12:35:29.1234567 'time' ,CAST('2007-05-08 12:35:29.1234567 ,CAST('2007-05-08 12:35:29.123' AS 'smalldatetime' ,CAST('2007-05-08 12:35:29.123' AS ,CAST('2007-05-08 12:35:29.1234567 'datetime2' ,CAST('2007-05-08 12:35:29.1234567 datetimeoffset(7)) AS 'datetimeoffset'; +12:15' AS time(7)) AS +12:15' AS date) AS 'date' smalldatetime) AS datetime) AS 'datetime' +12:15' AS datetime2(7)) AS +12:15' AS

3. 4.

On the toolbar, click Execute and then review the results. Close the query editor without saving the query.

Task 2: Convert sample data into new data type formats using T-SQL
1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
SELECT '2006-04-04T15:50:59.997' AS UnconvertedText, CAST('2006-04-04T15:50:59.997' AS datetime) AS UsingCast, CONVERT(date, '2006-04-04T15:50:59.997', 126) AS UsingConvertDate, CONVERT(time, 2006-04-04T15:50:59.997', 126) AS UsingConvertTime; GO

L2-10

Module 2: Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

3. 4. 5.

On the toolbar, click Execute and then review the results. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully obtained date and time formatting using T-SQL and then converted sample data into the date and time formats using T-SQL.

Exercise 3: Creating Tables


Task 1: Create a table named ReturnedGoods
1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TABLE ReturnedGoods ( ReturnID int identity, ProductID int, CustomerID int, ReturnDate datetime, ReturnReason ShortDescription NULL ); GO

3. 4.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables, click Refresh, and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new ReturnedGoods table. Close the query editor without saving the query.

5.

Task 2: Create a table named Refunds


1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TABLE Refunds ( RefundID int identity, ReturnID int, Amount CashValue ); GO

3.

On the toolbar, click Execute.

Lab: Creating Data Types and Tables

L2-11

MCT USE ONLY. STUDENT USE PROHIBITED

4.

Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables, click Refresh, and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new Refunds table. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created a table named ReturnedGoods, created a table named Refunds, and followed all provided specifications.

5. 6.

Exercise 4: Creating Partitioned Tables


Task 1: Limit result sets by using the INTERSECT clause with the
SELECT statement
1. 2. 3. 4. On the SQL Server Management Studio toolbar, click File, point to Open, and then click File. Browse to E:\MOD02\Labfiles\Scripts, select the file named partition_prep.sql, and then click Open. On the toolbar, click Execute. Close the query editor without saving the query.

L2-12

Module 2: Creating Data Types and Tables

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create a partitioned table named ReturnsArchive


1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE PARTITION FUNCTION myRangePF1 (int) AS RANGE LEFT FOR VALUES (1, 100, 1000); GO CREATE PARTITION SCHEME myRangePS1 AS PARTITION myRangePF1 TO (Test1FG, Test2FG, Test3FG, Test4FG); GO CREATE TABLE ReturnsArchive (ReturnID int identity, ProductID int, CustomerID int, ReturnDate datetime, ReturnReason ShortDescription NULL ) ON myRangePS1 (ReturnID); GO

3. 4.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables, click Refresh, and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new ReturnsArchive table. Close the query editor without saving the query.

5.

Task 3: Review the partitioning implementation


1. 2. 3. 4. 5. In Object Explorer, right-click the AdventureWorksDW2008 database, and then click Refresh. Expand NY-SQL-01 | AdventureWorksDW2008 | Tables, right-click the dbo.ReturnsArchive table, and then click Properties. In the Table Properties window, click Storage on the left. Review the Compression, Filegroups, and Partitioning information in the right pane of the Table Properties window, and then click OK. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have successfully prepared the database for partitioning, created a partitioned table named ReturnsArchive according to the specifications provided, and then reviewed the partitioning changes.

Lab: Creating and Optimizing Indexes

L3-13

MCT USE ONLY. STUDENT USE PROHIBITED

Module 3: Creating and Optimizing Indexes

Lab: Creating and Optimizing Indexes


Exercise 1: Creating Indexes
Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as
Student
1. 2. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project


1. 2. 3. 4. 5. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, click Connect. On the File menu, click New, and then click Project. In the New Project dialog box, in the Name field, type AW_Indexes. Change the Location field to E:\MOD03\Labfiles\Starter. Clear the Create directory for solution check box, and then click OK.

L3-14

Module 3: Creating and Optimizing Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create the Ix_Product_Supply_Chain index


1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type CreateIndex.sql, and then press ENTER. In the query window, type the following Transact-SQL code to create the Ix_Product_Supply_Chain index:
USE AdventureWorks2008 CREATE UNIQUE NONCLUSTERED INDEX Ix_Product_Supply_Chain ON Production.Product (ProductNumber, Color, ReorderPoint, SafetyStockLevel) INCLUDE (DaysToManufacture) WITH (ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 90, PAD_INDEX = ON)

4. 5. 6. 7. 8. 9.

On the toolbar, click Execute. On the File menu, click Save All. If Object Explorer is not visible, on the View menu, click Object Explorer. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Tables. Expand Production.Product, expand Indexes, and then verify that the Ix_Product_Supply_Chain index is listed. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully created a SQL Server Scripts project and created the Ix_Product_Supply_Chain index.

Lab: Creating and Optimizing Indexes

L3-15

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Optimizing Indexes


Task 1: Add the sample products to the database
1. 2. 3. 4. In Microsoft SQL Server Management Studio, on the File menu, click Open, and then click File. In the Open File dialog box, browse to the E:\MOD03\Labfiles\Starter folder, click the aw2008sampleproductadd.sql file, and then click Open. In Microsoft SQL Server Management Studio, on the toolbar, click Execute. Wait for the query to finish executing before continuing to the next task. Note that there may be some duplicate key errors. You can ignore this.

Task 2: Reorganize AK_Product_ProductNumber


1. 2. 3. 4. 5. 6. 7. 8. 9. In Object Explorer, make sure that Databases | AdventureWorks2008 | Tables | Production.Product | Indexes is still expanded. Right-click AK_Product_ProductNumber (Unique, Non-Clustered), and then click Properties. In the Index Properties AK_Product_ProductNumber dialog box, in the Select a page pane, click Fragmentation. In the details pane, under Fragmentation, notice that Total Fragmentation is 66.67%. Click Cancel. In Object Explorer, right-click AK_Product_ProductNumber (Unique, NonClustered), and then click Reorganize. In the Reorganize Indexes dialog box, click OK. In Object Explorer, right-click AK_Product_ProductNumber (Unique, NonClustered), and then click Properties. In the Index Properties AK_Product_ProductNumber dialog box, in the Select a page pane, click Fragmentation.

10. In the details pane, notice that Total fragmentation has changed to 50.00%. 11. Click Cancel.

L3-16

Module 3: Creating and Optimizing Indexes

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Rebuild AK_Product_Name


1. 2. 3. 4. 5. 6. 7. 8. 9. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Properties. In the Index Properties AK_Product_Name dialog box, in the Select a page pane, click Fragmentation. In the details pane, notice that Total fragmentation is 80.00%. Click Cancel. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Rebuild. In the Rebuild Indexes dialog box, click OK. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Properties. In the Index Properties AK_Product_Name dialog box, in the Select a page pane, click Fragmentation. In the details pane, notice that Total fragmentation is now 25.00%.

10. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.
Results: After this exercise, you should have successfully optimized the Production.Product table indexes using both reorganize and rebuild.

Lab: Implementing Data Integrity by Using Constraints

L4-17

MCT USE ONLY. STUDENT USE PROHIBITED

Module 4: Implementing Data Integrity by Using Constraints

Lab: Implementing Data Integrity by Using Constraints


Exercise 1: Creating Constraints
Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as
Student
1. 2. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project


1. 2. 3. 4. 5. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, click Connect. On the File menu, click New, and then click Project. In the New Project dialog box, in the Name field, type AW_DataIntegrity. Change the Location field to E:\MOD04\Labfiles\Starter. Clear the Create directory for solution check box, and then click OK.

L4-18

Module 4: Implementing Data Integrity by Using Constraints

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create the JobCandidateHistory table and constraints


1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type TableAndContraints.sql, and then press ENTER. In the query window, type the following Transact-SQL code to create the JobCandidateHistory table:
USE [AdventureWorks2008] GO CREATE TABLE [HumanResources].[JobCandidateHistory]( [JobCandidateID] [int] NOT NULL UNIQUE, [Rating] [int] NOT NULL CONSTRAINT [DF_JobCandidateHistory_Rating] Default (5), [RejectedDate] [datetime] NOT NULL, [BusinessEntityID] [int] NULL, CONSTRAINT [FK_JobCandidateHistory_BusinessEntity_BusinessEntityID] FOREIGN KEY (BusinessEntityID) REFERENCES [Person].[BusinessEntity] (BusinessEntityID), CONSTRAINT [CK_JobCandidateHistory_Rating] CHECK ([Rating]>=0 AND [Rating]<=10) ) ON [PRIMARY]

4. 5. 6. 7.

On the toolbar, click Execute. On the File menu, click Save All. If Object Explorer is not visible, on the View menu, click Object Explorer. In Object Explorer, expand Databases, expand AdventureWorks2008, expand Tables, and then verify that the HumanResources.JobCandidateHistory table is listed. You may need to rightclick Tables, and then click Refresh to see the new table. In Object Explorer, expand the HumanResources.JobCandidateHistory table. In the HumanResources.JobCandidateHistory table, expand the Columns, Keys, Indexes, and Constraints folders, and then verify that the necessary constraints have been implemented.

8. 9.

Lab: Implementing Data Integrity by Using Constraints

L4-19

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: Test the JobCandidateHistory table and constraints


1. 2. 3. In SQL Server Management Studio, on the File menu, click Open, and then click File. In the Open File dialog box, browse to E:\MOD04\Labfiles\Starter, click TestConstraints.sql, and then click Open. Below the comment This should fail, select the code, and then on the toolbar, click Execute. The INSERT operation should fail, because the Rating value conflicts with the CHECK constraint. Below the comment This should succeed, select the code, and then on the toolbar, click Execute. The INSERT operation should succeed. Keep SQL Server Management Studio open to use in the next exercise.
Results: After this exercise, you should have successfully created a SQL Server Scripts project, created the HumanResources.JobCandidateHistory table, and tested the constraints.

4. 5.

Exercise 2: Disabling Constraints


Task 1: Insert multiple rows into the JobCandidateHistory table
1. 2. 3. 4. In Microsoft SQL Server Management Studio, on the File menu, click Open, and then click File. In the Open File dialog box, browse to the E:\MOD04\Labfiles\Starter folder, click the InsertTestData.sql file, and then click Open. On the toolbar, click the Include Client Statistics button, and then click Execute. Click the Client Statistics tab, and verify that the Time Statistics have been recorded.

Task 2: Disable constraints on the JobCandidateHistory table


1. 2. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type Constraints.sql, and then press ENTER.

L4-20

Module 4: Implementing Data Integrity by Using Constraints

MCT USE ONLY. STUDENT USE PROHIBITED

3.

In the query window, type the following Transact-SQL code:


USE [AdventureWorks2008] GO ALTER TABLE HumanResources.JobCandidateHistory NOCHECK CONSTRAINT [CK_JobCandidateHistory_Rating] GO

4. 5. 6. 7. 8. 9.

On the toolbar, click Execute. Verify that the commands completed successfully. On the File menu, click Save All. Switch to the InsertTestData.sql query window. On the toolbar, click Execute. Click the Client Statistics tab, and then compare the Time Statistics with the previous trial. Notice that Trial 2 executes more quickly.

Task 3: Enable constraints on the JobCandidateHistory table


1. 2. Switch to the Constraints.sql query window. In the query window, type the following Transact-SQL code below the existing statements:
ALTER TABLE HumanResources.JobCandidateHistory CHECK CONSTRAINT [CK_JobCandidateHistory_Rating] GO

3. 4. 5. 6.

Select the new statements, and then on the toolbar, click Execute. Verify that the commands completed successfully. On the File menu, click Save All. Keep SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully compared performance results with constraints enabled and disabled.

Lab: Implementing Data Integrity by Using Constraints

L4-21

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating Triggers


Task 1: Create the dJobCandidate trigger
1. 2. 3. In SQL Server Management Studio, on the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type Trigger.sql, and then press ENTER. In the query window, type the following Transact-SQL code to create the dJobCandidate trigger on the HumanResources.JobCandidate table:
USE AdventureWorks2008 GO CREATE TRIGGER [dJobCandidate] ON [HumanResources].[JobCandidate] AFTER DELETE AS BEGIN SET NOCOUNT ON; INSERT INTO [HumanResources].[JobCandidateHistory] (JobCandidateID, RejectedDate) SELECT JobCandidateID, getdate() FROM deleted END;

4. 5. 6. 7.

On the toolbar, click Execute. On the File menu, click Save All. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Tables. Right-click Tables, and then click Refresh. Expand the HumanResources.JobCandidate table, expand Triggers, and then verify that the dJobCandidate trigger is listed.

L4-22

Module 4: Implementing Data Integrity by Using Constraints

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Test the dJobCandidate trigger


1. 2. 3. 4. On the File menu, click Open, and then click File. In the Open File dialog box, browse to the E:\MOD04\Labfiles\Starter folder, click the TestTrigger.sql query file, and then click Open. On the toolbar, click Execute to execute the query script. In the results pane, verify that the record deleted from the HumanResources.JobCandidate table is inserted into the HumanResources.JobCandidateHistory table. The record should contain the default value of 5 for Rating, and the current date for RejectedDate. Click the Messages tab, and then verify that there are two (1 row(s) affected) messages indicating that a row was deleted from one table and inserted into another. Close SQL Server Management Studio, and then shutdown the virtual machine without saving changes to reset it for the next Lab.
Results: After this exercise, you should have successfully created and tested the dJobCandidate trigger.

5.

6.

Lab: Using XML

L5-23

MCT USE ONLY. STUDENT USE PROHIBITED

Module 5: Using XML

Lab: Using XML


Exercise 1: Mapping Relational Data and XML
Task 1: Create the FOR XML queries to return the order manifest
documents
1. 2. 3. 4. 5. 6. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. If the Connect to Server dialog box appears, click Connect. On the File menu, point to Open, and then click Project/Solution. The Open Project dialog box appears. Browse to the E:\Mod05\Labfiles\Starter folder, click the XML.ssmssln solution, and then click Open. a. b. c. 7. 8. 9. If the Connect to Server dialog box appears, click Connect. If Solution Explorer is not visible, on the View menu, click Solution Explorer. If necessary, in the Solution Explorer pane, expand XML | Queries.

In the Solution Explorer, double-click the FORXML.sql query to open it. Switch to the FORXML query. Examine the query and note that it retrieves data from the Sales.SalesOrderHeader and Sales.SalesOrderDetail tables in the AdventureWorks2008 database.

10. On the toolbar, click Execute. 11. Examine the Results and Messages boxes and verify that the script completed without any errors.

L5-24

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

12. Modify the SELECT statement to include the FOR XML clause and return attribute-centric XML by using AUTO mode, as shown in the following Transact-SQL example:
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, Item.ProductID, Item.OrderQty FROM Sales.SalesOrderHeader SalesOrder JOIN Sales.SalesOrderDetail Item ON SalesOrder.SalesOrderID = Item.SalesOrderID WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

13. On the toolbar, click Execute. 14. Examine the Results and Messages boxes and verify that the script completed without any errors. 15. Review the query results. 16. In the query results, click the returned XML to view it in the XML editor. 17. It should be similar to the example shown in the following output:
<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item ProductID="776" OrderQty="1" /> <Item ProductID="777" OrderQty="3" /> <Item ProductID="778" OrderQty="1" /> <Item ProductID="771" OrderQty="1" /> <!-- more items here --> </SalesOrder>

18. On the File menu, click Close to close the XML editor.

Lab: Using XML

L5-25

MCT USE ONLY. STUDENT USE PROHIBITED

19. Modify the SELECT statement, as shown in the following Transact-SQL example:
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, (SELECT Item.ProductID, Item.OrderQty FROM Sales.SalesOrderDetail Item WHERE SalesOrder.SalesOrderID = Item.SalesOrderID FOR XML AUTO, ELEMENTS, TYPE) FROM Sales.SalesOrderHeader SalesOrder WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

20. On the toolbar, click Execute. 21. Examine the Results and Messages boxes and verify that the script completed without any errors. 22. In the query results, click the returned XML to view it in the XML editor. 23. Verify that the query returned the required XML format, as shown in the following sample output:
<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item> <ProductID>776</ProductID> <OrderQty>1</OrderQty> </Item> <Item> <ProductID>777</ProductID> <OrderQty>3</OrderQty> </Item> <Item> <ProductID>778</ProductID> <OrderQty>1</OrderQty> </Item> <!-- more items here --> </SalesOrder>

24. On the File menu, click Close to close the XML editor. 25. On the File menu, click Save FORXML.sql. 26. Keep the SQL Server Management Studio solution open. You will use it in the next part of this exercise.

L5-26

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Use the OPENXML function to insert the XML data into the
tables
1. 2. In the Solution Explorer pane, double-click the OPENXML.sql query to open it. Examine the query and note that it provides a sample XML document that contains a sales order from a customer for two items. The remainder of the file is incomplete. Locate the comment Call stored procedure to create the memory tree, and then add a call to the sp_xml_preparedocument stored procedure, as shown in the following example:
EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc

3.

4.

Locate the comment Add OPENXML function for SalesOrderHeader table INSERT, and then add an OPENXML function to retrieve the relevant attributes from the SalesOrder node, as shown in the following example:
OPENXML(@docHandle, '/SalesOrder', 1) WITH ( CustomerID int, OrderDate datetime, DueDate datetime, AccountNumber nvarchar(15), SalesPersonID int, BillToAddressID int, ShipToAddressID int, ShipMethodID int, SubTotal money, TaxAmt money)

5.

Locate the comment Add OPENXML function for SalesOrderDetail table INSERT, and then add an OPENXML function to retrieve the relevant subelements from the Item node, as shown in the following example:
OPENXML(@docHandle, '/SalesOrder/Item', 2) WITH ( OrderQty int, ProductID int, UnitPrice money)

Lab: Using XML

L5-27

MCT USE ONLY. STUDENT USE PROHIBITED

6.

Locate the comment Call stored procedure to clean up memory tree, and then add a call to the sp_xml_removedocument stored procedure, as shown in the following example:
EXEC sp_xml_removedocument @docHandle

7. 8. 9.

On the toolbar, click Execute. Examine the Results and Messages boxes and verify that the script completed without any errors. Review the results, and confirm that a new record was added to the SalesOrderHeader table and two records were added to the SalesOrderDetail table.

10. On the File menu, click Save All. 11. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you should have modified the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML.

Exercise 2: Storing XML Natively in the Database


Task 1: Create a SQL Server Scripts project in SQL Server Management
Studio
1. 2. 3. 4. 5. 6. 7. On the File menu, point to New, and then click Project. The New Project dialog box appears. In the Templates box, makes sure SQL Server Scripts is highlighted. In the Name field, type Job Candidate History. In the Location field, type E:\Mod05\Labfiles\Starter. Click OK. In the Solution Explorer, right-click Connections, and then click New Connection. The Connect to Server dialog box appears. Click OK.

L5-28

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create the HumanResources.JobCandidateHistory table


1. 2. 3. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. In the query pane, type the following Transact-SQL code to create a table named HumanResources.JobCandidateHistory in the AdventureWorks2008 database:
USE AdventureWorks2008 GO CREATE TABLE HumanResources.JobCandidateHistory ( JobCandidateID int IDENTITY PRIMARY KEY, BusinessEntityID int NULL, Rating int NOT NULL Default (5), RejectedDate datetime NOT NULL, NationalIDNumber nvarchar (15) NOT NULL, ModifiedDate DateTime, Resume xml ) GO

4. 5. 6. 7. 8. 9.

On the toolbar, click Execute. If the Connect to Server dialog box appears, click Connect. Examine Messages box and verify that the script completed without any errors. On the File menu, click Save SQLQuery1.sql As. The Save File As dialog box appears. In the File name field, type CreateJobCandidateHistoryTable.sql, and then click Save. In Object Explorer, expand Databases | AdventureWorks2008 | Tables.

10. Verify that the HumanResources.JobCandidateHistory table is listed. 11. In Object Explorer, expand the HumanResources.JobCandidateHistory table. 12. In the HumanResources.JobCandidateHistory table, expand Columns. 13. Verify that the necessary columns have been successfully created.

Lab: Using XML

L5-29

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create a new query file


1. 2. 3. 4. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery2.sql As. The Save File As dialog box appears. In the File name field, type XMLSchema.sql, and then click Save.

Task 4: Create an XML schema collection named


HumanResources.HistoricResumeSchemaCollection
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click XML Files. Navigate to the E:\Mod05\Labfiles\Starter folder. Click HistoricResumeSchema.xml, and then click Add. In the details pane, examine the new schema definition. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. Navigate to the E:\Mod05\Labfiles\Starter folder. Click CreateXMLSchema.sql, and then click Add.

10. If the Connect to Server dialog box appears, click Connect.

L5-30

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

11. Examine the code that creates the new XML Schema. It should be identical to the code listed below:
USE AdventureWorks2008 GO CREATE XML SCHEMA COLLECTION HumanResources.HistoricResumeSchemaCollection AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:t="http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume" targetNamespace="http://schemas.microsoft.com/sqlserver/2004/07/adv enture-works/Resume" elementFormDefault="qualified"> <xsd:element name="Address" type="t:AddressType" /> <xsd:element name="Education" type="t:EducationType" /> <xsd:element name="Employment" type="t:EmploymentType" /> <xsd:element name="Location" type="t:LocationType" /> <xsd:element name="Name" type="t:NameType" /> <xsd:element name="Resume" type="t:ResumeType" /> <xsd:element name="Telephone" type="t:TelephoneType" /> <xsd:complexType name="AddressType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Addr.Type" type="xsd:string" /> <xsd:element name="Addr.OrgName" type="xsd:string" /> <xsd:element name="Addr.Street" type="xsd:string" maxOccurs="unbounded" /> <xsd:element name="Addr.Location"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Location" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> <xsd:element name="Addr.PostalCode" type="xsd:string" /> <xsd:element name="Addr.Telephone" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence>

Lab: Using XML

L5-31

MCT USE ONLY. STUDENT USE PROHIBITED

(continued)
<xsd:element ref="t:Telephone" maxOccurs="unbounded" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="EducationType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Edu.Level" type="xsd:string" /> <xsd:element name="Edu.StartDate" type="xsd:date" /> <xsd:element name="Edu.EndDate" type="xsd:date" /> <xsd:element name="Edu.Degree" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.Major" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.Minor" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.GPA" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.GPAAlternate" type="xsd:decimal" minOccurs="0" /> <xsd:element name="Edu.GPAScale" type="xsd:decimal" minOccurs="0" /> <xsd:element name="Edu.School" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.Location" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Location" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType>

L5-32

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

(continued)
<xsd:complexType name="EmploymentType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Emp.StartDate" type="xsd:date" minOccurs="0" /> <xsd:element name="Emp.EndDate" type="xsd:date" minOccurs="0" /> <xsd:element name="Emp.OrgName" type="xsd:string" /> <xsd:element name="Emp.JobTitle" type="xsd:string" /> <xsd:element name="Emp.Responsibility" type="xsd:string" /> <xsd:element name="Emp.FunctionCategory" type="xsd:string" minOccurs="0" /> <xsd:element name="Emp.IndustryCategory" type="xsd:string" minOccurs="0" /> <xsd:element name="Emp.Location" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Location" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="LocationType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Loc.CountryRegion" type="xsd:string" /> <xsd:element name="Loc.State" type="xsd:string" minOccurs="0" /> <xsd:element name="Loc.City" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType>

Lab: Using XML

L5-33

MCT USE ONLY. STUDENT USE PROHIBITED

(continued)
<xsd:complexType name="NameType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Name.Prefix" type="xsd:string" minOccurs="0" /> <xsd:element name="Name.First" type="xsd:string" /> <xsd:element name="Name.Middle" type="xsd:string" minOccurs="0" /> <xsd:element name="Name.Last" type="xsd:string" /> <xsd:element name="Name.Suffix" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="ResumeType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Name" /> <xsd:element name="Skills" type="xsd:string" minOccurs="0" /> <xsd:element ref="t:Employment" maxOccurs="unbounded" /> <xsd:element ref="t:Education" maxOccurs="unbounded" /> <xsd:element ref="t:Address" maxOccurs="unbounded" /> <xsd:element ref="t:Telephone" minOccurs="0" /> <xsd:element name="EMail" type="xsd:string" minOccurs="0" /> <xsd:element name="WebSite" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="TelephoneType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Tel.Type" type="xsd:anyType" minOccurs="0" /> <xsd:element name="Tel.IntlCode" type="xsd:int" minOccurs="0" /> <xsd:element name="Tel.AreaCode" type="xsd:int" minOccurs="0" /> <xsd:element name="Tel.Number" type="xsd:string" />

L5-34

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

(continued)
<xsd:element name="Tel.Extension" type="xsd:int" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:schema>' GO

12. On the toolbar, click Execute. 13. Examine Messages box and verify that the script completed without any errors.

Task 5: Apply the schema collection to the


JobCandidateHistory.Resume column
1. 2. 3. 4. 5. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery3.sql As. The Save File As dialog box appears. In the File name field, type AlterCandiateTable.sql, and then click Save. In the query window, enter the following code to alter the JobCandidateHistory table:
ALTER TABLE HumanResources.JobCandidateHistory ALTER COLUMN Resume xml (HumanResources.HistoricResumeSchemaCollection) GO

6. 7. 8. 9.

On the toolbar, click Execute. Examine Messages box and verify that the script completed without any errors. In Object Explorer, right-click AdventureWorks2008, and then click Refresh. In Object Explorer, expand Databases | AdventureWorks2008 | Tables | HumanResources.JobCandidateHistory | Columns.

10. Notice that the Resume column is now associated with the HumanResources.HistoricResumeSchemaCollection.

Lab: Using XML

L5-35

MCT USE ONLY. STUDENT USE PROHIBITED

Task 6: Test the HistoricResumeSchema XML schema


1. 2. 3. 4. 5. 6. 7. 8. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. Navigate to the E:\Mod05\Labfiles\Starter folder. Click TestXMLSchema.sql, and then click Add. If the Connect to Server dialog box appears, click Connect. In the details pane, below the comment This should fail, select the INSERT code. On the toolbar, click Execute. Examine the error message in the Messages pane. The INSERT operation fails because the Resume XML does not conform to the schema. 9. Below the comment This should succeed, select the code.

10. On the toolbar, click Execute. 11. Examine the Message box and verify that the script completed without any errors. The INSERT operation should succeed. 12. In the Solution Explorer pane, right-click Queries, and then click New Query. 13. If the Connect to Server dialog box appears, click Connect. 14. On the File menu, click Save SQLQuery4.sql As. 15. The Save File As dialog box appears. In the File name field, type SelectCandidates.sql, and then click Save.

L5-36

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

16. Type the following Transact-SQL code:


USE AdventureWorks2008 GO SELECT * FROM HumanResources.JobCandidateHistory GO

17. On the toolbar, click Execute. 18. Examine the Results and Messages boxes and verify that the script completed without any errors. 19. In the Results pane, in the first row, click the <Resume> field. 20. Examine the XML record to confirm that it is complete and accurate. 21. On the File menu, click Close to close the XML editor.

Task 7: Populate the HumanResources.JobCandidateHistory table with


additional sample data
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. Navigate to the E:\Mod05\Labfiles\Starter folder. Click AddCandidate.sql, and then click Add. If the Connect to Server dialog box appears, click Connect. On the toolbar, click Execute. Examine the Message box and verify that the script completed without any errors. In the Solution Explorer, double-click SelectCandidates.sql. On the toolbar, click Execute.

10. Examine the Results and Messages boxes and verify that the script completed without any errors. 11. In the Results pane, in the second row, click the <Resume> field. 12. Examine the xml record to confirm that it is accurate. 13. On the File menu, click Close to close the XML editor.

Lab: Using XML

L5-37

MCT USE ONLY. STUDENT USE PROHIBITED

14. On the File menu, click Save All. 15. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.

Note: This is the end of the first part of the module and the remaining exercises will come after the rest of the presentation.

Results: After this exercise, the student has created and applied an XML schema and stored XML natively in the database.

Exercise 3: Using XQuery with XML Methods


Task 1: Retrieve the resume elements
1. 2. 3. 4. 5. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery5.sql As. The Save File As dialog box appears. In the File name field, type xmlMethods.sql, and then click Save. In the query window, enter the following code to retrieve the resume elements:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT NationalIDNumber, Resume.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources.JobCandidateHistory GO

6. 7. 8.

On the toolbar, click Execute. Examine the Results and Messages boxes and verify that the script completed without any errors. Verify that the desired results are returned.

L5-38

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Retrieve the address for a specified candidate


1. Below the SELECT statement, type the following Transact-SQL code:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT Resume.value( '(/RES:Resume/RES:Address/RES:Addr.Street)[1]', 'nvarchar(100)') As ResumeAddress FROM HumanResources.JobCandidateHistory WHERE JobCandidateID = 2 GO

This retrieves a single resume address with a JobCandidateID of 2. 2. 3. Select the statements you just added, and then on the toolbar, click Execute. Verify that the desired results are returned.

Task 3: Update a candidate's address


1. Below the previous SELECT statement, type the following Transact-SQL code:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") UPDATE HumanResources.JobCandidateHistory SET Resume.modify('replace value of (/RES:Resume/RES:Address/RES:Addr.Street)[1] with "7194 Fourth St. Rockhampton"') WHERE JobCandidateID = 2 GO

2.

This updates the HumanResources.JobCandidateHistory table, setting the Address element value in the document for the record with a JobCandidateID of 2 to 7194 Fourth St. Rockhampton.

Lab: Using XML

L5-39

MCT USE ONLY. STUDENT USE PROHIBITED

3. 4.

Select the statements you just added, and then on the toolbar, click the Execute button. Examine the Messages box and verify that the script completed without any errors.

Task 4: Verify the updated candidate's address


1. 2. 3. 4. 5. Select the statements from Task 2. On the toolbar, click Execute. Verify that the desired results are returned as 7194 Fourth St. Rockhampton. On the File menu, click Save All. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you have used XQuery with XML methods to view the selected contents of an XML schema and modified an XML object.

Exercise 4: Create XML Indexes


Task 1: Create a new query file
1. 2. 3. 4. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery6.sql As. The Save File As dialog box appears. In the File name field, type CreateXMLIndexes.sql, and then click Save.

L5-40

Module 5: Using XML

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create XML indexes


1. In the query window, type the following code to create the primary XML index on the Diagram column of the Production.Illustration table:
USE AdventureWorks2008 GO SET ARITHABORT ON CREATE PRIMARY XML INDEX PXML_Illustration_Diagram ON Production.Illustration (Diagram) WITH (FILLFACTOR = 60, PAD_INDEX = ON)

2.

In the query window, below the existing code, type the following code to create the secondary path XML index on the Diagram column of the Production.Illustration table:
CREATE XML INDEX XMLPATH_Illustration_Diagram ON Production.Illustration (Diagram) USING XML INDEX PXML_Illustration_Diagram FOR PATH WITH (FILLFACTOR = 70, PAD_INDEX = OFF) GO

3. 4. 5. 6. 7. 8. 9.

On the toolbar, click Execute to execute the query. Examine the Messages box and verify that the script completed without any errors. On the File menu, click Save All. In the navigation pane, expand Databases | AdventureWorks2008 | Tables | Production.Illustration | Indexes. Verify that the new XML indexes are listed and are correct. Close SQL Server Management Studio. Turn off 6232A-NY-SQL-01 and delete changes.
Results: After this exercise, you have created XML indexes.

Lab: Implementing Views

L6-41

MCT USE ONLY. STUDENT USE PROHIBITED

Module 6: Implementing Views

Lab: Implementing Views


Exercise 1: Creating Views
Task 1: Create a SQL Server Scripts project
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Administrator using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. The Connect to Server dialog box appears. Click Connect. On the File menu, point to New, and then click Project. The New Project dialog box appears. In the Templates box, make sure SQL Server Scripts is highlighted. In the Name field, type AW_Views. In the Location field, type E:\Mod06\Labfiles\Starter. Clear the Create directory for solution check box.

10. Click OK. 11. In the Solution Explorer pane, right-click Queries, and then click New Query. 12. If the Connect to Server dialog box appears, click Connect. 13. On the File menu, click Save SQLQuery1.sql As. 14. The Save File As dialog box appears. In the File name field, type CreateEmployeeView.sql, and then click Save.

L6-42

Module 6: Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create the HumanResources.vEmployeeDetails view


1. In the query window, type the following Transact-SQL code to create the HumanResources.vEmployeeDetails view:
USE AdventureWorks2008 GO CREATE VIEW HumanResources.vEmployeeDetails WITH SCHEMABINDING AS SELECT e.BusinessEntityID ,c.Title ,c.FirstName ,c.MiddleName ,c.LastName ,c.Suffix ,e.JobTitle ,c.EmailPromotion ,a.AddressLine1 ,a.AddressLine2 ,a.City ,sp.Name AS StateProvinceName ,a.PostalCode ,cr.Name AS CountryRegionName ,c.AdditionalContactInfo FROM HumanResources.Employee e INNER JOIN Person.Person c ON c.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.BusinessEntityAddress ea ON e. BusinessEntityID = ea. BusinessEntityID INNER JOIN Person.Address a ON ea.AddressID = a.AddressID INNER JOIN Person.StateProvince sp ON sp.StateProvinceID = a.StateProvinceID INNER JOIN Person.CountryRegion cr ON cr.CountryRegionCode = sp.CountryRegionCode

2. 3. 4. 5. 6.

On the toolbar, click Execute. Examine Messages box and verify that the script completed without any errors. On the File menu, click Save All. In Object Explorer, expand Databases | AdventureWorks2008 | Views. Verify that the HumanResources.vEmployeeDetails view is listed.

Lab: Implementing Views

L6-43

MCT USE ONLY. STUDENT USE PROHIBITED

7. 8.

In Object Explorer, expand Databases | AdventureWorks2008 | Views | HumanResources.vEmployeeDetails | Columns. Verify that the correct columns are listed in the view.

Task 3: Test the HumanResources.vEmployeeDetails view


1. 2. 3. 4. 5. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery2.sql As. The Save File As dialog box appears. In the File name field, type TestEmployeeView.sql, and then click Save. In the query window, type the following code:
Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails

6. 7. 8. 9.

On the toolbar, click Execute. Examine the Results and Messages boxes and verify that the script completed without any errors. Verify that correct data is returned from the view. On the File menu, click Save All.

10. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you should have created and tested of a new view for the database.

L6-44

Module 6: Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Creating Indexed Views


Task 1: Create a new query file
1. 2. 3. 4. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery3.sql As. The Save File As dialog box appears. In the File name field, type CreateViewIndex.sql, and then click Save.

Task 2: Create the IX_vEmployeeDetails index


1. In the query window, type the following Transact-SQL code to create the IX_vEmployeeDetails index on the HumanResources.vEmployeeDetails view.
USE AdventureWorks2008 GO CREATE UNIQUE CLUSTERED INDEX IX_vEmployeeDetails ON HumanResources.vEmployeeDetails (BusinessEntityID)

2. 3. 4. 5. 6. 7.

On the toolbar, click Execute. Examine Messages box and verify that the script completed without any errors. On the File menu, click Save All. In Object Explorer, expand Databases | AdventureWorks2008 | Views | HumanResources.vEmployeeDetails | Indexes. Verify that the IX_vEmployeeDetails index is listed. Keep SQL Server Management Studio open. You will use it in the next exercise.
Results: After this exercise, you should have created a new view index.

Lab: Implementing Views

L6-45

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 3: Creating Partitioned Views


Task 1: Prepare the SQL Server instances
1. 2. 3. 4. Click Start, and then click Computer. In Microsoft Windows Explorer, navigate to the E:\Mod06\Labfiles\Starter folder. Double-click LabSetup.cmd to run the script that configures the servers for the partitioned view. When the script completes, close Windows Explorer.

Task 2: Create a new query file


1. 2. 3. 4. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery4.sql As. The Save File As dialog box appears. In the File name field, type CreatePartitionedView.sql, and then click Save.

Task 3: Create the Person.vContact distributed partitioned view


1. In the query window, type the following code to create the distributed partitioned view named Person.vContact on the AW_Contacts database:
USE AW_Contacts GO CREATE VIEW Person.vContact AS SELECT * FROM [NY-SQL-01].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE2].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE3].AW_Contacts.Person.Contact

2. 3. 4.

On the toolbar, click Execute. On the File menu, click Save All. In Object Explorer, right-click Databases, and then click Refresh.

L6-46

Module 6: Implementing Views

MCT USE ONLY. STUDENT USE PROHIBITED

5. 6. 7. 8. 9.

Expand Databases | AW_Contacts | Views. Verify that the Person.vContact view is listed. In Object Explorer, expand Databases | AW_Contacts | Views | Person.vContact | Columns. Verify that the correct columns are listed. In the Solution Explorer pane, right-click Queries, and then click New Query.

10. If the Connect to Server dialog box appears, click Connect. 11. On the File menu, click Save SQLQuery5.sql As. 12. The Save File As dialog box appears. In the File name field, type ViewPersonContact.sql, and then click Save. 13. In the query window, type the following code to select the contents of the Person.vContact view:
USE AW_Contacts GO SELECT * FROM Person.vContact

14. On the toolbar, click Execute. 15. Examine the Results and Messages boxes and verify that the script completed without any errors. 16. Verify that the result set of the Person.vContact view contains the data from the Person.Contact tables on all three SQL Server instances. 17. On the File menu, click Save All. 18. Close SQL Server Management Studio. 19. Turn off 6232A-NY-SQL-01 and delete changes.
Results: After this exercise, you should have configured and tested a new partitioned view for the SQL Server.

Lab: Implementing Stored Procedures

L7-47

MCT USE ONLY. STUDENT USE PROHIBITED

Module 7: Implementing Stored Procedures

Lab: Implementing Stored Procedures


Exercise 1: Creating Stored Procedures
Task 1: Create and test the GetDiscounts stored procedure
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Student with the password of Pa$$w0rd. Click Start, right-click Computer and then click Explore. In Windows Explorer browse to E:\MOD07\Labfiles\Starter. Double-click the AWProgrammability project file. The Microsoft SQL Server Management Studio window opens. If the Solution Explorer is not visible in the right pane, click View | Solution Explorer. In the Solution Explorer, double-click InitilizeData.sql. If the Connect to Sever dialog box appears, connect to server NY-SQL-01 using Windows Authentication. Click Connect. On the toolbar, click Execute, and then confirm that no errors occur.

10. In Solution Explorer, double-click the StoredProcedures.sql query file. 11. If the Connect to Sever dialog box appears, connect to server NY-SQL-01 using Windows Authentication. Click Connect. 12. Select the Use AdventureWorks2008 statement, and then on the toolbar, click Execute. 13. Select the text between the --Create GetDiscount comment and the following comment. 14. On the toolbar, click the Execute button to execute the selected text.

L7-48

Module 7: Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

15. To test the GetDiscount stored procedure: select the text between the Test GetDiscounts comment and the following comment. 16. On the toolbar, click the Execute button. 17. Verify the query runs with no errors.

Task 2: Create and test the GetDiscountsForCategory stored procedure


1. 2. 3. 4. 5. Select the text between the --Create GetDiscountsForCategory comment and the following comment. On the toolbar, click the Execute button to execute the selected text. To test the GetDiscountsForCategory stored procedure: select the text between the -- Test GetDiscountsForCategory comment and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors.

Task 3: Create and test the GetDiscountsForCategoryAndDate stored


procedure
1. 2. 3. Select the text between the --Create GetDiscountsForCategoryAndDate comment and the following comment. On the toolbar, click the Execute button to execute the selected text To test the GetDiscountsForCategoryAndDate stored procedure: select the text between the -- Test GetDiscountsForCategoryAndDate comment and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors. Select the text between the comment -- Test GetDiscountsForCategoryAndDate with both parameters and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors.

4. 5. 6.

7. 8.

Lab: Implementing Stored Procedures

L7-49

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: Create and test the AddDiscount stored procedure


1. 2. 3. 4. 5. 6. Select the text between the Create AddDiscount comment and the following comment. On the toolbar, click the Execute button to execute the selected text. To test the AddDiscount stored procedure: select the text between the -- Test AddDiscount comment and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors. To test executing the query with variables that generate an error, select all code between the comments -- Test AddDiscount with errors and the following comment, and then click Execute. Verify that an error log record is returned in the results pane.
Results: After this exercise, you should have created and tested 4 stored procedures.

7.

Exercise 2: Working with Execution Plans


Task 1: View the text-based execution plan
1. 2. 3. 4. In the Query window, select the code between the comment Test the textbased execution plan and the following comment. On the toolbar, click Execute. Observe in the results pane both the query and the text based execution plan are displayed instead of query results. Observe that the execution plan displays query parts in hierarchical order from most to least expensive operation.

Task 2: View the graphical execution plan


1. 2. 3. In the Query window, select the code between the comment Test the graphical execution plan and the following comment. Right-click the selection and then click Include Actual Execution Plan. On the toolbar, click Execute.

L7-50

Module 7: Implementing Stored Procedures

MCT USE ONLY. STUDENT USE PROHIBITED

4. 5. 6.

In the Results pane, observe that query results are returned. Observe the Execution Plan tab above the returned results. Click the Execution Plan tab. Observe that the execution plan shows that 0% of the executions work was involved in the SELECT statement, that 68% of the work was involved in the sort and 32% was involved in the clustered index scan.

Task 3: Tune the database to improve performance


1. 2. In the Query window select the code between the comment --Tune the database. Create an index on Name and the following comment. On the toolbar, click Execute.

Task 4: View the revised execution plan


1. 2. 3. 4. 5. In the Query window select the code below the comment Retest the graphical execution plan. In the toolbar, click Execute. In the Results pane observe that query results are returned. Observe the Execution Plan tab above the returned results. Click the Execution Plan tab. Observe that the execution plan shows that 0% of the executions work was involved in the SELECT statement, that 68% of the work was involved in the sort and 32% was involved in the clustered index scan. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.
Results: After this exercise, you should have created and viewed both text-based and graphical execution.

6.

Lab: Implementing Functions

L8-51

MCT USE ONLY. STUDENT USE PROHIBITED

Module 8: Implementing Functions

Lab: Implementing Functions


Exercise 1: Creating Functions
Task 1: Create and test the GetMaximumDiscountForCategory Userdefined function
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Administrator with the password of Pa$$w0rd. From the Start Menu, right-click Computer, and then click Explore. In Windows Explorer, browse to E:\MOD08\Labfiles\Starter. Double-click createnewuser.vbs. Click OK. Open Command Prompt. Browse to E:\MOD08\Labfiles\Starter. Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER. Log off Administrator and then log on as Student with the password of Pa$$w0rd. From the Start Menu, right-click Computer, and then click Explore.

10. In Windows Explorer, browse to E:\MOD08\Labfiles\Starter. 11. Double-click the AWProgrammability solution file. The SQL Server Management Studio window opens. 12. If the Solution Explorer is not visible in the right pane, click View | Solution Explorer in the File menu. 13. In the Solution Explorer, expand AWProgramability | Queries. 14. Double-click InitilizeData.sql. 15. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. 16. The query appears. On the toolbar, click Execute, and then confirm that no errors occur. 17. In Solution Explorer, double-click the UserDefinedFunctions.sql query file.

L8-52

Module 8: Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

18. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. 19. Select the Use AdventureWorks2008 statement. On the toolbar, click Execute. 20. Locate the Create Sales.GetMaximumDiscountForCategory comment. Select the CREATE FUNCTION code shown in the following Transact-SQL example:
CREATE FUNCTION Sales.GetMaximumDiscountForCategory (@Category nvarchar(50)) RETURNS smallmoney AS BEGIN DECLARE @Max smallmoney SELECT @Max = MAX(DiscountPct) FROM Sales.SpecialOffer WHERE Category = @Category AND GetDate() BETWEEN StartDate AND EndDate GROUP BY Category IF (@Max IS NULL) SET @Max = 0 RETURN @Max END

21. On the Toolbar, click Execute. 22. In the Results pane, review the query results, verifying that the statement executed successfully. 23. Locate the Test Sales.GetMaximumDiscountForCategory comment, and then test the function, as shown in the following Transact-SQL example:
SELECT Sales.GetMaximumDiscountForCategory('Reseller')

24. Select the query, and then on the toolbar, click Execute. In the Query results, verify that a discount value is returned. 25. On the File menu, click Save UserDefinedFunctions.sql.

Lab: Implementing Functions

L8-53

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create and test the GetDiscountsForDate User-defined


function
1. Locate the Create Sales.GetDiscountsForDate comment, and then create the user-defined function, as shown in the following Transact-SQL example:
CREATE FUNCTION Sales.GetDiscountsForDate (@DateToCheck datetime) RETURNS TABLE AS RETURN ( SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer WHERE @DateToCheck BETWEEN StartDate AND EndDate )

2. 3. 4.

Select the CREATE FUNCTION statement. On the toolbar, click Execute. In the Results pane, review the query results, verifying that the statement executed successfully. Locate the Test Sales.GetDiscountsForDate comment, select the TransactSQL statement shown below in the following Transact-SQL example:
SELECT * FROM Sales.GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC

5. 6.

On the toolbar, click Execute. In the query results, verify that some rows are displayed. On the File menu, click Save UserDefinedFunctions.sql.

L8-54

Module 8: Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create and test the GetDiscountedProducts User-defined


function
1. Locate the Create Sales.GetDiscountedProducts comment. Select the code to create the user-defined function as shown in the following Transact-SQL example:
CREATE FUNCTION Sales.GetDiscountedProducts (@IncludeHistory bit) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money) AS BEGIN IF (@IncludeHistory = 1) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct FROM Sales.SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) ORDER BY ProductID ELSE INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice *

Lab: Implementing Functions

L8-55

MCT USE ONLY. STUDENT USE PROHIBITED

(continued)
SO.DiscountPct FROM Sales.SpecialOfferProduct SOP INNER JOIN

Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END

2. 3. 4.

On the toolbar, click Execute. In the Results pane, review the query results. Verify that the statement executed successfully. Locate the Test Sales.GetDiscountedProducts comment; select the code as shown in the following Transact-SQL example:
SELECT * FROM Sales.GetDiscountedProducts(0) SELECT * FROM Sales.GetDiscountedProducts(1)

5. 6.

On the toolbar, click Execute. In the query results, view the number of rows returned by each query. On the File menu, click Save UserDefinedFunctions.sql.
Results: After this exercise, you should have created and tested 3 user-defined functions.

L8-56

Module 8: Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Controlling Execution Context


Task 1: Create the GetCurrencyRate User-defined function
1. 2. 3. 4. In Solution Explorer, double-click the ExecutionContext.sql query file. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. Select the USE AdventureWorks2008 statement. On the toolbar, click Execute. Locate the Create Sales.GetCurrencyRate comment, and then create the userdefined function, as shown in the following Transact-SQL example:
CREATE FUNCTION Sales.GetCurrencyRate (@CurrencyCode nchar(3)) RETURNS float WITH EXECUTE AS 'Adam' AS BEGIN DECLARE @CurrencyRate float SELECT @CurrencyRate = (SELECT TOP (1) EndOfDayRate FROM AdventureWorksDW2008.dbo.DimCurrency C INNER JOIN AdventureWorksDW2008.dbo.FactCurrencyRate CR ON C.CurrencyKey = CR.CurrencyKey WHERE C.CurrencyAlternateKey = @CurrencyCode ORDER BY CR.DateKey DESC) IF (@CurrencyRate IS NULL) SET @CurrencyRate = 1.0 RETURN @CurrencyRate END GO

5. 6. 7.

Select the CREATE FUNCTION statement. On the toolbar, click Execute. In the Results pane, review the query results. Verify that the statement executed successfully. Locate the Test Sales.GetCurrencyRate comment, and then test the function, as shown in the following Transact-SQL example:
SELECT Sales.GetCurrencyRate('GBP')

Lab: Implementing Functions

L8-57

MCT USE ONLY. STUDENT USE PROHIBITED

8.

Select the SELECT statement. On the toolbar, click Execute.

Note: At this stage you have not established a trust relationship between the databases, so you should expect to receive the following error message: The server principal "NY-SQL-01\Adam" is not able to access the database "AdventureWorksDW" under the current security context.

9.

On the File menu, click Save ExecutionContext.sql.

Task 2: Establish a database trust relationship


1. 2. 3. 4. In Solution Explorer, double-click the TrustRelationship.sql query file. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. Select the USE AdventureWorksDW2008 statement. Click Execute. Locate the Create the user for the NY-SQL-01\Adam login comment, and then create a user called Adam in the AdventureWorksDW2008 database for the NY-SQL-01\Adam login, as shown in the following Transact-SQL example:
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = 'Adam' AND type = 'U') CREATE USER Adam FOR LOGIN [NY-SQL-01\Adam] GO

5. 6. 7. 8.

Select the IF and CREATE statements. On the toolbar, click Execute. Verify that the statements executed successfully. Locate the Grant AUTHENTICATE permission on the database comment. Implement the Transact-SQL code required to grant the mapped user AUTHENTICATE permission in the AdventureWorksDW2008 database, as shown in the following Transact-SQL example:
GRANT AUTHENTICATE TO Adam GO

L8-58

Module 8: Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

9.

Select the GRANT statement. On the toolbar, click Execute.

10. Verify that the statement executed successfully. 11. Locate the Grant SELECT permissions to Adam comment, and then implement the Transact-SQL code required to grant the authenticator the permissions required by the user-defined function in the calling database, as shown in the following Transact-SQL example.
GRANT SELECT TO Adam GO

12. Select the GRANT statement. On the toolbar, click Execute. 13. Verify that the statement executed successfully. 14. Locate the Set the TRUSTWORTHY database option on the AdventureWorks2008 database comment, and then implement the TransactSQL code required to alter the calling database and set the TRUSTWORTHY option to ON, as shown in the following Transact-SQL example:
ALTER DATABASE AdventureWorks2008 SET TRUSTWORTHY ON GO

15. Select the ALTER statement. On the toolbar, click Execute. 16. Verify that the statement executed successfully. 17. On the File menu, click Save TrustRelationship.sql.

Lab: Implementing Functions

L8-59

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create and test the GetCurrencyDiscountedProducts Userdefined Function


1. 2. 3. In Solution Explorer, double-click the ExecutionContext.sql query file. Select the USE AdventureWorks2008 statement. On the toolbar, click Execute. Locate the Sales.GetCurrencyDiscountedProducts comment, as shown in the following example:
-- Sales.GetCurrencyDiscountedProducts CREATE FUNCTION Sales.GetCurrencyDiscountedProducts (@CurrencyCode nchar(3)) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, CurrencyPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money, DiscountedCurrencyPrice money) AS BEGIN DECLARE @CurrencyRate float SET @CurrencyRate = Sales.GetCurrencyRate(@CurrencyCode) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, P.ListPrice * @CurrencyRate, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct, (P.ListPrice - P.ListPrice * SO.DiscountPct) * @CurrencyRate FROM Sales.SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END GO

L8-60

Module 8: Implementing Functions

MCT USE ONLY. STUDENT USE PROHIBITED

4. 5. 6.

Select the CREATE FUNCTION statement. On the toolbar, click Execute. Verify that the statement executed successfully. Locate the Test Sales.GetCurrencyDiscountedProducts comment, and then test the function, as shown in the following Transact-SQL example:
SELECT * FROM Sales.GetCurrencyDiscountedProducts('GBP')

7. 8. 9.

Select the SELECT statement. On the toolbar, click Execute. Review the query results and verify that the statement executed successfully. On the File menu, click Save All, and then close SQL Server Management Studio.

10. Turn off 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have created two user-defined functions and created a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008.

Lab: Implementing Managed Code in a Database

L9-61

MCT USE ONLY. STUDENT USE PROHIBITED

Module 9: Implementing Managed Code in a Database

Lab: Implementing Managed Code in a Database


Exercise 1: Importing an Assembly
Task 1: Start the NY-SQL-01 virtual machine and log on as
Administrator
1. 2. 3. 4. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Administrator using the password of Pa$$w0rd. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect.
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

L9-62

Module 9: Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Import the AWorksUtilities assembly


1. 2. 3. 4. 5. 6. 7. On the File menu, point to Open, and then click Project/Solution. In the Open Project dialog box, browse to the E:\MOD09\Labfiles\Starter folder click the AWorks_CLR.ssmssln file, and then click Open. If Solution Explorer is not visible, on the View menu, click Solution Explorer. In Solution Explorer, expand the Queries node, and then double-click the Initialize.sql query file. On the toolbar, click Execute, and then confirm that no errors occur. In Solution Explorer, double-click the ImportAssembly.sql query file. Below the Enable CLR integration comment, add the following code:
sp_configure 'clr enabled', 1 GO RECONFIGURE GO

8. 9.

On the toolbar, click Execute, and then verify that the statements executed successfully. Below the Create assembly comment, add the following code:
USE AdventureWorks2008 CREATE ASSEMBLY AWorksUtilities FROM 'E:\MOD09\Labfiles\Starter\AWorksUtilities.dll'

10. Below the Create assembly comment, select all the code, and then on the toolbar, click Execute. 11. In the query results, verify that the statements executed successfully. 12. On the File menu, click Save ImportAssembly.sql. 13. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you should have the managed database objects in the AWorksUtilities assembly available for use within the AdventureWorks2008 database.

Lab: Implementing Managed Code in a Database

L9-63

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Creating Managed Database Objects


Task 1: Create the SaveXML managed stored procedure referencing
the external assembly
1. 2. In Solution Explorer, double-click the SaveXML.sql query file. Locate the Create managed stored procedure comment, and then add the following code:
USE AdventureWorks2008 GO CREATE PROCEDURE dbo.SaveXML ( @XmlData xml, @FileName nvarchar(100) ) AS EXTERNAL NAME AWorksUtilities.StoredProcedures.SaveXML GO

3. 4. 5. 6. 7.

Below the Create managed stored procedure comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test managed stored procedure comment, select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. Confirm that an error message is displayed. The assembly does not have the required permissions to write to the file system. Below the Change security permissions to allow file access comment, add the following code:
ALTER ASSEMBLY AWorksUtilities WITH PERMISSION_SET = EXTERNAL_ACCESS GO

8. 9.

Select the ALTER ASSEMBLY statement, and then on the toolbar, click Execute. In the query results, verify that the statements executed successfully.

10. Below the Retest managed stored procedure comment, select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. 11. Confirm that no errors occur this time.

L9-64

Module 9: Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

12. On the File menu, click Save SaveXML.sql. 13. Keep the SQL Server Management Studio solution open. You will use it in the next procedure. 14. Click Start, and then click Computer. 15. In Microsoft Windows Explorer, browse to the E:\MOD09\Labfiles\Starter folder, and then verify the existence of the Output.xml file. 16. Double-click the Output.xml file to display the XML in Microsoft Internet Explorer. 17. Close Internet Explorer and Windows Explorer when you have confirmed that the file contains XML.

Lab: Implementing Managed Code in a Database

L9-65

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Create the GetLongDate managed user-defined function


referencing the external assembly
1. 2. In Solution Explorer, double-click the GetLongDate.sql query file. Below the Create managed user-defined function comment, add the following code:
USE AdventureWorks2008 GO CREATE FUNCTION dbo.GetLongDate ( @DateVal datetime ) RETURNS nvarchar(50) AS EXTERNAL NAME AWorksUtilities.UserDefinedFunctions.GetLongDate GO

3. 4. 5. 6. 7. 8.

Below the Create managed user-defined function comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test managed user-defined function comment, select the SELECT statement, and then on the toolbar, click Execute. Verify that a list of orders is displayed that includes the day of the week in the OrderDate column. Confirm that the records are displayed with a long OrderDate value. On the File menu, click Save GetLongDate.sql.

L9-66

Module 9: Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create the EmailChange managed trigger on the


Person.EmailAddress table referencing the external assembly
1. 2. In Solution Explorer, double-click the EmailChange.sql query file. Below the Create trigger comment, add the following code:
USE AdventureWorks2008 GO CREATE TRIGGER EmailChange ON Person.EmailAddress FOR UPDATE AS EXTERNAL NAME AWorksUtilities.Triggers.EmailChange GO

3. 4. 5. 6. 7. 8.

Below the Create trigger comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test trigger comment, select the first UPDATE statement, and then on the toolbar, click Execute. Confirm that a message is displayed, noting the new e-mail address in the Messages pane. Below the Test trigger comment, select the second UPDATE statement, and then on the toolbar, click Execute. Confirm that there is no message because the statement did not update the email address. This is because the managed code checks to see which columns were updated and performs the trigger logic only if the e-mail column is modified. On the File menu, click Save EmailChange.sql.

9.

Lab: Implementing Managed Code in a Database

L9-67

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: Create the Concatenate managed aggregate function


referencing the external assembly
1. 2. In Solution Explorer, double-click the Concatenate.sql query file. Below the Create aggregate function comment, add the following code:
USE AdventureWorks2008 GO CREATE AGGREGATE Concatenate(@input nvarchar(4000)) RETURNS nvarchar(4000) EXTERNAL NAME AWorksUtilities.Concatenate GO

3. 4. 5. 6. 7.

Below the Create aggregate function comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test aggregate function comment, select the SELECT statement, and then on the toolbar, click Execute. Confirm that orders are displayed as a concatenated string for each account in the Messages pane. On the File menu, click Save Concatenate.sql.

L9-68

Module 9: Implementing Managed Code in a Database

MCT USE ONLY. STUDENT USE PROHIBITED

Task 5: Create the IPAddress managed user-defined type referencing


the external assembly
1. 2. In Solution Explorer, double-click the IPAddress.sql query file. Below the Create managed user-defined type comment, add the following code:
USE AdventureWorks2008 GO CREATE TYPE IPAddress EXTERNAL NAME AWorksUtilities.IPAddress GO

3. 4. 5. 6. 7. 8. 9.

Below the Create managed user-defined type comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test managed user-defined type comment, select the statements, and then on the toolbar, click Execute. Confirm that three result sets are displayed that show the IPAddress value in various forms. On the File menu, click Save IPAddress.sql. Close the SQL Server Management Studio solution. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.
Results: After this exercise, you should have successfully imported assembly code and created managed database objects.

Lab: Managing Transactions and Locks

L10-69

MCT USE ONLY. STUDENT USE PROHIBITED

Module 10: Managing Transactions and Locks

Lab: Managing Transactions and Locks


Exercise 1: Using Transactions
Task 1: Start the virtual machine and log on as Administrator
1. 2. In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd.

Task 2: Create and commit a transaction


1. 2. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect:
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

3. 4.

On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Tran1.sql, and then click Open.

L10-70

Module 10: Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

5.

In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

6.

Locate the comment START TRANSACTION HERE, and then add a statement to start a transaction. Your code should resemble the following:
BEGIN TRANSACTION

7.

Click Execute to execute the script, and then review the results. At this point, the transaction is still active and locks are still held. The changes made have not been committed to the database. Locate the comment END TRANSACTION HERE, and then add a statement to commit the changes to the database. Your code should resemble the following:
COMMIT TRANSACTION

8.

9.

Select the end transaction statement, and then click Execute. The changes are now committed to the database.

10. Select the last two statements in the script, and then click Execute. 11. Verify that the transaction count is now set to zero and the changes have been committed to the database. 12. On the File menu, click Save Tran1.sql. 13. On the File menu, click Close.

Lab: Managing Transactions and Locks

L10-71

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Create and rollback a transaction


1. 2. 3. On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Tran2.sql, and then click Open. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

4.

Notice that the statements update a different record in the Person.Person table. Again, the SELECT statements and the @@trancount global variable show the progress of the transaction. Locate the comment END TRANSACTION HERE, and then add a statement to roll back the changes to the database. Your code should resemble the following:
ROLLBACK TRANSACTION

5.

6.

Click Execute to execute the script, and then review the results. Notice that the transaction is complete because the transaction count is zero and the changes have been cancelled. On the File menu, click Save Tran2.sql. Close SQL Server Management Studio.
Results: After this exercise, you should have committed and rolled back transactions.

7. 8.

L10-72

Module 10: Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Exercise 2: Managing Locks


Task 1: View locking information
1. 2. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect:
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

3. 4. 5. 6.

In SQL Server Management Studio, in the console tree, right-click NY-SQL-01, and then click Activity Monitor. Review the information that is displayed in Processes, ResourceWaits, and Data File I/O, and Recent Expensive Queries. On the File menu, point to New, and then click Query with Current Connection. Type the following statement into the query window:
SELECT resource_type, request_mode, request_type, request_status, request_session_id FROM sys.dm_tran_locks

7. 8. 9.

Click Execute to execute the statement. Review the information that shows the current lock in the master database. On the File menu, point to Open, and then click File.

10. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Lock1.sql, and then click Open.

Lab: Managing Transactions and Locks

L10-73

MCT USE ONLY. STUDENT USE PROHIBITED

11. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

12. Notice that a transaction starts with the BEGIN TRANSACTION statement, but there is no corresponding COMMIT TRANSACTION or ROLLBACK TRANSACTION statement to complete the transaction. 13. Click Execute to execute the script and note the SPID of the connection. 14. Switch back to the original query window and then click Execute to execute the query and retrieve data from the sys.dm_tran_locks view. Notice that now the SPID of the second connection holds locks on various objects. 15. In SQL Server Management Studio, in the console tree, right-click NY-SQL01, and then click Activity Monitor. 16. Review the information that is now displayed in Overview, Processes, and Resource Waits. 17. Switch to the Lock1.sql query window, type the following code at the end of the script, and then execute the statement:
ROLLBACK TRANSACTION

18. Switch back to the original query window, and then click Execute to execute the query and retrieve data from the sys.dm_tran_locks view. 19. Notice that the object locks acquired during the transaction have now been released. 20. Close SQL Server Management Studio without saving the changes to the files.

L10-74

Module 10: Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Set locking options


1. 2. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect:
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

3. 4. 5.

On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Lock1.sql, and then click Open. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

6. 7. 8. 9.

Review the contents of the file, and then execute the query. On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Lock2.sql, and then click Open. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

Lab: Managing Transactions and Locks

L10-75

MCT USE ONLY. STUDENT USE PROHIBITED

10. Review the contents of the file and notice that the transaction isolation level is set to SERIALIZABLE, which prevents other users from accessing rows that match the criteria in a WHERE clause.

Note: In the next step, you will execute the query. Continue with the exercise and do not wait for the execution to complete.

11. Click Execute to execute the query. 12. On the File menu, point to Open, and then click File. 13. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click LockList.sql, and then click Open. 14. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

15. Click Execute to execute the query and notice that there is an entry of WAIT in the request_status column, which indicates that the second query is waiting for a lock to be granted before proceeding. 16. Switch to the Lock2.sql query window, and then click Cancel Executing Query. 17. Switch to the LockList.sql query window, and then click Execute to execute the query. 18. Verify that the waiting transaction has been cancelled.

L10-76

Module 10: Managing Transactions and Locks

MCT USE ONLY. STUDENT USE PROHIBITED

Task 3: Set the lock timeout


1. Switch to the Lock2.sql query window, and then edit the file by adding the following statement immediately before the BEGIN TRANSACTION statement:
SET lock_timeout 5000

2. 3. 4.

Click Execute to execute the query and wait five seconds. Notice that the query no longer waits indefinitely for the lock to be granted. Close SQL Server Management Studio without saving the changes to the files. Turn off the virtual machine and delete changes.
Results: After this exercise, you should have set locking options and timeouts.

Lab: Using Service Broker

L11-77

MCT USE ONLY. STUDENT USE PROHIBITED

Module 11: Using Service Broker

Lab: Using Service Broker


Exercise 1: Creating Service Broker Objects
Task 1: Launch SQL Server Management Studio
1. 2. 3. 4. 5. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, verify that Server type is set to Database Engine and Server name is set to NY-SQL-01, and then click Connect. Maximize the Microsoft SQL Server Management Studio window.

Task 2: Create the AW_ServiceBroker SQL Server Scripts project


1. 2. 3. 4. On the File menu, point to New, and then click Project. In the New Project dialog box, in the Name field, type AW_ServiceBroker. In the Location field, type E:\MOD11\Labfiles\Starter. Clear Create directory for solution and then click OK.

Task 3: Configure the AdventureWorks database for Service Broker


1. 2. 3. 4. 5. On the Project menu, click New Query to add a new query file to the project. If the Connect to Database Engine dialog box appears, click Connect. If Solution Explorer is not visible, on the View menu, click Solution Explorer. In Solution Explorer, in the Queries folder, right-click SQLQuery1.sql, click Rename, type PrepareDatabase.sql, and then press ENTER. Notice how the name of the query in the design pane has automatically changed to PrepareDatabase.sql.

L11-78

Module 11: Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

6.

Add the following Transact-SQL code to the PrepareDatabase.sql query:


USE master GO -- Enable Service Broker in the AdventureWorks2008 database ALTER DATABASE AdventureWorks2008 SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO ALTER DATABASE AdventureWorks2008 SET ENABLE_BROKER GO -- Configure the AdventureWorks2008 database USE AdventureWorks2008 GO IF NOT EXISTS (SELECT * FROM sys.symmetric_keys WHERE name = '##MS_DatabaseMasterKey##') CREATE MASTER KEY ENCRYPTION BY PASSWORD = '23987hxJ#KL95234nl0zBe' GO CREATE SCHEMA EMailSvc GO CREATE SCHEMA CustomerSvc GO -- Create a table to log details of the customer e-mails sent CREATE TABLE EMailSvc.EmailLog ( Date datetime NOT NULL, [Event] nvarchar(50) NOT NULL, CustomerData xml ) GO ALTER DATABASE AdventureWorks2008 SET MULTI_USER GO

7. 8.

On the toolbar, click Execute to execute the query. On the File menu, click Save All.

Lab: Using Service Broker

L11-79

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: Create the Service Broker objects required for the customer email solution
1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type CreateServiceBrokerObjects.sql, and then press ENTER. In the CreateServiceBrokerObjects.sql query window, type the following Transact-SQL code to create the message type, contract, queues, and services:
USE AdventureWorks2008 GO -- Create message types CREATE MESSAGE TYPE [//AW/EMail/CustomerDetails] VALIDATION = WELL_FORMED_XML GO -- Create contracts CREATE CONTRACT [//AW/EMail/SendCustomerDetails] ( [//AW/EMail/CustomerDetails] SENT BY INITIATOR ) GO -- Create queues CREATE QUEUE CustomerSvc.NewCustomerQueue WITH STATUS = ON CREATE QUEUE EMailSvc.NewCustomerEmailQueue WITH STATUS = OFF GO -- Create services CREATE SERVICE [//AW/Sales/CustomerService] ON QUEUE CustomerSvc.NewCustomerQueue CREATE SERVICE [//AW/EMail/EmailService] ON QUEUE EMailSvc.NewCustomerEmailQueue ([//AW/EMail/SendCustomerDetails])

L11-80

Module 11: Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

4. 5. 6. 7. 8.

On the toolbar, click Execute to execute the query. On the File menu, click Save All. If Object Explorer is not visible, on the View menu, click Object Explorer. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Service Broker. In the Service Broker folder, expand the Message Types, Contracts, Queues, and Services folders, and then verify that the necessary Service Broker objects are listed. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have launched SQL Server Management Studio and created the AW_ServiceBroker SQL Server Scripts project. In addition, you should have configured the AdventureWorks database for Service Broker and then created the Service Broker objects required for the customer e-mail solution.

9.

Exercise 2: Implementing the Initiating Service


Task 1: Add the CreateEmailNewCustomerSP.sql query file to the
AW_ServiceBroker project
1. 2. On the Project menu, click Add Existing Item. In the Add Existing Item AW_ServiceBroker dialog box, browse to the E:\MOD11\Labfiles\Starter folder, click the CreateEmailNewCustomerSP.sql query file, and then click Add.

Lab: Using Service Broker

L11-81

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Implement the CustomerService service


1. Examine the Transact-SQL code in the CreateEmailNewCustomerSP.sql query file. Notice that it contains Transact-SQL statements to create a stored procedure that sends messages from the CustomerService service to the EmailService service in the AdventureWorks2008 database. On the toolbar, click Execute to execute the query. On the File menu, click Save All. In Object Explorer, under AdventureWorks2008, expand Programmability, and then expand Stored Procedures. Verify that the CustomerSvc.uspEmailNewCustomer stored procedure is listed. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created the CustomerSvc.uspEmailNewCustomer stored procedure used by the service.

2. 3. 4. 5. 6.

Exercise 3: Implementing the Target Service


Task 1: Add the CreateSendEmailSP.sql query file to the
AW_ServiceBroker project
1. 2. On the Project menu, click Add Existing Item. In the Add Existing Item AW_ServiceBroker dialog box, browse to the E:\MOD11\Labfiles\Starter folder, click the CreateSendEmailSP.sql query file, and then click Add.

L11-82

Module 11: Using Service Broker

MCT USE ONLY. STUDENT USE PROHIBITED

Task 2: Implement the EmailService service


1. Examine the Transact-SQL code in the CreateSendEmailSP.sql query file. Notice that it contains Transact-SQL statements to create a stored procedure to receive and process messages in the EmailService service in the AdventureWorks2008 database. On the toolbar, click Execute to execute the query. On the File menu, click Save All. In Object Explorer, right-click Stored Procedures, and then click Refresh. Verify that the EMailSvc.uspSendCustomerEmail stored procedure is listed.

2. 3. 4. 5.

Task 3: Configure the target service for automatic activation


1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type AlterServiceBrokerQueue.sql, and then press ENTER. In the AlterServiceBrokerQueue.sql query window, type the following Transact-SQL statement to make the EMailSvc.NewCustomerEmailQueue queue activate the EMailSvc.uspSendCustomerEmail stored procedure:
USE AdventureWorks2008 GO ALTER QUEUE EMailSvc.NewCustomerEmailQueue WITH STATUS = ON, ACTIVATION ( STATUS = ON, PROCEDURE_NAME = AdventureWorks2008.EMailSvc.uspSendCustomerEmail, MAX_QUEUE_READERS = 5, EXECUTE AS OWNER)

4. 5.

On the toolbar, click Execute to execute the query. On the File menu, click Save All.

Lab: Using Service Broker

L11-83

MCT USE ONLY. STUDENT USE PROHIBITED

Task 4: Test the EmailService service


1. 2. On the Project menu, click Add Existing Item. In the Add Existing Item AW_ServiceBroker dialog box, browse to the E:\MOD11\Labfiles\Starter folder, click the TestEmailService.sql query file, and then click Add. Examine the TestEmailService.sql query file, and notice that it contains Transact-SQL statements to execute the CustomerSvc.uspEmailNewCustomer stored procedure and then query the EMailSvc.EmailLog table. On the toolbar, click Execute to execute the query. Review the result set returned from the EMailSvc.EmailLog table, and verify that it contains the customer data sent to the EmailService service. (If the table contains no records, wait a few seconds, select the SELECT statement, and then re-execute it). On the File menu, click Save All. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have created a stored procedure that receives and processes messages in the EmailService service. You should have also tested the EmailService service.

3.

4. 5.

6. 7.

MCT USE ONLY. STUDENT USE PROHIBITED

Das könnte Ihnen auch gefallen