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.
    b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions
         location, an IT Academy location, or such other entity as Microsoft may designate from time to time.
    c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and
         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.
    d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning
         Center during an Authorized Training Session, each of which provides training on a particular
         Microsoft technology subject matter.
    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.
    g.   “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that
         may be included with the Licensed Content.
    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.
   j.   “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.
   k. “Trainer Content” means the materials accompanying these license terms that are for use by
        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.
   l.   “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”.
   m. “Virtual Machine” means a virtualized computing experience, created and accessed using
        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”.
   n.    “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
        license terms.
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.
             B. Portable Device. You may install another copy on a portable device solely for your own
                   personal training Use and for preparation of an Authorized Training Session.
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.
    b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to
        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.
    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.
             ii.   Survival. Your duty to protect confidential information survives this agreement.
             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
                 •   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.

   d.   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”).
   e.   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.
   f.   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.
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   You may not install Virtual Machines and Virtual Hard Disks on portable Devices or
                Devices that are accessible to other networks.
            o   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.
            o   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.
            o   You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or
                downloaded from Devices on which you installed them.
            o   You will strictly comply with all Microsoft instructions relating to installation, use,
                activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.
            o   You may not modify the Virtual Machines and Virtual Hard Disks or any contents
                thereof.
            o   You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.
   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 Material’s original copyright notice, or a copyright notice to
                Microsoft’s 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 else’s 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
       Microsoft’s 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.
9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed
    Content marked as “NFR” or “Not for Resale.”
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.
11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you
    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.
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 Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION 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 péril. Microsoft n’accorde aucune autre
garantie expresse. Vous pouvez bénéficier 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, d’adéquation à un usage particulier et d’absence de contrefaçon sont
exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS 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 prétendre à aucune indemnisation
pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de
bénéfices.
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 réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte,
        de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel
dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages
indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne
s’appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent 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 20-
   year 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                                                                 1-3
      Lesson 2: Creating Filegroups                                                               1-11
      Lesson 3: Creating Schemas                                                                  1-15
      Lesson 4: Creating Database Snapshots                                                       1-19
      Lab: Creating Databases and Database Files                                                  1-25

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

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

Module 4: Implementing Data Integrity by Using Constraints and Triggers
      Lesson 1: Data Integrity Overview                                                            4-3
      Lesson 2: Implementing Constraints                                                           4-7
      Lesson 3: Implementing Triggers                                                             4-14
      Lab: Implementing Data Integrity by Using Constraints and Triggers                          4-27
xiv   Implementing a Microsoft SQL Server 2008 Database




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

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

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

Module 8: Implementing Functions
      Lesson 1: Introducing Functions                       8-3
      Lesson 2: Working with Functions                      8-9
      Lesson 3: Controlling Execution Context              8-13
      Lab: Implementing Functions                          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                         9-4
      Lesson 2: Importing and Configuring Assemblies                                           9-10
      Lesson 3: Creating Managed Database Objects                                              9-15
      Lab: Implementing Managed Code in a Database                                             9-20

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

Module 11: Using Service Broker
      Lesson 1: Service Broker Overview                                                        11-3
      Lesson 2: Creating Service Broker Objects                                               11-14
      Lesson 3: Sending and Receiving Messages                                                11-22
      Lab: Using Service Broker                                                               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 it’s 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 CD-
    ROM 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                  Role
           6232A-NY-SQL-01                   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.4–gigahertz (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                                                             1-3
  Lesson 2: Creating Filegroups                                                           1-11
  Lesson 3: Creating Schemas                                                              1-15
  Lesson 4: Creating Database Snapshots                                                   1-19
  Lab: Creating Databases and Database Files                                              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 locale-
    specific 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:MOD01Labfiles 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:MOD01LabfilesScripts folder.

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


       Task 1: Create a SQL Server Management Studio Scripts project
       1.     Start 6232A-NY-SQL-01, and log on as Student with the password of
              Pa$$w0rd.
       2.     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:MOD01LabfilesScripts 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      Create a new database user.
2.     Create a schema and assign ownership to a user.
3.     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-01Katie should use the TechSupport schema as her default
       schema.


Task 3: Display ownership of a schema
1.     Create a T-SQL statement that displays ownership of the TechSupport schema.
2.     Comment the T-SQL statement to explain what it will do on execution.
3.     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.    Create a database snapshot.
       2.    Alter the database.
       3.    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:MOD01LabfilesSnapshots 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.    When are objects assigned to the default filegroup?
       2.    What is a database schema and how can schemas be used?
       3.    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                                                                2-3
  Lesson 2: Creating Tables                                                                    2-8
  Lesson 3: Creating Partitioned Tables                                                       2-17
  Lab: Creating Data Types and Tables                                                         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, T-
            SQL 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 user-
            defined 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 Transact-
    SQL 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 company’s 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.   Create a data type based on the nvarchar system-supplied data type.
    2.   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.     Obtain date and time formatting using T-SQL.
2.     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 2007-
       05-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.     Create a table named ReturnedGoods.
       2.     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.   Prepare the database for partitioning.
2.   Create a partitioned table named ReturnsArchive.
3.   Review the partitioning implementation.


Task 1: Prepare the database for partitioning
•    Open the query located at E:MOD02LabfilesScriptspartition_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.   What are the two types of temporary tables and how do they differ from each
        other?
   2.   How can you decide whether to implement partitioning?
   3.   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                                                                  3-3
  Lesson 2: Creating Indexes                                                                  3-8
  Lesson 3: Optimizing Indexes                                                               3-21
  Lab: Creating and Optimizing Indexes                                                       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 optimizer—the
      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 index—the table’s 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 non-
clustered 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 created—and all connections attempting
    INSERT, UPDATE, or DELETE statements that will change values in the
    index—have 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 tables—to improve
performance and to make large indexes more manageable—by 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 Transact-
       SQL 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 non-
            clustered 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:MOD03LabfilesStarter 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 exercise’s main tasks are:
       1.     Start the 6432A-NY-SQL-01 virtual machine and log on as Student.
       2.     Create a SQL Server Scripts project.
       3.     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.     Open SQL Server Management Studio, and connect to the server you want to
              manage (NY-SQL-01).
       2.     On the File menu, click New, and then click Project.
       3.     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.
       2.     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.
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 exercise’s main tasks are:
1.   Add the sample products to the database.
2.   Reorganize AK_Product_ProductNumber.
3.   Rebuild AK_Product_Name.


Task 1: Add the sample products to the database
•    In SQL Server Management Studio, open aw2008sampleproductadd.sql
     from the E:Mod03LabfilesStarter 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.   What is the difference between a clustered index and a non-clustered index?
   2.   Why does fragmentation occur in an index?
   3.   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                                                         4-3
  Lesson 2: Implementing Constraints                                                        4-7
  Lesson 3: Implementing Triggers                                                          4-14
  Lab: Implementing Data Integrity by Using Constraints and Triggers                       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 integrity–domain, entity, and referential–is 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 employee’s 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 re-
    create a table.
•   You must build error-checking logic into your applications and transactions to
    test whether a constraint has been violated.
•   You must specify 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.    The DELETE step that captures the before image of the data.
       2.    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 trigger’s 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:MOD04LabfilesStarter folder.

       This exercise’s main tasks are:
       1.    Start the 6232A-NY-SQL-01 virtual machine and log on as Student.
       2.    Create a SQL Server Scripts project.
       3.    Create the JobCandidateHistory table and constraints.
       4.    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.    Open SQL Server Management Studio, and connect to the server you want to
             manage (NY-SQL-01).
       2.    On the File menu, click New, and then click Project.
       3.    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.
       2     Execute the query, and then save the query file.
       3.    Use Object Explorer to verify that the table and constraints have been created.
Implementing a Microsoft SQL Server 2008 Database   4-29




                                                                                                        MCT USE ONLY. STUDENT USE PROHIBITED
Task 4: Test the JobCandidateHistory table and constraints
1.     In SQL Server Management Studio, open the TestConstraints.sql script file
       in the E:MOD04LabfilesStarter folder.
2.     Use the INSERT statement to test inserting invalid data.
3.     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 exercise’s main tasks are:
       1.    Insert multiple rows into the JobCandidateHistory table.
       2.    Disable constraints on the JobCandidateHistory table.
       3.    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:Mod04LabfilesStarter folder, and then execute it with statistics
             enabled.
             Examine the performance statistics.


       Task 2: Disable constraints on the JobCandidateHistory table
       1.    Add a new query to the project. Change the query file name to
             Constraints.sql.
       2.    In the query window, type the appropriate Transact-SQL to disable the
             constraints on the HumanResources.JobCandidateHistory table.
       3.    Execute the query, and then save the query file.
       4.    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.     In the Constraints.sql query window, type the appropriate Transact-SQL to
       enable the constraints on the HumanResources.JobCandidateHistory table.
2.     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 candidate’s 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 exercise’s main tasks are:
       1.    Create the dJobCandidate trigger.
       2.    Test the dJobCandidate trigger.


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




                                                                                                        MCT USE ONLY. STUDENT USE PROHIBITED
Task 2: Test the dJobCandidate trigger
1.     In SQL Server Management Studio, open the TestTrigger.sql query file from
       the E:MOD04LabfilesStarter folder.
2.     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.    What is the difference between a constraint and a trigger?
       2.    Why implement check constraints if an application is already checking the
             input data?
       3.    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                                                        5-3
  Lesson 2: Retrieving XML by Using FOR XML                                               5-12
  Lesson 3: Shredding XML by Using OPENXML                                                5-21
  Lab 5A: Using XML                                                                       5-27
  Lesson 4: Introducing XQuery                                                            5-37
  Lesson 5: Creating XML Indexes                                                          5-43
  Lesson 6: Implementing XML Schemas                                                      5-48
  Lab 5B: Using XML                                                                       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                                   Data type
CustomerID                                     int
OrderDate                                      datetime
DueDate                                        datetime
AccountNumber                                  nvarchar(15)
ContactID                                      int
BillToAddressID                                int
ShipToAddressID                                int
ShipMethodID                                   int
SubTotal                                       money
TaxAmt                                         money

The second OPENXML query will insert data into the Sales.SalesOrderDetail table
and should use the following schema declaration:
Column name                                  Data type
OrderQty                                      Int
ProductID                                     Int
UnitPrice                                     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:Mod05LabfilesStarter folder.
•   A file named HistoricResumeSchema.xml containing the schema for the
    HistoricResumeSchemaCollection XML schema collection is provided in the
    E:Mod05LabfilesStarter folder.


Task 1: Create a SQL Server Scripts project in SQL Server Management
Studio
•   Create a new project.
    •   Name: Job Candidate History
    •   Location: E:Mod05LabfilesSolution
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:Mod05LabfilesStarter
             •     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:Mod05LabfilesStarter
      •   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 Schema-
    based 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/adventure-
    works/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/adventure-
    works/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/adventure-
           works/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.   What is XML?
   2.   What does the nodes() method do?
   3.   What are RAW Mode Queries?
   4.   What are AUTO Mode Queries?
   5.   What are EXPLICIT Mode Queries?
   6.   What are PATH Mode Queries?
   7.   What is the purpose of an XML schema?
   8.   When would you use untyped XML?
   9.   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                    Use for                             Where to find it
 SQL Server              • Integrated management              Start | All Programs |
 Management Studio         and development console            Microsoft SQL Server 2008

 Microsoft Visual        • Comprehensive                      Start | All Programs |
 Studio® 2008              development platform               Microsoft Visual Studio
                                                              2008

 SQL Server              • SQL Server, Services, and          Start | All Programs |
 Configuration Manager     networking protocols               Microsoft SQL Server 2008
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                                                         6-3
  Lesson 2: Creating and Managing Views                                                   6-9
  Lesson 3: Optimizing Performance by Using Views                                        6-19
  Lab: Implementing Views                                                                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 (T-
      SQL) 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 schema—it 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 views—the
    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 aren’t 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.   Create a SQL Server Scripts project.
2.   Create the HumanResources.vEmployeeDetails view.
3.   Test the HumanResources.vEmployeeDetails view.


Task 1: Create a SQL Server Scripts project
1.   Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd.
2.   Start the Server Management Studio and connect to the server.
3.   Create a new project.
     •   Name: AW_Views
     •   Location: E:Mod06LabfilesStarter
4.   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.   Examine this code.
       3.   Execute the code. Examine the Messages box and verify that the script
            completed without any errors.
       4.   Verify that the HumanResources.vEmployeeDetails view is listed in the
            Object Explorer.
       5.   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.
       •   File name: TestEmployeeView.sql
2.     In the blank query window, type the following code:

 Use AdventureWorks2008
 SELECT * FROM
 HumanResources.vEmployeeDetails


3.     Examine this code.
4.     Execute the code. Examine the Messages box and verify that the script
       completed without any errors.
5.     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.     Create a new query file.
       2.     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.     Examine this code.
       3.     Execute the code. Examine the Messages box and verify that the script
              completed without any errors.
       4.     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.   Prepare the SQL Server instances.
2.   Create a new query file.
3.   Create the Person.vContact distributed partitioned view.


Task 1: Prepare the SQL Server instances
•    Execute the following code:
     •   E:Mod06LabfilesStarter 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-01SQLINSTANCE2].AW_Contacts.Person.Contact
          UNION ALL
        SELECT * FROM [NY-SQL-01SQLINSTANCE3].AW_Contacts.Person.Contact


       2.     Examine this code.
       3.     Execute the code. Examine the Messages box and verify that the script
              completed without any errors.
       4.     Verify that the Person.vContact view is listed in the Object Explorer.
       5.     Verify that the correct columns are listed in the view.
       6.     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.     Examine this code.
       9.     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.   How does SQL Server store the view in the database?
       2.   What is a Standard non-indexed view?
       3.   What is an unbroken ownership chain?
       4.   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                    Use for                                    Where to find it
    SQL Server              • Integrated management and                Microsoft SQL Server
    Management Studio          development console                     2008

    Microsoft Visual        • Comprehensive development                Microsoft Visual Studio
    Studio® 2008               platform                                2008

    SQL Server              • SQL Server, Services, and                Microsoft SQL Server
    Configuration Manager      networking protocols                    2008
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                                                          7-3
  Lesson 2: Creating Parameterized Stored Procedures                                        7-12
  Lesson 3: Working with Execution Plans                                                    7-17
  Lesson 4: Handling Exceptions                                                             7-24
  Lab: Implementing Stored Procedures                                                       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 database—except 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 exception-
       handling 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 TRY…CATCH 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 TRY…CATCH 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
            TRY…CATCH 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:MOD07LabfilesStarter 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.   Create and test the GetDiscounts stored procedure.
2.   Create and test the GetDiscountsForCategory stored procedure.
3.   Create and test the GetDiscountsForCategoryAndDate stored procedure.
4.   Create and test the AddDiscount stored procedure.


Task 1: Create and test the GetDiscounts stored procedure
1.   Start 6232A-NY-SQL-01, and log on as Student with the password of
     Pa$$w0rd.
2.   Open the AWProgrammability.ssmssln solution in the
     E:MOD07LabfilesStarter folder.
3.   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.
       2.   Test the Sales.GetDiscountsForCategory stored procedure using 'Reseller' for
            the @Category value, and then review the results.


       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.
       2.   Test the Sales.GetDiscountsForCategoryAndDate stored procedure using
            'Reseller' for the @Category value and the default value for the @DateToCheck
            parameter. Review the results.
       3.   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.


       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.
       2.   Test the Sales.AddDiscount stored procedure by using the following parameter
            values:
            Parameter                   Value
            @Description                'Half price of everything'
            @DiscountPct                .5
            @Type                       'Seasonal Discount'
            @Category                   'Customer'
            @StartDate                  Local variable with current date from GETDATE function
            @EndDate                    Local variable with date one month from current date
            @MinQty                     0
            @MaxQty                     20
Implementing a Microsoft SQL Server 2008 Database   7-31




                                                                                                   MCT USE ONLY. STUDENT USE PROHIBITED
3.   Confirm that a new special offer was create by displaying the @NewProductID
     OUTPUT parameter value.
4.   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.   View text-based execution plans.
       2.   View graphical execution plans.
       3.   Tune the database to improve performance.
       4.   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 Transact-
            SQL 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.   If a nonqualified user-defined stored procedure is specified, in which order
            does the Database Engine searches for the procedure?
       2.   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                                                           8-3
  Lesson 2: Working with Functions                                                          8-9
  Lesson 3: Controlling Execution Context                                                  8-13
  Lab: Implementing Functions                                                              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 BEGIN…END 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 user-
           provided 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 user-
defined 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:MOD08LabfilesStarter 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-01Adam 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.   Create and test the GetMaximumDiscountsForCategory user-defined function.
       2.   Create and test the GetDiscountsForDate user-defined function.
       3.   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 user-
defined function
1.   Start the NY-SQL-01 virtual machine.
2.   Logon as Administrator with the password: Pa$$w0rd.
3.   Run the createnewuser.vbs script located at E:MOD8LabfilesStarter.
4.   Open Command Prompt. Browse to E:MOD08LabfilesStarter.
5.   Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER.
6.   Log off Administrator and then logon as Student with the password:
     Pa$$w0rd.
7.   Open the SQL Server Management Studio scripts project located at
     E:MOD8LabfilesStarterAWProgrammability.ssmssln.
8.   In Solution Explorer open the query file InitilizeData.sql and execute its
     complete contents, ensure that it executes successfully.
9.   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.   In the UserDefinedFunctions.sql query locate the Create
            Sales.GetDiscountsForDate comment.
       2.   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.   Locate the Test Sales.GetDiscountsForDate comment.
       4.   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.   In the UserDefinedFunctions.sql query locate the Create
     Sales.GetDiscountedProducts comment.
2.   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)

                                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


       3.   Locate the Test Sales.GetDiscountedProducts comment.
       4.   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-SQL-
01Adam 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.   Create the GetCurrencyRate user-defined function.
2.   Establish a database trust relationship between the AdventureWorks2008
     database and the AdventureWorksDW2008 database.
3.   Create and test the GetCurrencyDiscountedProducts user-defined function.


Task 1: Create the GetCurrencyRate user-defined function
1.   In Solution Explorer open the query file ExecutionContext.sql.
2.   Connect to server NY-SQL-01 using Windows Authentication.
3.   Select and Execute the USE AdventureWorks2008 statement.
4.   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.   Locate the Test Sales.GetCurrencyRate comment.
       7.   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-01Adam" 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.   In Solution Explorer open the TrustRelationship.sql query file.
       2.   Execute the USE AdventureWorksDW2008 statement.
       3.   Locate the Create the user for the NY-SQL-01Adam 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-01Adam]
 GO


5.   Locate the Grant Authenticate permission on the database comment.
6.   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.   Locate the Grant SELECT permission to Adam comment.
8.   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 user-
defined function
1.   In Solution Explorer open the ExecutionContext.sql query file.
2.   Select and execute the USE AdventureWorks2008 statement.
3.   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.   Verify that the statement executes successfully.
       6.   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.   Review the query results and verify that the statement executes successfully.
9.   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.   When using the EXECUTE AS clause, what privileges should the login or user
            have?
       2.   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                        9-4
  Lesson 2: Importing and Configuring Assemblies                                          9-10
  Lesson 3: Creating Managed Database Objects                                             9-15
  Lab: Implementing Managed Code in a Database                                            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 Transact-
      SQL. 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 user-
defined 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:MOD09LabfilesStarter 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.     Start the NY-SQL-01 virtual machine and log on as Administrator.
2.     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.     Open the AWorks_CLR.ssmssln solution.
2.     Execute the Initialize.sql query file.
3.     Open the ImportAssembly.sql query file and add and run the code to enable
       CLR Integration.
4.     Add and run the code to create the AWorksUtilities assembly.
5.     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:MOD09LabfilesStarter 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.   Create the SaveXML managed stored procedure referencing the external
            assembly.
       2.   Create the GetLongDate managed user-defined function referencing the
            external assembly.
       3.   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.   Create the Concatenate managed aggregate function referencing the external
     assembly.
5.   Create the IPAddress managed user-defined type referencing the external
     assembly.


Task 1: Create the SaveXML managed stored procedure referencing
the external assembly
1.   Open the SaveXML.sql query file and add the code to create the SaveXML
     stored procedure.
2.   Highlight and run the new code.
3.   Highlight and run the DECLARE, SET, and EXEC statements.
4.   Add code to change the security permissions.
5.   Highlight and run the ALTER ASSEMBLY statement.
6.   Highlight and run the DECLARE, SET, and EXEC statements.
7.   Save the SaveXML.sql file.
8.   Using Windows Explorer check for the existence of the Output.xml file in the
     E:MOD09LabfilesStarter folder.
9.   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.   Open the GetLongDate.sql query file.
2.   Add the code to create the GetLongDate function then highlight and run the
     code.
3.   Select and run the SELECT statement and execute it.
4.   Confirm that the records returned display with a long OrderDate value.
5.   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.     Open the EmailChange.sql query file.
       2.     Add and execute the code to create the EmailChange trigger.
       3.     Highlight and execute the first UPDATE statement
       4.     Highlight and execute the second UPDATE statement.
       5.     Save the EmailChange.sql file.


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


       Task 5: Create the IPAddress managed user-defined type referencing
       the external assembly
       1.     Open the IPAddress.sql query file.
       2.     Add and execute the code to create the new IPAddress type
       3.     Highlight and execute the SELECT statements.
       4.     Confirm that three result sets are displayed that show the IPAddress value in
              various forms.
       5.     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.   When is CLR integration of managed code the best option for creating
            database objects?
       2.   When is Transact-SQL the best choice?
       3.   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                                 Troubleshooting tip
  When using a managed database
  object you get an error indicating
  that the execution of user code in
  the .NET framework is disabled.


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                                             10-3
  Lesson 2: Managing Transactions                                                         10-11
  Lesson 3: Understanding SQL Server Locking Architecture                                 10-25
  Lesson 4: Managing Locks                                                                10-34
  Lab: Managing Transactions and Locks                                                    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 administrator’s perspective, the primary concerns are the
    number of users, the number of transactions, and the throughput. From the
    user’s 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 table-
             level.
             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             IS        S            U            IX            SIX          X

    Intent shared (IS)         Yes       Yes          Yes          Yes           Yes          No

    Shared (S)                 Yes       Yes          Yes          No            No           No

    Update (U)                 Yes       Yes          No           No            No           No

    Intent exclusive (IX)      Yes       No           No           Yes           No           No

    Shared with intent         Yes       No           No           No            No           No
    exclusive (SIX)

    Exclusive (X)              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                                        Description
          READ COMMITTED with                           Directs SQL Server to use shared locks
          READ_COMMITTED_SNAPSHOT OFF                   while reading. At this level, you cannot
                                                        experience dirty reads.

          READ COMMITTED with                           Directs SQL Server to use row
          READ_COMMITTED_SNAPSHOT ON                    versioning instead of locking. The data
                                                        is not protected from updates made
                                                        by other transactions.

          READ UNCOMMITTED                              Directs SQL Server not to issue shared
                                                        locks and does not honor exclusive
                                                        locks. You can experience dirty reads.

          REPEATABLE READ                               Indicates that dirty reads and
                                                        nonrepeatable reads cannot occur.
                                                        Shared locks are held until the end of
                                                        the transaction.

          SERIALIZABLE                                  Prevents other users from updating or
                                                        inserting new rows that match the
                                                        criteria in the WHERE clause of the
                                                        transaction. Phantoms cannot occur.

        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                                 Value

  textsize                                   2147483627

  language                                   us_english

  dateformat                                 mdy

  datefirst                                  7

  ...

  isolation level                            read uncommitted

  (13 row(s) affected)



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 cost-
effective 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 transaction’s 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.   Notifies the deadlock victim’s application (with message number 1205).
        3.   Cancels the deadlock victim’s current request.
        4.   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.   In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch.
    2.   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.     Start SQL Server Management Studio and connect to the NY-SQL-01 instance
               by using Windows authentication.
        2.     Open the script E:Mod10LabfilesStarterTran1.sql and connect to the
               NY-SQL-01 instance by using Windows authentication.
        3.     Review the script.
        4.     Add a statement to begin a transaction in the appropriate place.
        5.     Execute the script. Notice that the transaction has not ended.
        6.     Add a statement to commit the transaction in the appropriate place.
        7.     Execute the statement that you have just added to end the transaction.
        8.     Execute the last two statements of the script to verify that the changes have
               been committed to the database.
        9.     Close the file.


        Task 3: Create and rollback a transaction
        1.     Open the script E:Mod10LabfilesStarterTran2.sql and connect to the
               NY-SQL-01 instance by using Windows authentication.
        2.     Review the script.
        3.     Add a statement to roll back the transaction in the appropriate place.
        4.     Execute the script and verify that the changes are not made and the
               transaction is complete.
        5.     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.   Start SQL Server Management Studio and connect to the NY-SQL-01 instance
     by using Windows authentication.
2.   Use the Activity Monitor window to review the current lock information.
3.   Create a new query to select the following columns from the
     sys.dm_tran_locks dynamic management view.
     •   resource_type
     •   request_mode
     •   request_type
     •   request_status
     •   request_session_id
4.   Execute the query and review the results that show the lock on the master
     database.
5.   Open the script E:Mod10LabfilesStarterLock1.sql and connect to the
     NY-SQL-01 instance by using Windows authentication.
6.   Review and execute the script, noting the SPID of your connection.
7.   Execute the query against the sys.dm_tran_locks dynamic management view
     and note the new locks listed.
8.   Use the Activity Monitor window to review the additional locks held.
9.   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.     Start SQL Server Management Studio and connect to the NY-SQL-01 instance
               by using Windows authentication.
        2.     Open E:Mod10LabfilesStarterLock1.sql and connect to the NY-SQL-01
               instance by using Windows authentication.
        3.     Review the contents of the file and execute the script.
        4.     Open E:Mod10LabfilesStarterLock2.sql and connect to the NY-SQL-01
               instance by using Windows authentication.
        5.     Review the contents of the file and execute the script.
        6.     Open E:Mod10LabfilesStarterLockList.sql and connect to the NY-SQL-
               01 instance by using Windows authentication.
        7.     Execute the script and notice the WAIT entry in the request_status column.
        8.     Cancel the Lock2.sql script and verify that the waiting transaction has been
               cancelled.


        Task 3: Set the lock timeout
        1.     Add a SET statement to the start of the Lock2.sql script to change the lock
               timeout to five seconds.
        2.     Execute the query and note that the query now times out.
        3.     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.   What is the default Transaction Isolation Level in SQL Server?
   2.   How long is a lock held in a read operation when using the READ
        COMMITTED isolation level?
   3.   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                                 Troubleshooting tip
            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.

        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-out-
               transaction 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                                                        11-3
  Lesson 2: Creating Service Broker Objects                                               11-14
  Lesson 3: Sending and Receiving Messages                                                11-22
  Lab: Using Service Broker                                                               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 SendingReceiving 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 company’s Web site. To minimize
    the impact to the site’s 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                       Value

            Name                            //AW/EMail/CustomerDetails

            Validation                      WELL_FORMED_XML

        •     Use the following details to create a contract that will be supported by the
              EmailService service.

            Property                       Value
            Name                            //AW/EMail/SendCustomerDetails

            Message type                    //AW/EMail/CustomerDetails

            Message Direction               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                        Value

     Name                            CustomerSvc.NewCustomerQueue

     Queue status                    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                        Value

     Name                            EMailSvc.NewCustomerEmailQueue

     Queue status                    OFF

•      Use the following details to create the CustomerService service.

    Property                        Value
     Name                            //AW/Sales/CustomerService

     Queue                           CustomerSvc.NewCustomerQueue

•      Use the following details to create the EmailService service.

    Property                        Value

     Name                            //AW/EMail/EmailService

     Queue                           EMailSvc.NewCustomerEmailQueue

     Contract                        //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.     Launch SQL Server Management Studio.
2.     Create the AW_ServiceBroker SQL Server Scripts project.
11-30   Using Service Broker




                                                                                                 MCT USE ONLY. STUDENT USE PROHIBITED
        3.    Configure the AdventureWorks database for Service Broker.
        4.    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.    Open SQL Server Management Studio and connect to the default database
              engine.
        2.    Create a new project named AW_ServiceBroker in the
              E:MOD11LabfilesStarter folder.


        Task 3: Configure the AdventureWorks database for Service Broker
        1.    Create a new query named PrepareDatabase.sql in the
              AdventureWorks2008 database.
        2.    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 e-
        mail solution
        1.    Create a new query named CreateServiceBrokerObjects.sql in the
              AdventureWorks2008 database.
        2.    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      Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker
               project.
        2.     Implement the CustomerService service.


        Task 1: Add the CreateEmailNewCustomerSP.sql query file to the
        AW_ServiceBroker project
        1.     Use the Add Existing Item option to add an item to the project.
        2.     Add the CreateEmailNewCustomerSP.sql query file in the
               E:MOD11LabfilesStarter folder to the project.


        Task 2: Implement the CustomerService service
        1.     Execute the CreateEmailNewCustomerSP.sql query.
        2.     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 Transact-
SQL 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                               Value

     Name                               EMailSvc.NewCustomerEmailQueue

     Queue status                       ON

     Activation status                  ON

     Procedure name                     AdventureWorks.EMailSvc.uspSendCustomerEmail

     Maximum readers                    5

     Execute as                         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.     Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project.
2.     Implement the EmailService service.
3.     Configure the target service for automatic activation.
4.     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.     Use the Add Existing Item option to add an item to the project.
        2.     Add the CreateSendEmailSP.sql query file in the
               E:MOD11LabfilesStarter folder to the project.


        Task 2: Implement the EmailService service
        1.     Execute the CreateSendEmailSP.sql query.
        2.     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.     Create a new query named AlterServiceBrokerQueue.sql.
        2.     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.
        3.     Execute the query.


        Task 4: Test the EmailService service
        1.     Use the Add Existing Item option to add an item to the project.
        2.     Add the TestEmailService.sql query file in the E:MOD11LabfilesStarter
               folder to the project.
        3.     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.   What does Service Broker security rely on and why?
   2.   How can you ensure that message delivery is correctly supported?
   3.   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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Student using the password Pa$$w0rd.
3.   Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL
     Server Management Studio.
4.   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.
5.   Maximize Microsoft SQL Server Management Studio.
6.   In Object Explorer expand NY-SQL-01, right-click Databases, and then click
     New Database.
7.   The New Database window appears. Maximize the window.
8.   On the General page, in the Database name field, enter AW_IT_Assets.
9.   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:MOD01Labfiles, 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.     In Microsoft SQL Server Management Studio, click File, point to Open, and
       then click File. The Open File dialog box appears.
2.     Browse to E:MOD01Labfiles, select AW_IT_Assets_DBScript, and then
       click Open.
3.     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.     Right-click NY-SQL-01 | Databases in Object Explorer and then click Refresh.
5.     Expand NY-SQL-01 | Databases. The AW_IT_Assets database has been added
       to the Databases folder.
6.     Close the query editor without saving the query.
7.     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.     In SQL Server Management Studio expand NY-SQL-01 | Databases |
       AW_IT_Assets | Security, right-click Users, and then click New User.
2.     In the Database User window, enter Katie in the User name field and NY-
       SQL-01Katie 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.     Click New Query on the Standard toolbar.
       2.     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.     On the toolbar, click Execute.
       4.     Close the query editor without saving the query.


       Task 3: Create a schema and assign ownership to a user
       1.     In SQL Server Management Studio, on the toolbar, click New Query.
       2.     In the new, blank query window, type the following T-SQL statement:

              SELECT *
              FROM INFORMATION_SCHEMA.SCHEMATA
              WHERE SCHEMA_NAME = 'TechSupport';
              GO


       3.     On the toolbar, click Execute.
       4.     Close the query editor without saving the query.
       5.     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.   In SQL Server Management Studio, on the toolbar, click New Query.
2.   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:MOD01LabfilesSnapshotsAW_IT_Assets_Data1.ss' ),
     ( NAME = AW_IT_Assets_Data2, FILENAME =
     ‘E:MOD01LabfilesSnapshotsAW_IT_Assets_Data2.ss’ )
     AS SNAPSHOT OF AW_IT_Assets;
     GO


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


Task 2: Alter the database
1.   Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables, right-click the
     TechSupport.Hardware table, and then click Delete.
2.   The Delete Object window appears. Click OK.
3.   Expand NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas,
     right-click the TechSupport schema, and then click Delete.
4.   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.     In Object Explorer, expand NY-SQL-01 | Databases, right-click the
              AW_IT_Assets database, and then click New Query.
       2.     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.     On the toolbar, click Execute.
       4.     Right-click NY-SQL-01 | Databases, and then click Refresh.
       5.     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.
       6.     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.
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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Student using the password Pa$$w0rd.
3.   Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL
     Server Management Studio.
4.   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.
5.   Maximize Microsoft SQL Server Management Studio.
6.   Expand NY-SQL-01 | Databases, right-click the AdventureWorksDW2008
     database, and then click New Query.
7.   In the new, blank query window, type the following T-SQL statement:

     CREATE TYPE ShortDescription
     FROM nvarchar(10) NOT NULL;


8.   On the toolbar, click Execute.
9.   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.     Right-click the AdventureWorksDW2008 database, and then click New
              Query.
       2.     In the new, blank query window, type the following T-SQL statement:

              CREATE TYPE CashValue
              FROM decimal(8,2) NOT NULL;


       3.     On the toolbar, click Execute.
       4.     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.
       5.     Close the query editor without saving the query.
       6.     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.
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.   Right-click the AdventureWorksDW2008 database, and then click New
     Query.
2.   In the new, blank query window, type the following T-SQL statement:

     SELECT
          CAST('2007-05-08 12:35:29.1234567       +12:15' AS time(7)) AS
     'time'
         ,CAST('2007-05-08 12:35:29.1234567       +12:15' AS date) AS 'date'
         ,CAST('2007-05-08 12:35:29.123' AS       smalldatetime) AS
             'smalldatetime'
         ,CAST('2007-05-08 12:35:29.123' AS       datetime) AS 'datetime'
         ,CAST('2007-05-08 12:35:29.1234567       +12:15' AS datetime2(7)) AS
             'datetime2'
         ,CAST('2007-05-08 12:35:29.1234567       +12:15' AS
     datetimeoffset(7)) AS
             'datetimeoffset';


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


Task 2: Convert sample data into new data type formats using T-SQL
1.   Right-click the AdventureWorksDW2008 database, and then click New
     Query.
2.   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.     On the toolbar, click Execute and then review the results.
        4.     Close the query editor without saving the query.
        5.     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.     In SQL Server Management Studio, on the toolbar, click New Query.
        2.     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.     On the toolbar, click Execute.
        4.     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.
        5.     Close the query editor without saving the query.


        Task 2: Create a table named Refunds
        1.     Right-click the AdventureWorksDW2008 database, and then click New
               Query.
        2.     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.
5.     Close the query editor without saving the query.
6.     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.


Exercise 4: Creating Partitioned Tables
Task 1: Limit result sets by using the INTERSECT clause with the
SELECT statement
1.     On the SQL Server Management Studio toolbar, click File, point to Open, and
       then click File.
2.     Browse to E:MOD02LabfilesScripts, select the file named
       partition_prep.sql, and then click Open.
3.     On the toolbar, click Execute.
4.     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.     In SQL Server Management Studio, on the toolbar, click New Query.
        2.     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.     On the toolbar, click Execute.
        4.     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.
        5.     Close the query editor without saving the query.


        Task 3: Review the partitioning implementation
        1.     In Object Explorer, right-click the AdventureWorksDW2008 database, and
               then click Refresh.
        2.     Expand NY-SQL-01 | AdventureWorksDW2008 | Tables, right-click the
               dbo.ReturnsArchive table, and then click Properties.
        3.     In the Table Properties window, click Storage on the left.
        4.     Review the Compression, Filegroups, and Partitioning information in the
               right pane of the Table Properties window, and then click OK.
        5.     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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on as Student with the password of Pa$$w0rd.


Task 2: Create a SQL Server Scripts project
1.   Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL
     Server Management Studio.
2.   In the Connect to Server dialog box, click Connect.
3.   On the File menu, click New, and then click Project.
4.   In the New Project dialog box, in the Name field, type AW_Indexes. Change
     the Location field to E:MOD03LabfilesStarter.
5.   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.     On the Project menu, click New Query.
        2.     In Solution Explorer, right-click SQLQuery1.sql, click Rename, type
               CreateIndex.sql, and then press ENTER.
        3.     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.     On the toolbar, click Execute.
        5.     On the File menu, click Save All.
        6.     If Object Explorer is not visible, on the View menu, click Object Explorer.
        7.     In Object Explorer, expand Databases, expand AdventureWorks2008, and
               then expand Tables.
        8.     Expand Production.Product, expand Indexes, and then verify that the
               Ix_Product_Supply_Chain index is listed.
        9.     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.   In Microsoft SQL Server Management Studio, on the File menu, click Open,
     and then click File.
2.   In the Open File dialog box, browse to the E:MOD03LabfilesStarter
     folder, click the aw2008sampleproductadd.sql file, and then click Open.
3.   In Microsoft SQL Server Management Studio, on the toolbar, click Execute.
4.   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.   In Object Explorer, make sure that Databases | AdventureWorks2008 |
     Tables | Production.Product | Indexes is still expanded.
2.   Right-click AK_Product_ProductNumber (Unique, Non-Clustered), and
     then click Properties.
3.   In the Index Properties – AK_Product_ProductNumber dialog box, in the
     Select a page pane, click Fragmentation.
4.   In the details pane, under Fragmentation, notice that Total Fragmentation is
     66.67%.
5.   Click Cancel.
6.   In Object Explorer, right-click AK_Product_ProductNumber (Unique, Non-
     Clustered), and then click Reorganize.
7.   In the Reorganize Indexes dialog box, click OK.
8.   In Object Explorer, right-click AK_Product_ProductNumber (Unique, Non-
     Clustered), and then click Properties.
9.   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.     In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered),
               and then click Properties.
        2.     In the Index Properties – AK_Product_Name dialog box, in the Select a page
               pane, click Fragmentation.
        3.     In the details pane, notice that Total fragmentation is 80.00%.
        4.     Click Cancel.
        5.     In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered),
               and then click Rebuild.
        6.     In the Rebuild Indexes dialog box, click OK.
        7.     In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered),
               and then click Properties.
        8.     In the Index Properties – AK_Product_Name dialog box, in the Select a page
               pane, click Fragmentation.
        9.     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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on as Student with the password of Pa$$w0rd.


Task 2: Create a SQL Server Scripts project
1.   Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL
     Server Management Studio.
2.   In the Connect to Server dialog box, click Connect.
3.   On the File menu, click New, and then click Project.
4.   In the New Project dialog box, in the Name field, type AW_DataIntegrity.
     Change the Location field to E:MOD04LabfilesStarter.
5.   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.    On the Project menu, click New Query.
        2.    In Solution Explorer, right-click SQLQuery1.sql, click Rename, type
              TableAndContraints.sql, and then press ENTER.
        3.    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.    On the toolbar, click Execute.
        5.    On the File menu, click Save All.
        6.    If Object Explorer is not visible, on the View menu, click Object Explorer.
        7.    In Object Explorer, expand Databases, expand AdventureWorks2008,
              expand Tables, and then verify that the
              HumanResources.JobCandidateHistory table is listed. You may need to right-
              click Tables, and then click Refresh to see the new table.
        8.    In Object Explorer, expand the HumanResources.JobCandidateHistory table.
        9.    In the HumanResources.JobCandidateHistory table, expand the Columns,
              Keys, Indexes, and Constraints folders, and then verify that the necessary
              constraints have been implemented.
Lab: Implementing Data Integrity by Using Constraints   L4-19




                                                                                                            MCT USE ONLY. STUDENT USE PROHIBITED
Task 4: Test the JobCandidateHistory table and constraints
1.     In SQL Server Management Studio, on the File menu, click Open, and then
       click File.
2.     In the Open File dialog box, browse to E:MOD04LabfilesStarter, click
       TestConstraints.sql, and then click Open.
3.     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.
4.     Below the comment This should succeed, select the code, and then on the
       toolbar, click Execute. The INSERT operation should succeed.
5.     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.


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


Task 2: Disable constraints on the JobCandidateHistory table
1.     On the Project menu, click New Query.
2.     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.     On the toolbar, click Execute.
        5.     Verify that the commands completed successfully.
        6.     On the File menu, click Save All.
        7.     Switch to the InsertTestData.sql query window.
        8.     On the toolbar, click Execute.
        9.     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.     Switch to the Constraints.sql query window.
        2.     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.     Select the new statements, and then on the toolbar, click Execute.
        4.     Verify that the commands completed successfully.
        5.     On the File menu, click Save All.
        6.     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.   In SQL Server Management Studio, on the Project menu, click New Query.
2.   In Solution Explorer, right-click SQLQuery1.sql, click Rename, type
     Trigger.sql, and then press ENTER.
3.   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.   On the toolbar, click Execute.
5.   On the File menu, click Save All.
6.   In Object Explorer, expand Databases, expand AdventureWorks2008, and
     then expand Tables. Right-click Tables, and then click Refresh.
7.   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.     On the File menu, click Open, and then click File.
        2.     In the Open File dialog box, browse to the E:MOD04LabfilesStarter
               folder, click the TestTrigger.sql query file, and then click Open.
        3.     On the toolbar, click Execute to execute the query script.
        4.     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.
        5.     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.
        6.     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.
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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Student using the password Pa$$w0rd.
3.   Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server
     Management Studio.
4.   If the Connect to Server dialog box appears, click Connect.
5.   On the File menu, point to Open, and then click Project/Solution.
6.   The Open Project dialog box appears. Browse to the
     E:Mod05LabfilesStarter folder, click the XML.ssmssln solution, and then
     click Open.
     a.   If the Connect to Server dialog box appears, click Connect.
     b.   If Solution Explorer is not visible, on the View menu, click Solution
          Explorer.
     c.   If necessary, in the Solution Explorer pane, expand XML | Queries.
7.   In the Solution Explorer, double-click the FORXML.sql query to open it.
8.   Switch to the FORXML query.
9.   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.   In the Solution Explorer pane, double-click the OPENXML.sql query to open
             it.
        2.   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.
        3.   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


        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.     On the toolbar, click Execute.
8.     Examine the Results and Messages boxes and verify that the script completed
       without any errors.
9.     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.     On the File menu, point to New, and then click Project.
2.     The New Project dialog box appears. In the Templates box, makes sure SQL
       Server Scripts is highlighted.
3.     In the Name field, type Job Candidate History.
4.     In the Location field, type E:Mod05LabfilesStarter.
5.     Click OK.
6.     In the Solution Explorer, right-click Connections, and then click New
       Connection.
7.     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.   In the Solution Explorer, right-click Queries, and then click New Query.
        2.   If the Connect to Server dialog box appears, click Connect.
        3.   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.   On the toolbar, click Execute.
        5.   If the Connect to Server dialog box appears, click Connect.
        6.   Examine Messages box and verify that the script completed without any
             errors.
        7.   On the File menu, click Save SQLQuery1.sql As.
        8.   The Save File As dialog box appears. In the File name field, type
             CreateJobCandidateHistoryTable.sql, and then click Save.
        9.   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.   In the Solution Explorer, right-click Queries, and then click New Query.
2.   If the Connect to Server dialog box appears, click Connect.
3.   On the File menu, click Save SQLQuery2.sql As.
4.   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.   In the Solution Explorer, right-click Job Candidate History, point to Add, and
     then click Existing item.
2.   The Add Existing Item - Job Candidate History dialog box appears. In the
     File of type list, click XML Files.
3.   Navigate to the E:Mod05LabfilesStarter folder.
4.   Click HistoricResumeSchema.xml, and then click Add.
5.   In the details pane, examine the new schema definition.
6.   In the Solution Explorer, right-click Job Candidate History, point to Add, and
     then click Existing item.
7.   The Add Existing Item - Job Candidate History dialog box appears. In the
     File of type list, click SQL Server files.
8.   Navigate to the E:Mod05LabfilesStarter folder.
9.   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/adventure-
             works/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.   In the Solution Explorer, right-click Queries, and then click New Query.
        2.   If the Connect to Server dialog box appears, click Connect.
        3.   On the File menu, click Save SQLQuery3.sql As.
        4.   The Save File As dialog box appears. In the File name field, type
             AlterCandiateTable.sql, and then click Save.
        5.   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.   On the toolbar, click Execute.
        7.   Examine Messages box and verify that the script completed without any
             errors.
        8.   In Object Explorer, right-click AdventureWorks2008, and then click Refresh.
        9.   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.   In the Solution Explorer, right-click Job Candidate History, point to Add, and
     then click Existing item.
2.   The Add Existing Item - Job Candidate History dialog box appears. In the
     File of type list, click SQL Server files.
3.   Navigate to the E:Mod05LabfilesStarter folder.
4.   Click TestXMLSchema.sql, and then click Add.
5.   If the Connect to Server dialog box appears, click Connect.
6.   In the details pane, below the comment This should fail, select the INSERT
     code.
7.   On the toolbar, click Execute.
8.   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.   In the Solution Explorer, right-click Job Candidate History, point to Add, and
             then click Existing item.
        2.   The Add Existing Item - Job Candidate History dialog box appears. In the
             File of type list, click SQL Server files.
        3.   Navigate to the E:Mod05LabfilesStarter folder.
        4.   Click AddCandidate.sql, and then click Add.
        5.   If the Connect to Server dialog box appears, click Connect.
        6.   On the toolbar, click Execute.
        7.   Examine the Message box and verify that the script completed without any
             errors.
        8.   In the Solution Explorer, double-click SelectCandidates.sql.
        9.   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.     In the Solution Explorer pane, right-click Queries, and then click New Query.
2.     If the Connect to Server dialog box appears, click Connect.
3.     On the File menu, click Save SQLQuery5.sql As.
4.     The Save File As dialog box appears. In the File name field, type
       xmlMethods.sql, and then click Save.
5.     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/adventure-
       works/Resume' AS "RES")
       SELECT NationalIDNumber, Resume.query('
          /RES:Resume/RES:Name
       ') as Result
       FROM HumanResources.JobCandidateHistory
       GO


6.     On the toolbar, click Execute.
7.     Examine the Results and Messages boxes and verify that the script completed
       without any errors.
8.     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/adventure-
             works/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.   Select the statements you just added, and then on the toolbar, click Execute.
        3.   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/adventure-
             works/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.     Select the statements you just added, and then on the toolbar, click the
       Execute button.
4.     Examine the Messages box and verify that the script completed without any
       errors.


Task 4: Verify the updated candidate's address
1.     Select the statements from Task 2.
2.     On the toolbar, click Execute.
3.     Verify that the desired results are returned as 7194 Fourth St. Rockhampton.
4.     On the File menu, click Save All.
5.     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.     In the Solution Explorer pane, right-click Queries, and then click New Query.
2.     If the Connect to Server dialog box appears, click Connect.
3.     On the File menu, click Save SQLQuery6.sql As.
4.     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.     On the toolbar, click Execute to execute the query.
        4.     Examine the Messages box and verify that the script completed without any
               errors.
        5.     On the File menu, click Save All.
        6.     In the navigation pane, expand Databases | AdventureWorks2008 | Tables
               | Production.Illustration | Indexes.
        7.     Verify that the new XML indexes are listed and are correct.
        8.     Close SQL Server Management Studio.
        9.     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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Administrator using the password Pa$$w0rd.
3.   Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server
     Management Studio.
4.   The Connect to Server dialog box appears. Click Connect.
5.   On the File menu, point to New, and then click Project.
6.   The New Project dialog box appears. In the Templates box, make sure SQL
     Server Scripts is highlighted.
7.   In the Name field, type AW_Views.
8.   In the Location field, type E:Mod06LabfilesStarter.
9.   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.   On the toolbar, click Execute.
        3.   Examine Messages box and verify that the script completed without any
             errors.
        4.   On the File menu, click Save All.
        5.   In Object Explorer, expand Databases | AdventureWorks2008 | Views.
        6.   Verify that the HumanResources.vEmployeeDetails view is listed.
Lab: Implementing Views   L6-43




                                                                                                   MCT USE ONLY. STUDENT USE PROHIBITED
7.     In Object Explorer, expand Databases | AdventureWorks2008 | Views |
       HumanResources.vEmployeeDetails | Columns.
8.     Verify that the correct columns are listed in the view.


Task 3: Test the HumanResources.vEmployeeDetails view
1.     In the Solution Explorer, right-click Queries, and then click New Query.
2.     If the Connect to Server dialog box appears, click Connect.
3.     On the File menu, click Save SQLQuery2.sql As.
4.     The Save File As dialog box appears. In the File name field, type
       TestEmployeeView.sql, and then click Save.
5.     In the query window, type the following code:

       Use AdventureWorks2008
       SELECT * FROM
       HumanResources.vEmployeeDetails


6.     On the toolbar, click Execute.
7.     Examine the Results and Messages boxes and verify that the script completed
       without any errors.
8.     Verify that correct data is returned from the view.
9.     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.     In the Solution Explorer pane, right-click Queries, and then click New Query.
        2.     If the Connect to Server dialog box appears, click Connect.
        3.     On the File menu, click Save SQLQuery3.sql As.
        4.     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.     On the toolbar, click Execute.
        3.     Examine Messages box and verify that the script completed without any
               errors.
        4.     On the File menu, click Save All.
        5.     In Object Explorer, expand Databases | AdventureWorks2008 | Views |
               HumanResources.vEmployeeDetails | Indexes.
        6.     Verify that the IX_vEmployeeDetails index is listed.
        7.     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.   Click Start, and then click Computer.
2.   In Microsoft® Windows® Explorer, navigate to the
     E:Mod06LabfilesStarter folder.
3.   Double-click LabSetup.cmd to run the script that configures the servers for
     the partitioned view.
4.   When the script completes, close Windows Explorer.


Task 2: Create a new query file
1.   In the Solution Explorer pane, right-click Queries, and then click New Query.
2.   If the Connect to Server dialog box appears, click Connect.
3.   On the File menu, click Save SQLQuery4.sql As.
4.   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-01SQLINSTANCE2].AW_Contacts.Person.Contact
       UNION ALL
     SELECT * FROM [NY-SQL-01SQLINSTANCE3].AW_Contacts.Person.Contact


2.   On the toolbar, click Execute.
3.   On the File menu, click Save All.
4.   In Object Explorer, right-click Databases, and then click Refresh.
L6-46   Module 6: Implementing Views




                                                                                                     MCT USE ONLY. STUDENT USE PROHIBITED
        5.     Expand Databases | AW_Contacts | Views.
        6.     Verify that the Person.vContact view is listed.
        7.     In Object Explorer, expand Databases | AW_Contacts | Views |
               Person.vContact | Columns.
        8.     Verify that the correct columns are listed.
        9.     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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on as Student with the password of Pa$$w0rd.
3.   Click Start, right-click Computer and then click Explore.
4.   In Windows Explorer browse to E:MOD07LabfilesStarter.
5.   Double-click the AWProgrammability project file. The Microsoft SQL Server
     Management Studio window opens.
6.   If the Solution Explorer is not visible in the right pane, click View | Solution
     Explorer.
7.   In the Solution Explorer, double-click InitilizeData.sql.
8.   If the Connect to Sever dialog box appears, connect to server NY-SQL-01
     using Windows Authentication. Click Connect.
9.   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.   Select the text between the --Create GetDiscountsForCategory comment and
             the following comment.
        2.   On the toolbar, click the Execute button to execute the selected text.
        3.   To test the GetDiscountsForCategory stored procedure: select the text between
             the -- Test GetDiscountsForCategory comment and the following comment.
        4.   On the toolbar, click the Execute button.
        5.   Verify the query runs with no errors.


        Task 3: Create and test the GetDiscountsForCategoryAndDate stored
        procedure
        1.   Select the text between the --Create GetDiscountsForCategoryAndDate
             comment and the following comment.
        2.   On the toolbar, click the Execute button to execute the selected text
        3.   To test the GetDiscountsForCategoryAndDate stored procedure: select the text
             between the -- Test GetDiscountsForCategoryAndDate comment and the
             following comment.
        4.   On the toolbar, click the Execute button.
        5.   Verify the query runs with no errors.
        6.   Select the text between the comment -- Test
             GetDiscountsForCategoryAndDate with both parameters and the following
             comment.
        7.   On the toolbar, click the Execute button.
        8.   Verify the query runs with no errors.
Lab: Implementing Stored Procedures   L7-49




                                                                                                      MCT USE ONLY. STUDENT USE PROHIBITED
Task 4: Create and test the AddDiscount stored procedure
1.     Select the text between the – Create AddDiscount comment and the following
       comment.
2.     On the toolbar, click the Execute button to execute the selected text.
3.     To test the AddDiscount stored procedure: select the text between the -- Test
       AddDiscount comment and the following comment.
4.     On the toolbar, click the Execute button.
5.     Verify the query runs with no errors.
6.     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.
7.     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.


Exercise 2: Working with Execution Plans
Task 1: View the text-based execution plan
1.     In the Query window, select the code between the comment –Test the text-
       based execution plan and the following comment.
2.     On the toolbar, click Execute.
3.     Observe in the results pane both the query and the text based execution plan
       are displayed instead of query results.
4.     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.     In the Query window, select the code between the comment –Test the
       graphical execution plan and the following comment.
2.     Right-click the selection and then click Include Actual Execution Plan.
3.     On the toolbar, click Execute.
L7-50   Module 7: Implementing Stored Procedures




                                                                                                    MCT USE ONLY. STUDENT USE PROHIBITED
        4.     In the Results pane, observe that query results are returned. Observe the
               Execution Plan tab above the returned results.
        5.     Click the Execution Plan tab.
        6.     Observe that the execution plan shows that 0% of the execution’s 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.     In the Query window select the code between the comment --Tune the
               database. Create an index on Name and the following comment.
        2.     On the toolbar, click Execute.


        Task 4: View the revised execution plan
        1.     In the Query window select the code below the comment –Retest the
               graphical execution plan.
        2.     In the toolbar, click Execute.
        3.     In the Results pane observe that query results are returned. Observe the
               Execution Plan tab above the returned results.
        4.     Click the Execution Plan tab.
        5.     Observe that the execution plan shows that 0% of the execution’s 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.
        6.     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.
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 User-
defined function
1.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on as Administrator with the password of Pa$$w0rd.
3.   From the Start Menu, right-click Computer, and then click Explore.
4.   In Windows Explorer, browse to E:MOD08LabfilesStarter.
5.   Double-click createnewuser.vbs. Click OK.
6.   Open Command Prompt. Browse to E:MOD08LabfilesStarter.
7.   Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER.
8.   Log off Administrator and then log on as Student with the password of
     Pa$$w0rd.
9.   From the Start Menu, right-click Computer, and then click Explore.
10. In Windows Explorer, browse to E:MOD08LabfilesStarter.
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.   Select the CREATE FUNCTION statement. On the toolbar, click Execute.
3.   In the Results pane, review the query results, verifying that the statement
     executed successfully.
4.   Locate the Test Sales.GetDiscountsForDate comment, select the Transact-
     SQL statement shown below in the following Transact-SQL example:

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


5.   On the toolbar, click Execute. In the query results, verify that some rows are
     displayed.
6.   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.     On the toolbar, click Execute.
3.     In the Results pane, review the query results. Verify that the statement
       executed successfully.
4.     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.     On the toolbar, click Execute. In the query results, view the number of rows
       returned by each query.
6.     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.   In Solution Explorer, double-click the ExecutionContext.sql query file.
        2.   If the Connect to Sever box appears, connect to server NY-SQL-01 using
             Windows Authentication.
        3.   Select the USE AdventureWorks2008 statement. On the toolbar, click
             Execute.
        4.   Locate the Create Sales.GetCurrencyRate comment, and then create the user-
             defined 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.   Select the CREATE FUNCTION statement. On the toolbar, click Execute.
        6.   In the Results pane, review the query results. Verify that the statement
             executed successfully.
        7.   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-01Adam" 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.     In Solution Explorer, double-click the TrustRelationship.sql query file.
2.     If the Connect to Sever box appears, connect to server NY-SQL-01 using
       Windows Authentication.
3.     Select the USE AdventureWorksDW2008 statement. Click Execute.
4.     Locate the Create the user for the NY-SQL-01Adam login comment, and
       then create a user called Adam in the AdventureWorksDW2008 database for
       the NY-SQL-01Adam 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-01Adam]
       GO


5.     Select the IF and CREATE statements. On the toolbar, click Execute.
6.     Verify that the statements executed successfully.
7.     Locate the Grant AUTHENTICATE permission on the database comment.
8.     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 Transact-
            SQL 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 User-
defined Function
1.   In Solution Explorer, double-click the ExecutionContext.sql query file.
2.   Select the USE AdventureWorks2008 statement. On the toolbar, click
     Execute.
3.   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.     Select the CREATE FUNCTION statement. On the toolbar, click Execute.
        5.     Verify that the statement executed successfully.
        6.     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.     Select the SELECT statement. On the toolbar, click Execute.
        8.     Review the query results and verify that the statement executed successfully.
        9.     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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Administrator using the password of Pa$$w0rd.
3.   Click Start, point to All Programs, point to Microsoft® SQL Server® 2008,
     and then click SQL Server Management Studio™.
4.   In the Connect to Server dialog box, specify the values in the following table,
     and then click Connect.

     Property                                Value
      Server type                            Database Engine

      Server name                            NY-SQL-01

      Authentication                         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.     On the File menu, point to Open, and then click Project/Solution.
        2.     In the Open Project dialog box, browse to the E:MOD09LabfilesStarter
               folder click the AWorks_CLR.ssmssln file, and then click Open.
        3.     If Solution Explorer is not visible, on the View menu, click Solution Explorer.
        4.     In Solution Explorer, expand the Queries node, and then double-click the
               Initialize.sql query file.
        5.     On the toolbar, click Execute, and then confirm that no errors occur.
        6.     In Solution Explorer, double-click the ImportAssembly.sql query file.
        7.     Below the Enable CLR integration comment, add the following code:

               sp_configure 'clr enabled', 1
               GO
               RECONFIGURE
               GO


        8.     On the toolbar, click Execute, and then verify that the statements executed
               successfully.
        9.     Below the Create assembly comment, add the following code:

               USE AdventureWorks2008
               CREATE ASSEMBLY AWorksUtilities
               FROM
                 'E:MOD09LabfilesStarterAWorksUtilities.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.   In Solution Explorer, double-click the SaveXML.sql query file.
2.   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.   Below the Create managed stored procedure comment, select the code, and
     then on the toolbar, click Execute.
4.   Verify that the statements executed successfully.
5.   Below the Test managed stored procedure comment, select the DECLARE,
     SET, and EXEC statements, and then on the toolbar, click Execute.
6.   Confirm that an error message is displayed. The assembly does not have the
     required permissions to write to the file system.
7.   Below the Change security permissions to allow file access comment, add
     the following code:

     ALTER ASSEMBLY AWorksUtilities
     WITH PERMISSION_SET = EXTERNAL_ACCESS
     GO


8.   Select the ALTER ASSEMBLY statement, and then on the toolbar, click
     Execute.
9.   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:MOD09LabfilesStarter
            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.   In Solution Explorer, double-click the GetLongDate.sql query file.
2.   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.   Below the Create managed user-defined function comment, select the code,
     and then on the toolbar, click Execute.
4.   Verify that the statements executed successfully.
5.   Below the Test managed user-defined function comment, select the SELECT
     statement, and then on the toolbar, click Execute.
6.   Verify that a list of orders is displayed that includes the day of the week in the
     OrderDate column.
7.   Confirm that the records are displayed with a long OrderDate value.
8.   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.   In Solution Explorer, double-click the EmailChange.sql query file.
        2.   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.   Below the Create trigger comment, select the code, and then on the toolbar,
             click Execute.
        4.   Verify that the statements executed successfully.
        5.   Below the Test trigger comment, select the first UPDATE statement, and then
             on the toolbar, click Execute.
        6.   Confirm that a message is displayed, noting the new e-mail address in the
             Messages pane.
        7.   Below the Test trigger comment, select the second UPDATE statement, and
             then on the toolbar, click Execute.
        8.   Confirm that there is no message because the statement did not update the e-
             mail 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.
        9.   On the File menu, click Save EmailChange.sql.
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.   In Solution Explorer, double-click the Concatenate.sql query file.
2.   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.   Below the Create aggregate function comment, select the code, and then on
     the toolbar, click Execute.
4.   Verify that the statements executed successfully.
5.   Below the Test aggregate function comment, select the SELECT statement,
     and then on the toolbar, click Execute.
6.   Confirm that orders are displayed as a concatenated string for each account in
     the Messages pane.
7.   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.     In Solution Explorer, double-click the IPAddress.sql query file.
        2.     Below the Create managed user-defined type comment, add the following
               code:

               USE AdventureWorks2008
               GO
               CREATE TYPE IPAddress
               EXTERNAL NAME AWorksUtilities.IPAddress
               GO


        3.     Below the Create managed user-defined type comment, select the code, and
               then on the toolbar, click Execute.
        4.     Verify that the statements executed successfully.
        5.     Below the Test managed user-defined type comment, select the statements,
               and then on the toolbar, click Execute.
        6.     Confirm that three result sets are displayed that show the IPAddress value in
               various forms.
        7.     On the File menu, click Save IPAddress.sql.
        8.     Close the SQL Server Management Studio solution.
        9.     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.   In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Student using the password Pa$$w0rd.


Task 2: Create and commit a transaction
1.   Click Start, point to All Programs, point to Microsoft SQL Server 2008, and
     then click SQL Server Management Studio.
2.   In the Connect to Server dialog box, specify the values in the following table,
     and then click Connect:

     Property                                Value

      Server type                            Database Engine

      Server name                            NY-SQL-01

      Authentication                         Windows Authentication

3.   On the File menu, point to Open, and then click File.
4.   In the Open File dialog box, browse to the E:Mod10LabfilesStarter 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                               Value

                Server name                            NY-SQL-01

                Authentication                         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.
         8.   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


         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.     On the File menu, point to Open, and then click File.
2.     In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder,
       click Tran2.sql, and then click Open.
3.     In the Connect to Database Engine dialog box, specify the values in the
       following table, and then click Connect:

        Property                                 Value

        Server name                               NY-SQL-01

        Authentication                            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.
5.     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


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.
7.     On the File menu, click Save Tran2.sql.
8.     Close SQL Server Management Studio.


     Results: After this exercise, you should have committed and rolled back transactions.
L10-72   Module 10: Managing Transactions and Locks




                                                                                                MCT USE ONLY. STUDENT USE PROHIBITED
         Exercise 2: Managing Locks
         Task 1: View locking information
         1.   Click Start, point to All Programs, point to Microsoft SQL Server 2008, and
              then click SQL Server Management Studio.
         2.   In the Connect to Server dialog box, specify the values in the following table,
              and then click Connect:

               Property                               Value

                Server type                             Database Engine

                Server name                             NY-SQL-01

                Authentication                          Windows Authentication

         3.   In SQL Server Management Studio, in the console tree, right-click NY-SQL-01,
              and then click Activity Monitor.
         4.   Review the information that is displayed in Processes, ResourceWaits, and
              Data File I/O, and Recent Expensive Queries.
         5.   On the File menu, point to New, and then click Query with Current
              Connection.
         6.   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.   Click Execute to execute the statement.
         8.   Review the information that shows the current lock in the master database.
         9.   On the File menu, point to Open, and then click File.
         10. In the Open File dialog box, browse to the E:Mod10LabfilesStarter 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                               Value

     Server name                           NY-SQL-01

     Authentication                        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-SQL-
    01, 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.   Click Start, point to All Programs, point to Microsoft SQL Server 2008, and
              then click SQL Server Management Studio.
         2.   In the Connect to Server dialog box, specify the values in the following table,
              and then click Connect:

               Property                               Value

                Server type                           Database Engine

                Server name                           NY-SQL-01

                Authentication                        Windows Authentication

         3.   On the File menu, point to Open, and then click File.
         4.   In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder,
              click Lock1.sql, and then click Open.
         5.   In the Connect to Database Engine dialog box, specify the values in the
              following table, and then click Connect:

               Property                               Value

                Server name                           NY-SQL-01

                Authentication                        Windows Authentication

         6.   Review the contents of the file, and then execute the query.
         7.   On the File menu, point to Open, and then click File.
         8.   In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder,
              click Lock2.sql, and then click Open.
         9.   In the Connect to Database Engine dialog box, specify the values in the
              following table, and then click Connect:

               Property                               Value
                Server name                           NY-SQL-01

                Authentication                        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:Mod10LabfilesStarter 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                                 Value

     Server name                               NY-SQL-01

     Authentication                            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.     Click Execute to execute the query and wait five seconds. Notice that the
                query no longer waits indefinitely for the lock to be granted.
         3.     Close SQL Server Management Studio without saving the changes to the files.
         4.     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.   In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch.
2.   Log on to NY-SQL-01 as Student using the password Pa$$w0rd.
3.   Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL
     Server Management Studio.
4.   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.
5.   Maximize the Microsoft SQL Server Management Studio window.


Task 2: Create the AW_ServiceBroker SQL Server Scripts project
1.   On the File menu, point to New, and then click Project.
2.   In the New Project dialog box, in the Name field, type AW_ServiceBroker.
3.   In the Location field, type E:MOD11LabfilesStarter.
4.   Clear Create directory for solution and then click OK.


Task 3: Configure the AdventureWorks database for Service Broker
1.   On the Project menu, click New Query to add a new query file to the project.
2.   If the Connect to Database Engine dialog box appears, click Connect.
3.   If Solution Explorer is not visible, on the View menu, click Solution Explorer.
4.   In Solution Explorer, in the Queries folder, right-click SQLQuery1.sql, click
     Rename, type PrepareDatabase.sql, and then press ENTER.
5.   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.    On the toolbar, click Execute to execute the query.
         8.    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 e-
mail solution
1.   On the Project menu, click New Query.
2.   In Solution Explorer, right-click SQLQuery1.sql, click Rename, type
     CreateServiceBrokerObjects.sql, and then press ENTER.
3.   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.     On the toolbar, click Execute to execute the query.
         5.     On the File menu, click Save All.
         6.     If Object Explorer is not visible, on the View menu, click Object Explorer.
         7.     In Object Explorer, expand Databases, expand AdventureWorks2008, and
                then expand Service Broker.
         8.     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.
         9.     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.


         Exercise 2: Implementing the Initiating Service
         Task 1: Add the CreateEmailNewCustomerSP.sql query file to the
         AW_ServiceBroker project
         1.     On the Project menu, click Add Existing Item.
         2.     In the Add Existing Item – AW_ServiceBroker dialog box, browse to the
                E:MOD11LabfilesStarter 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.
2.     On the toolbar, click Execute to execute the query.
3.     On the File menu, click Save All.
4.     In Object Explorer, under AdventureWorks2008, expand Programmability,
       and then expand Stored Procedures.
5.     Verify that the CustomerSvc.uspEmailNewCustomer stored procedure is
       listed.
6.     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.


Exercise 3: Implementing the Target Service
Task 1: Add the CreateSendEmailSP.sql query file to the
AW_ServiceBroker project
1.     On the Project menu, click Add Existing Item.
2.     In the Add Existing Item – AW_ServiceBroker dialog box, browse to the
       E:MOD11LabfilesStarter 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.
         2.    On the toolbar, click Execute to execute the query.
         3.    On the File menu, click Save All.
         4.    In Object Explorer, right-click Stored Procedures, and then click Refresh.
         5.    Verify that the EMailSvc.uspSendCustomerEmail stored procedure is listed.


         Task 3: Configure the target service for automatic activation
         1.    On the Project menu, click New Query.
         2.    In Solution Explorer, right-click SQLQuery1.sql, click Rename, type
               AlterServiceBrokerQueue.sql, and then press ENTER.
         3.    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.    On the toolbar, click Execute to execute the query.
         5.    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.     On the Project menu, click Add Existing Item.
2.     In the Add Existing Item – AW_ServiceBroker dialog box, browse to the
       E:MOD11LabfilesStarter folder, click the TestEmailService.sql query file,
       and then click Add.
3.     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.
4.     On the toolbar, click Execute to execute the query.
5.     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).
6.     On the File menu, click Save All.
7.     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.
MCT USE ONLY. STUDENT USE PROHIBITED

6232 a implementing a microsoft sql server 2008 database

  • 1.
    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.
  • 2.
    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
  • 3.
    MICROSOFT LICENSE TERMS OFFICIALMICROSOFT 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. b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions location, an IT Academy location, or such other entity as Microsoft may designate from time to time. c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and 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. d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning Center during an Authorized Training Session, each of which provides training on a particular Microsoft technology subject matter. 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. g. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that may be included with the Licensed Content. h. “Student(s)” means a student duly enrolled for an Authorized Training Session at your location.
  • 4.
    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. j. “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. k. “Trainer Content” means the materials accompanying these license terms that are for use by 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. l. “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”. m. “Virtual Machine” means a virtualized computing experience, created and accessed using 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”. n. “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these license terms. 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.
  • 5.
    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. B. Portable Device. You may install another copy on a portable device solely for your own personal training Use and for preparation of an Authorized Training Session. 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. b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to 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. 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. ii. Survival. Your duty to protect confidential information survives this agreement. 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
  • 6.
    protective order orotherwise protect the information. Confidential information does not include information that • 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. d. 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”). e. 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. f. 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. 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:
  • 7.
    You may onlyuse the Virtual Machines and Virtual Hard Disks if you comply with the terms and conditions of this agreement and the following security requirements: o You may not install Virtual Machines and Virtual Hard Disks on portable Devices or Devices that are accessible to other networks. o 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. o 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. o You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or downloaded from Devices on which you installed them. o You will strictly comply with all Microsoft instructions relating to installation, use, activation and deactivation, and security of Virtual Machines and Virtual Hard Disks. o You may not modify the Virtual Machines and Virtual Hard Disks or any contents thereof. o You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks. 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.
  • 8.
    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 Material’s original copyright notice, or a copyright notice to Microsoft’s 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 else’s 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 Microsoft’s 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;
  • 9.
    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. 9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed Content marked as “NFR” or “Not for Resale.” 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. 11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you 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. 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.
  • 10.
    16. LIMITATION ONAND 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 Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français. EXONÉRATION 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 péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier 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, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues. LIMITATION DES DOMMAGES-INTÉRÊTS 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 prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices. 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 réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur. Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard. EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.
  • 11.
    Implementing a MicrosoftSQL 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 20- year 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.
  • 12.
    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.
  • 13.
    Implementing a MicrosoftSQL Server 2008 Database xiii Contents Module 1: Creating Databases and Database Files Lesson 1: Creating Databases 1-3 Lesson 2: Creating Filegroups 1-11 Lesson 3: Creating Schemas 1-15 Lesson 4: Creating Database Snapshots 1-19 Lab: Creating Databases and Database Files 1-25 Module 2: Creating Data Types and Tables Lesson 1: Creating Data Types 2-3 Lesson 2: Creating Tables 2-8 Lesson 3: Creating Partitioned Tables 2-17 Lab: Creating Data Types and Tables 2-23 Module 3: Creating and Tuning Indexes Lesson 1: Planning Indexes 3-3 Lesson 2: Creating Indexes 3-8 Lesson 3: Optimizing Indexes 3-21 Lab: Creating and Optimizing Indexes 3-29 Module 4: Implementing Data Integrity by Using Constraints and Triggers Lesson 1: Data Integrity Overview 4-3 Lesson 2: Implementing Constraints 4-7 Lesson 3: Implementing Triggers 4-14 Lab: Implementing Data Integrity by Using Constraints and Triggers 4-27
  • 14.
    xiv Implementing a Microsoft SQL Server 2008 Database Module 5: Using XML Lesson 1: Using the XML Data Type 5-3 Lesson 2: Retrieving XML by Using FOR XML 5-12 Lesson 3: Shredding XML by Using OPENXML 5-21 Lab 5A: Using XML 5-27 Lesson 4: Introducing XQuery 5-37 Lesson 5: Creating XML Indexes 5-43 Lesson 6: Implementing XML Schemas 5-48 Lab 5B: Using XML 5-54 Module 6: Implementing Views Lesson 1: Introduction to Views 6-3 Lesson 2: Creating and Managing Views 6-9 Lesson 3: Optimizing Performance by Using Views 6-19 Lab: Implementing Views 6-24 Module 7: Implementing Stored Procedures Lesson 1: Using Stored Procedures 7-3 Lesson 2: Creating Parameterized Stored Procedures 7-12 Lesson 3: Working with Execution Plans 7-17 Lesson 4: Handling Exceptions 7-24 Lab: Implementing Stored Procedures 7-28 Module 8: Implementing Functions Lesson 1: Introducing Functions 8-3 Lesson 2: Working with Functions 8-9 Lesson 3: Controlling Execution Context 8-13 Lab: Implementing Functions 8-17
  • 15.
    Implementing a MicrosoftSQL Server 2008 Database xv Module 9: Implementing Managed Code in a Database Lesson 1: Introduction to the SQL Server® Common Language Runtime 9-4 Lesson 2: Importing and Configuring Assemblies 9-10 Lesson 3: Creating Managed Database Objects 9-15 Lab: Implementing Managed Code in a Database 9-20 Module 10: Managing Transactions and Locks Lesson 1: Overview of Transactions and Locks 10-3 Lesson 2: Managing Transactions 10-11 Lesson 3: Understanding SQL Server Locking Architecture 10-25 Lesson 4: Managing Locks 10-34 Lab: Managing Transactions and Locks 10-49 Module 11: Using Service Broker Lesson 1: Service Broker Overview 11-3 Lesson 2: Creating Service Broker Objects 11-14 Lesson 3: Sending and Receiving Messages 11-22 Lab: Using Service Broker 11-27 Lab Answer Keys
  • 17.
    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.
  • 18.
    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.
  • 19.
    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.
  • 20.
    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.
  • 21.
    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 it’s 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 CD- ROM 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.
  • 22.
    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 Role 6232A-NY-SQL-01 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.
  • 23.
    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.4–gigahertz (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.
  • 24.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 25.
    Implementing a MicrosoftSQL Server 2008 Database 1-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 1 Creating Databases and Database Files Contents: Lesson 1: Creating Databases 1-3 Lesson 2: Creating Filegroups 1-11 Lesson 3: Creating Schemas 1-15 Lesson 4: Creating Database Snapshots 1-19 Lab: Creating Databases and Database Files 1-25
  • 26.
    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.
  • 27.
    Implementing a MicrosoftSQL 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.
  • 28.
    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.
  • 29.
    Implementing a MicrosoftSQL Server 2008 Database 1-5 MCT USE ONLY. STUDENT USE PROHIBITED • Collation settings, which include character set, sort order, and other locale- specific 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?
  • 30.
    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.
  • 31.
    Implementing a MicrosoftSQL 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?
  • 32.
    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?
  • 33.
    Implementing a MicrosoftSQL 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.
  • 34.
    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?
  • 35.
    Implementing a MicrosoftSQL 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.
  • 36.
    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.
  • 37.
    Implementing a MicrosoftSQL 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.
  • 38.
    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?
  • 39.
    Implementing a MicrosoftSQL 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.
  • 40.
    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?
  • 41.
    Implementing a MicrosoftSQL 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.
  • 42.
    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?
  • 43.
    Implementing a MicrosoftSQL 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.
  • 44.
    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.
  • 45.
    Implementing a MicrosoftSQL 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?
  • 46.
    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.
  • 47.
    Implementing a MicrosoftSQL 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.
  • 48.
    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?
  • 49.
    Implementing a MicrosoftSQL 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:MOD01Labfiles 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.
  • 50.
    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:MOD01LabfilesScripts folder. The main tasks for this exercise are as follows: 1. Create a SQL Server Management Studio Scripts project. 2. Create a new database by executing a SQL Server Management Studio Scripts project. Task 1: Create a SQL Server Management Studio Scripts project 1. Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. 2. 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:MOD01LabfilesScripts 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.
  • 51.
    Implementing a MicrosoftSQL 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 Create a new database user. 2. Create a schema and assign ownership to a user. 3. 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-01Katie should use the TechSupport schema as her default schema. Task 3: Display ownership of a schema 1. Create a T-SQL statement that displays ownership of the TechSupport schema. 2. Comment the T-SQL statement to explain what it will do on execution. 3. 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.
  • 52.
    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. Create a database snapshot. 2. Alter the database. 3. 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:MOD01LabfilesSnapshots 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.
  • 53.
    Implementing a MicrosoftSQL 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.
  • 54.
    1-30 Creating Databases and Database Files MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. When are objects assigned to the default filegroup? 2. What is a database schema and how can schemas be used? 3. 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.
  • 55.
    Implementing a MicrosoftSQL 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.
  • 56.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 57.
    Implementing a MicrosoftSQL Server 2008 Database 2-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 2 Creating Data Types and Tables Contents: Lesson 1: Creating Data Types 2-3 Lesson 2: Creating Tables 2-8 Lesson 3: Creating Partitioned Tables 2-17 Lab: Creating Data Types and Tables 2-23
  • 58.
    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.
  • 59.
    Implementing a MicrosoftSQL 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.
  • 60.
    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, T- SQL 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.
  • 61.
    Implementing a MicrosoftSQL 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.
  • 62.
    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 user- defined databases. However, if the data type is created in a user-defined database, the data type exists only in that user-defined database.
  • 63.
    Implementing a MicrosoftSQL 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?
  • 64.
    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.
  • 65.
    Implementing a MicrosoftSQL 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.
  • 66.
    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.
  • 67.
    Implementing a MicrosoftSQL 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.
  • 68.
    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?
  • 69.
    Implementing a MicrosoftSQL 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.
  • 70.
    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.
  • 71.
    Implementing a MicrosoftSQL 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 Transact- SQL 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.
  • 72.
    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?
  • 73.
    Implementing a MicrosoftSQL 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.
  • 74.
    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.
  • 75.
    Implementing a MicrosoftSQL 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.
  • 76.
    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?
  • 77.
    Implementing a MicrosoftSQL 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.
  • 78.
    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?
  • 79.
    Implementing a MicrosoftSQL 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 company’s 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. Create a data type based on the nvarchar system-supplied data type. 2. Create a data type based on the decimal system-supplied data type.
  • 80.
    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.
  • 81.
    Implementing a MicrosoftSQL 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. Obtain date and time formatting using T-SQL. 2. 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 2007- 05-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.
  • 82.
    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. Create a table named ReturnedGoods. 2. 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.
  • 83.
    Implementing a MicrosoftSQL 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. Prepare the database for partitioning. 2. Create a partitioned table named ReturnsArchive. 3. Review the partitioning implementation. Task 1: Prepare the database for partitioning • Open the query located at E:MOD02LabfilesScriptspartition_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.
  • 84.
    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.
  • 85.
    Implementing a MicrosoftSQL Server 2008 Database 2-29 MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. What are the two types of temporary tables and how do they differ from each other? 2. How can you decide whether to implement partitioning? 3. 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.
  • 86.
    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.
  • 87.
    Implementing a MicrosoftSQL Server 2008 Database 3-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 3 Creating and Tuning Indexes Contents: Lesson 1: Planning Indexes 3-3 Lesson 2: Creating Indexes 3-8 Lesson 3: Optimizing Indexes 3-21 Lab: Creating and Optimizing Indexes 3-29
  • 88.
    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.
  • 89.
    Implementing a MicrosoftSQL 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.
  • 90.
    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 optimizer—the 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?
  • 91.
    Implementing a MicrosoftSQL 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?
  • 92.
    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 index—the table’s rows cannot be stored in more than one order.
  • 93.
    Implementing a MicrosoftSQL 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 non- clustered indexes?
  • 94.
    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.
  • 95.
    Implementing a MicrosoftSQL 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.
  • 96.
    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?
  • 97.
    Implementing a MicrosoftSQL 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.
  • 98.
    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.
  • 99.
    Implementing a MicrosoftSQL 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 created—and all connections attempting INSERT, UPDATE, or DELETE statements that will change values in the index—have 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
  • 100.
    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?
  • 101.
    Implementing a MicrosoftSQL 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 tables—to improve performance and to make large indexes more manageable—by 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?
  • 102.
    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.
  • 103.
    Implementing a MicrosoftSQL 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?
  • 104.
    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).
  • 105.
    Implementing a MicrosoftSQL 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.
  • 106.
    3-20 Creating and Tuning Indexes MCT USE ONLY. STUDENT USE PROHIBITED Demonstration: Creating Indexes Question: What permissions are required to create an index?
  • 107.
    Implementing a MicrosoftSQL 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.
  • 108.
    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 Transact- SQL and save it for later review and application, or you can choose to implement the recommended changes immediately.
  • 109.
    Implementing a MicrosoftSQL 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?
  • 110.
    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?
  • 111.
    Implementing a MicrosoftSQL 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?
  • 112.
    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 non- clustered 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.
  • 113.
    Implementing a MicrosoftSQL 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?
  • 114.
    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?
  • 115.
    Implementing a MicrosoftSQL 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:MOD03LabfilesStarter 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.
  • 116.
    3-30 Creating and Tuning Indexes MCT USE ONLY. STUDENT USE PROHIBITED This exercise’s main tasks are: 1. Start the 6432A-NY-SQL-01 virtual machine and log on as Student. 2. Create a SQL Server Scripts project. 3. 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. Open SQL Server Management Studio, and connect to the server you want to manage (NY-SQL-01). 2. On the File menu, click New, and then click Project. 3. 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. 2. 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.
  • 117.
    Implementing a MicrosoftSQL 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 exercise’s main tasks are: 1. Add the sample products to the database. 2. Reorganize AK_Product_ProductNumber. 3. Rebuild AK_Product_Name. Task 1: Add the sample products to the database • In SQL Server Management Studio, open aw2008sampleproductadd.sql from the E:Mod03LabfilesStarter 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.
  • 118.
    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.
  • 119.
    Implementing a MicrosoftSQL Server 2008 Database 3-33 MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. What is the difference between a clustered index and a non-clustered index? 2. Why does fragmentation occur in an index? 3. 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.
  • 120.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 121.
    Implementing a MicrosoftSQL 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 4-3 Lesson 2: Implementing Constraints 4-7 Lesson 3: Implementing Triggers 4-14 Lab: Implementing Data Integrity by Using Constraints and Triggers 4-27
  • 122.
    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.
  • 123.
    Implementing a MicrosoftSQL 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.
  • 124.
    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.
  • 125.
    Implementing a MicrosoftSQL 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?
  • 126.
    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?
  • 127.
    Implementing a MicrosoftSQL 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.
  • 128.
    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 integrity–domain, entity, and referential–is 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?
  • 129.
    Implementing a MicrosoftSQL 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?
  • 130.
    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.
  • 131.
    Implementing a MicrosoftSQL 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 employee’s 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?
  • 132.
    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?
  • 133.
    Implementing a MicrosoftSQL 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 re- create a table. • You must build error-checking logic into your applications and transactions to test whether a constraint has been violated. • You must specify 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,
  • 134.
    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?
  • 135.
    Implementing a MicrosoftSQL 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.
  • 136.
    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.
  • 137.
    Implementing a MicrosoftSQL 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?
  • 138.
    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?
  • 139.
    Implementing a MicrosoftSQL 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?
  • 140.
    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. The DELETE step that captures the before image of the data. 2. The INSERT step that captures the after image of the data. Question: When would you use an update trigger?
  • 141.
    Implementing a MicrosoftSQL 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?
  • 142.
    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 trigger’s 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.
  • 143.
    Implementing a MicrosoftSQL 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?
  • 144.
    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.
  • 145.
    Implementing a MicrosoftSQL 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)?
  • 146.
    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?
  • 147.
    Implementing a MicrosoftSQL 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.
  • 148.
    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:MOD04LabfilesStarter folder. This exercise’s main tasks are: 1. Start the 6232A-NY-SQL-01 virtual machine and log on as Student. 2. Create a SQL Server Scripts project. 3. Create the JobCandidateHistory table and constraints. 4. 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. Open SQL Server Management Studio, and connect to the server you want to manage (NY-SQL-01). 2. On the File menu, click New, and then click Project. 3. 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. 2 Execute the query, and then save the query file. 3. Use Object Explorer to verify that the table and constraints have been created.
  • 149.
    Implementing a MicrosoftSQL Server 2008 Database 4-29 MCT USE ONLY. STUDENT USE PROHIBITED Task 4: Test the JobCandidateHistory table and constraints 1. In SQL Server Management Studio, open the TestConstraints.sql script file in the E:MOD04LabfilesStarter folder. 2. Use the INSERT statement to test inserting invalid data. 3. 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.
  • 150.
    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 exercise’s main tasks are: 1. Insert multiple rows into the JobCandidateHistory table. 2. Disable constraints on the JobCandidateHistory table. 3. 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:Mod04LabfilesStarter folder, and then execute it with statistics enabled. Examine the performance statistics. Task 2: Disable constraints on the JobCandidateHistory table 1. Add a new query to the project. Change the query file name to Constraints.sql. 2. In the query window, type the appropriate Transact-SQL to disable the constraints on the HumanResources.JobCandidateHistory table. 3. Execute the query, and then save the query file. 4. 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.
  • 151.
    Implementing a MicrosoftSQL Server 2008 Database 4-31 MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Enable constraints on the JobCandidateHistory table 1. In the Constraints.sql query window, type the appropriate Transact-SQL to enable the constraints on the HumanResources.JobCandidateHistory table. 2. 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.
  • 152.
    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 candidate’s 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 exercise’s main tasks are: 1. Create the dJobCandidate trigger. 2. Test the dJobCandidate trigger. Task 1: Create the dJobCandidate trigger 1. Add a new query to the project. Change the query file name to Trigger.sql. 2. In the query window, type the appropriate Transact-SQL to create the dJobCandidate trigger on the HumanResources.JobCandidate table in the AdventureWorks database. 3. Execute the query, and then save the query file. 4. Use Object Explorer to verify that the trigger has been created.
  • 153.
    Implementing a MicrosoftSQL Server 2008 Database 4-33 MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Test the dJobCandidate trigger 1. In SQL Server Management Studio, open the TestTrigger.sql query file from the E:MOD04LabfilesStarter folder. 2. 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.
  • 154.
    4-34 Implementing Data Integrity by Using Constraints and Triggers MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. What is the difference between a constraint and a trigger? 2. Why implement check constraints if an application is already checking the input data? 3. 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.
  • 155.
    Implementing a MicrosoftSQL Server 2008 Database 5-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 5 Using XML Contents: Lesson 1: Using the XML Data Type 5-3 Lesson 2: Retrieving XML by Using FOR XML 5-12 Lesson 3: Shredding XML by Using OPENXML 5-21 Lab 5A: Using XML 5-27 Lesson 4: Introducing XQuery 5-37 Lesson 5: Creating XML Indexes 5-43 Lesson 6: Implementing XML Schemas 5-48 Lab 5B: Using XML 5-54
  • 156.
    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.
  • 157.
    Implementing a MicrosoftSQL 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.
  • 158.
    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.
  • 159.
    Implementing a MicrosoftSQL 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?
  • 160.
    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.
  • 161.
    Implementing a MicrosoftSQL 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?
  • 162.
    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.
  • 163.
    Implementing a MicrosoftSQL 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.
  • 164.
    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.
  • 165.
    Implementing a MicrosoftSQL 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?
  • 166.
    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.
  • 167.
    Implementing a MicrosoftSQL 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.
  • 168.
    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?
  • 169.
    Implementing a MicrosoftSQL 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.
  • 170.
    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.
  • 171.
    Implementing a MicrosoftSQL 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.
  • 172.
    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.
  • 173.
    Implementing a MicrosoftSQL 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.
  • 174.
    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?
  • 175.
    Implementing a MicrosoftSQL 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.
  • 176.
    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.
  • 177.
    Implementing a MicrosoftSQL 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
  • 178.
    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.
  • 179.
    Implementing a MicrosoftSQL 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.
  • 180.
    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?
  • 181.
    Implementing a MicrosoftSQL 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.
  • 182.
    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.
  • 183.
    Implementing a MicrosoftSQL 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 Data type CustomerID int OrderDate datetime DueDate datetime AccountNumber nvarchar(15) ContactID int BillToAddressID int ShipToAddressID int ShipMethodID int SubTotal money TaxAmt money The second OPENXML query will insert data into the Sales.SalesOrderDetail table and should use the following schema declaration: Column name Data type OrderQty Int ProductID Int UnitPrice 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.
  • 184.
    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.
  • 185.
    Implementing a MicrosoftSQL 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)
  • 186.
    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.
  • 187.
    Implementing a MicrosoftSQL 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:Mod05LabfilesStarter folder. • A file named HistoricResumeSchema.xml containing the schema for the HistoricResumeSchemaCollection XML schema collection is provided in the E:Mod05LabfilesStarter folder. Task 1: Create a SQL Server Scripts project in SQL Server Management Studio • Create a new project. • Name: Job Candidate History • Location: E:Mod05LabfilesSolution
  • 188.
    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:Mod05LabfilesStarter • File name: HistoricResumeSchema.xml • Examine this file.
  • 189.
    Implementing a MicrosoftSQL 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:Mod05LabfilesStarter • 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.
  • 190.
    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.
  • 191.
    Implementing a MicrosoftSQL 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 Schema- based 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.
  • 192.
    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.
  • 193.
    Implementing a MicrosoftSQL 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?
  • 194.
    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).
  • 195.
    Implementing a MicrosoftSQL 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.
  • 196.
    5-42 Using XML MCT USE ONLY. STUDENT USE PROHIBITED Demonstration: Using XQuery Expressions Question: What does the XMLNAMESPACES function do?
  • 197.
    Implementing a MicrosoftSQL 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.
  • 198.
    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.
  • 199.
    Implementing a MicrosoftSQL 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.
  • 200.
    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.
  • 201.
    Implementing a MicrosoftSQL 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?
  • 202.
    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.
  • 203.
    Implementing a MicrosoftSQL 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.
  • 204.
    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?
  • 205.
    Implementing a MicrosoftSQL 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.
  • 206.
    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.
  • 207.
    Implementing a MicrosoftSQL 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?
  • 208.
    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.
  • 209.
    Implementing a MicrosoftSQL 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/adventure- works/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/adventure- works/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.
  • 210.
    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/adventure- works/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.
  • 211.
    Implementing a MicrosoftSQL 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
  • 212.
    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.
  • 213.
    Implementing a MicrosoftSQL Server 2008 Database 5-59 MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. What is XML? 2. What does the nodes() method do? 3. What are RAW Mode Queries? 4. What are AUTO Mode Queries? 5. What are EXPLICIT Mode Queries? 6. What are PATH Mode Queries? 7. What is the purpose of an XML schema? 8. When would you use untyped XML? 9. When would you use typed XML?
  • 214.
    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.
  • 215.
    Implementing a MicrosoftSQL Server 2008 Database 5-61 MCT USE ONLY. STUDENT USE PROHIBITED Tools Tool Use for Where to find it SQL Server • Integrated management Start | All Programs | Management Studio and development console Microsoft SQL Server 2008 Microsoft Visual • Comprehensive Start | All Programs | Studio® 2008 development platform Microsoft Visual Studio 2008 SQL Server • SQL Server, Services, and Start | All Programs | Configuration Manager networking protocols Microsoft SQL Server 2008
  • 216.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 217.
    Implementing a MicrosoftSQL Server 2008 Database 6-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 6 Implementing Views Contents: Lesson 1: Introduction to Views 6-3 Lesson 2: Creating and Managing Views 6-9 Lesson 3: Optimizing Performance by Using Views 6-19 Lab: Implementing Views 6-24
  • 218.
    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 (T- SQL) 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.
  • 219.
    Implementing a MicrosoftSQL 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 schema—it 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 views—the different types of views, and how to use them.
  • 220.
    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.
  • 221.
    Implementing a MicrosoftSQL 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.
  • 222.
    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?
  • 223.
    Implementing a MicrosoftSQL 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.
  • 224.
    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?
  • 225.
    Implementing a MicrosoftSQL 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.
  • 226.
    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.
  • 227.
    Implementing a MicrosoftSQL 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.
  • 228.
    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?
  • 229.
    Implementing a MicrosoftSQL 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.
  • 230.
    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.
  • 231.
    Implementing a MicrosoftSQL 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?
  • 232.
    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.
  • 233.
    Implementing a MicrosoftSQL 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.
  • 234.
    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.
  • 235.
    Implementing a MicrosoftSQL 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.
  • 236.
    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
  • 237.
    Implementing a MicrosoftSQL Server 2008 Database 6-21 MCT USE ONLY. STUDENT USE PROHIBITED • Data warehouses • Online analytical processing (OLAP) stores and sources • Data mining workloads
  • 238.
    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?
  • 239.
    Implementing a MicrosoftSQL 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.
  • 240.
    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 aren’t 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.
  • 241.
    Implementing a MicrosoftSQL 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. Create a SQL Server Scripts project. 2. Create the HumanResources.vEmployeeDetails view. 3. Test the HumanResources.vEmployeeDetails view. Task 1: Create a SQL Server Scripts project 1. Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd. 2. Start the Server Management Studio and connect to the server. 3. Create a new project. • Name: AW_Views • Location: E:Mod06LabfilesStarter 4. Create a new query file. • File name: CreateEmployeeView.sql
  • 242.
    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. Examine this code. 3. Execute the code. Examine the Messages box and verify that the script completed without any errors. 4. Verify that the HumanResources.vEmployeeDetails view is listed in the Object Explorer. 5. Verify that the correct columns are listed in the view.
  • 243.
    Implementing a MicrosoftSQL Server 2008 Database 6-27 MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Test the HumanResources.vEmployeeDetails view 1. Create a new query file. • File name: TestEmployeeView.sql 2. In the blank query window, type the following code: Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails 3. Examine this code. 4. Execute the code. Examine the Messages box and verify that the script completed without any errors. 5. 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.
  • 244.
    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. Create a new query file. 2. 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. Examine this code. 3. Execute the code. Examine the Messages box and verify that the script completed without any errors. 4. Verify that the the IX_vEmployeeDetails index is listed in Object Explorer. Results: After this exercise, you should have created a new view index.
  • 245.
    Implementing a MicrosoftSQL 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. Prepare the SQL Server instances. 2. Create a new query file. 3. Create the Person.vContact distributed partitioned view. Task 1: Prepare the SQL Server instances • Execute the following code: • E:Mod06LabfilesStarter LabSetup.cmd Task 2: Create a new query file • Create a new query file. • File name: CreatePartitionedView.sql
  • 246.
    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-01SQLINSTANCE2].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01SQLINSTANCE3].AW_Contacts.Person.Contact 2. Examine this code. 3. Execute the code. Examine the Messages box and verify that the script completed without any errors. 4. Verify that the Person.vContact view is listed in the Object Explorer. 5. Verify that the correct columns are listed in the view. 6. 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. Examine this code. 9. 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.
  • 247.
    Implementing a MicrosoftSQL 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.
  • 248.
    6-32 Implementing Views MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. How does SQL Server store the view in the database? 2. What is a Standard non-indexed view? 3. What is an unbroken ownership chain? 4. 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.
  • 249.
    Implementing a MicrosoftSQL 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 Use for Where to find it SQL Server • Integrated management and Microsoft SQL Server Management Studio development console 2008 Microsoft Visual • Comprehensive development Microsoft Visual Studio Studio® 2008 platform 2008 SQL Server • SQL Server, Services, and Microsoft SQL Server Configuration Manager networking protocols 2008
  • 250.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 251.
    Implementing a MicrosoftSQL Server 2008 Database 7-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 7 Implementing Stored Procedures Contents: Lesson 1: Using Stored Procedures 7-3 Lesson 2: Creating Parameterized Stored Procedures 7-12 Lesson 3: Working with Execution Plans 7-17 Lesson 4: Handling Exceptions 7-24 Lab: Implementing Stored Procedures 7-28
  • 252.
    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.
  • 253.
    Implementing a MicrosoftSQL 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.
  • 254.
    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.
  • 255.
    Implementing a MicrosoftSQL 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 database—except 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.
  • 256.
    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.
  • 257.
    Implementing a MicrosoftSQL 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?
  • 258.
    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.
  • 259.
    Implementing a MicrosoftSQL 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.
  • 260.
    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?
  • 261.
    Implementing a MicrosoftSQL 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?
  • 262.
    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.
  • 263.
    Implementing a MicrosoftSQL 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.
  • 264.
    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?
  • 265.
    Implementing a MicrosoftSQL 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.
  • 266.
    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?
  • 267.
    Implementing a MicrosoftSQL 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.
  • 268.
    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.
  • 269.
    Implementing a MicrosoftSQL 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.
  • 270.
    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.
  • 271.
    Implementing a MicrosoftSQL 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.
  • 272.
    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?
  • 273.
    Implementing a MicrosoftSQL 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?
  • 274.
    7-24 Implementing Stored Procedures MCT USE ONLY. STUDENT USE PROHIBITED Lesson 4 Handling Exceptions This lesson introduces the Microsoft SQL Server 2008 structured exception- handling 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.
  • 275.
    Implementing a MicrosoftSQL 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 TRY…CATCH 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.
  • 276.
    7-26 Implementing Stored Procedures MCT USE ONLY. STUDENT USE PROHIBITED Guidelines for Handling Exceptions Key Points When you use the TRY…CATCH 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 TRY…CATCH construct. This includes an attention sent by the Microsoft Distributed Transaction Coordinator (MS DTC) when a distributed transaction fails. MS DTC manages distributed transactions.
  • 277.
    Implementing a MicrosoftSQL 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?
  • 278.
    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:MOD07LabfilesStarter 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.
  • 279.
    Implementing a MicrosoftSQL 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. Create and test the GetDiscounts stored procedure. 2. Create and test the GetDiscountsForCategory stored procedure. 3. Create and test the GetDiscountsForCategoryAndDate stored procedure. 4. Create and test the AddDiscount stored procedure. Task 1: Create and test the GetDiscounts stored procedure 1. Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. 2. Open the AWProgrammability.ssmssln solution in the E:MOD07LabfilesStarter folder. 3. 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.
  • 280.
    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. 2. Test the Sales.GetDiscountsForCategory stored procedure using 'Reseller' for the @Category value, and then review the results. 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. 2. Test the Sales.GetDiscountsForCategoryAndDate stored procedure using 'Reseller' for the @Category value and the default value for the @DateToCheck parameter. Review the results. 3. 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. 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. 2. Test the Sales.AddDiscount stored procedure by using the following parameter values: Parameter Value @Description 'Half price of everything' @DiscountPct .5 @Type 'Seasonal Discount' @Category 'Customer' @StartDate Local variable with current date from GETDATE function @EndDate Local variable with date one month from current date @MinQty 0 @MaxQty 20
  • 281.
    Implementing a MicrosoftSQL Server 2008 Database 7-31 MCT USE ONLY. STUDENT USE PROHIBITED 3. Confirm that a new special offer was create by displaying the @NewProductID OUTPUT parameter value. 4. 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.
  • 282.
    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. View text-based execution plans. 2. View graphical execution plans. 3. Tune the database to improve performance. 4. 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 Transact- SQL below the comment --Tune the database. Create an index on name.
  • 283.
    Implementing a MicrosoftSQL 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.
  • 284.
    7-34 Implementing Stored Procedures MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. If a nonqualified user-defined stored procedure is specified, in which order does the Database Engine searches for the procedure? 2. 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.
  • 285.
    Implementing a MicrosoftSQL Server 2008 Database 8-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 8 Implementing Functions Contents: Lesson 1: Introducing Functions 8-3 Lesson 2: Working with Functions 8-9 Lesson 3: Controlling Execution Context 8-13 Lab: Implementing Functions 8-17
  • 286.
    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.
  • 287.
    Implementing a MicrosoftSQL 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.
  • 288.
    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.
  • 289.
    Implementing a MicrosoftSQL 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 BEGIN…END block, contains the series of Transact-SQL statements that return the value.
  • 290.
    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 user- provided parameter within the view when you create it. • You can achieve the functionality of a parameterized view by using an inline table-valued function.
  • 291.
    Implementing a MicrosoftSQL 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?
  • 292.
    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?
  • 293.
    Implementing a MicrosoftSQL 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.
  • 294.
    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.
  • 295.
    Implementing a MicrosoftSQL 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 user- defined 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.
  • 296.
    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.
  • 297.
    Implementing a MicrosoftSQL 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.
  • 298.
    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.
  • 299.
    Implementing a MicrosoftSQL 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.
  • 300.
    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.
  • 301.
    Implementing a MicrosoftSQL 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:MOD08LabfilesStarter 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.
  • 302.
    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-01Adam 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. Create and test the GetMaximumDiscountsForCategory user-defined function. 2. Create and test the GetDiscountsForDate user-defined function. 3. Create and test the GetDiscountedProducts user-defined function.
  • 303.
    Implementing a MicrosoftSQL Server 2008 Database 8-19 MCT USE ONLY. STUDENT USE PROHIBITED Task 1: Create and test the GetMaximumDiscountForCategory user- defined function 1. Start the NY-SQL-01 virtual machine. 2. Logon as Administrator with the password: Pa$$w0rd. 3. Run the createnewuser.vbs script located at E:MOD8LabfilesStarter. 4. Open Command Prompt. Browse to E:MOD08LabfilesStarter. 5. Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER. 6. Log off Administrator and then logon as Student with the password: Pa$$w0rd. 7. Open the SQL Server Management Studio scripts project located at E:MOD8LabfilesStarterAWProgrammability.ssmssln. 8. In Solution Explorer open the query file InitilizeData.sql and execute its complete contents, ensure that it executes successfully. 9. 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
  • 304.
    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. In the UserDefinedFunctions.sql query locate the Create Sales.GetDiscountsForDate comment. 2. 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. Locate the Test Sales.GetDiscountsForDate comment. 4. 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.
  • 305.
    Implementing a MicrosoftSQL Server 2008 Database 8-21 MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Create and test the GetDiscountedProducts user-defined function 1. In the UserDefinedFunctions.sql query locate the Create Sales.GetDiscountedProducts comment. 2. 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
  • 306.
    8-22 Implementing Functions MCT USE ONLY. STUDENT USE PROHIBITED (continued) 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 3. Locate the Test Sales.GetDiscountedProducts comment. 4. 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.
  • 307.
    Implementing a MicrosoftSQL 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-SQL- 01Adam 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. Create the GetCurrencyRate user-defined function. 2. Establish a database trust relationship between the AdventureWorks2008 database and the AdventureWorksDW2008 database. 3. Create and test the GetCurrencyDiscountedProducts user-defined function. Task 1: Create the GetCurrencyRate user-defined function 1. In Solution Explorer open the query file ExecutionContext.sql. 2. Connect to server NY-SQL-01 using Windows Authentication. 3. Select and Execute the USE AdventureWorks2008 statement. 4. Locate the Create Sales.GetCurrencyRate comment.
  • 308.
    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. Locate the Test Sales.GetCurrencyRate comment. 7. 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-01Adam" 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. In Solution Explorer open the TrustRelationship.sql query file. 2. Execute the USE AdventureWorksDW2008 statement. 3. Locate the Create the user for the NY-SQL-01Adam login comment.
  • 309.
    Implementing a MicrosoftSQL 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-01Adam] GO 5. Locate the Grant Authenticate permission on the database comment. 6. 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. Locate the Grant SELECT permission to Adam comment. 8. 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 user- defined function 1. In Solution Explorer open the ExecutionContext.sql query file. 2. Select and execute the USE AdventureWorks2008 statement. 3. Locate the Test Sales.GetCurrencyDiscountedProducts comment.
  • 310.
    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. Verify that the statement executes successfully. 6. Locate the Test Sales.GetCurrencydiscountedProducts comment.
  • 311.
    Implementing a MicrosoftSQL 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. Review the query results and verify that the statement executes successfully. 9. 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.
  • 312.
    8-28 Implementing Functions MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. When using the EXECUTE AS clause, what privileges should the login or user have? 2. 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.
  • 313.
    Implementing a MicrosoftSQL 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 9-4 Lesson 2: Importing and Configuring Assemblies 9-10 Lesson 3: Creating Managed Database Objects 9-15 Lab: Implementing Managed Code in a Database 9-20
  • 314.
    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 Transact- SQL. 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.
  • 315.
    Implementing a MicrosoftSQL Server 2008 Database 9-3 MCT USE ONLY. STUDENT USE PROHIBITED In this module, you will learn about using CLR integrated code to create user- defined 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.
  • 316.
    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.
  • 317.
    Implementing a MicrosoftSQL 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.
  • 318.
    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.
  • 319.
    Implementing a MicrosoftSQL 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?
  • 320.
    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.
  • 321.
    Implementing a MicrosoftSQL 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?
  • 322.
    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.
  • 323.
    Implementing a MicrosoftSQL 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.
  • 324.
    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.
  • 325.
    Implementing a MicrosoftSQL 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.
  • 326.
    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?
  • 327.
    Implementing a MicrosoftSQL 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.
  • 328.
    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.
  • 329.
    Implementing a MicrosoftSQL 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.
  • 330.
    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.
  • 331.
    Implementing a MicrosoftSQL Server 2008 Database 9-19 MCT USE ONLY. STUDENT USE PROHIBITED Demonstration: Creating Managed Database Objects
  • 332.
    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:MOD09LabfilesStarter 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
  • 333.
    Implementing a MicrosoftSQL 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. Start the NY-SQL-01 virtual machine and log on as Administrator. 2. 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. Open the AWorks_CLR.ssmssln solution. 2. Execute the Initialize.sql query file. 3. Open the ImportAssembly.sql query file and add and run the code to enable CLR Integration. 4. Add and run the code to create the AWorksUtilities assembly. 5. 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.
  • 334.
    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:MOD09LabfilesStarter 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. Create the SaveXML managed stored procedure referencing the external assembly. 2. Create the GetLongDate managed user-defined function referencing the external assembly. 3. Create the EmailChange managed trigger on the Person.EmailAddress table referencing the external assembly.
  • 335.
    Implementing a MicrosoftSQL Server 2008 Database 9-23 MCT USE ONLY. STUDENT USE PROHIBITED 4. Create the Concatenate managed aggregate function referencing the external assembly. 5. Create the IPAddress managed user-defined type referencing the external assembly. Task 1: Create the SaveXML managed stored procedure referencing the external assembly 1. Open the SaveXML.sql query file and add the code to create the SaveXML stored procedure. 2. Highlight and run the new code. 3. Highlight and run the DECLARE, SET, and EXEC statements. 4. Add code to change the security permissions. 5. Highlight and run the ALTER ASSEMBLY statement. 6. Highlight and run the DECLARE, SET, and EXEC statements. 7. Save the SaveXML.sql file. 8. Using Windows Explorer check for the existence of the Output.xml file in the E:MOD09LabfilesStarter folder. 9. 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. Open the GetLongDate.sql query file. 2. Add the code to create the GetLongDate function then highlight and run the code. 3. Select and run the SELECT statement and execute it. 4. Confirm that the records returned display with a long OrderDate value. 5. Save the GetLongDate.sql file.
  • 336.
    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. Open the EmailChange.sql query file. 2. Add and execute the code to create the EmailChange trigger. 3. Highlight and execute the first UPDATE statement 4. Highlight and execute the second UPDATE statement. 5. Save the EmailChange.sql file. Task 4: Create the Concatenate managed aggregate function referencing the external assembly 1. Open the Concatenate.sql query file. 2. Add and execute the code to create the Concatenate aggregate. 3. Highlight and execute the SELECT statement. 4. Confirm that orders are displayed as a concatenated string. 5. Save the Concatenate.sql file. Task 5: Create the IPAddress managed user-defined type referencing the external assembly 1. Open the IPAddress.sql query file. 2. Add and execute the code to create the new IPAddress type 3. Highlight and execute the SELECT statements. 4. Confirm that three result sets are displayed that show the IPAddress value in various forms. 5. Save the IPAddress.sql file. Results: After this exercise, you should have successfully imported assembly code and created managed database objects.
  • 337.
    Implementing a MicrosoftSQL 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.
  • 338.
    9-26 Implementing Managed Code in a Database MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. When is CLR integration of managed code the best option for creating database objects? 2. When is Transact-SQL the best choice? 3. Given what you know of CLR Integration, are there some previous projects in your organization that could have benefited by using managed code?
  • 339.
    Implementing a MicrosoftSQL 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 Troubleshooting tip When using a managed database object you get an error indicating that the execution of user code in the .NET framework is disabled. 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.
  • 340.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 341.
    Implementing a MicrosoftSQL 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 10-3 Lesson 2: Managing Transactions 10-11 Lesson 3: Understanding SQL Server Locking Architecture 10-25 Lesson 4: Managing Locks 10-34 Lab: Managing Transactions and Locks 10-49
  • 342.
    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.
  • 343.
    Implementing a MicrosoftSQL 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.
  • 344.
    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.
  • 345.
    Implementing a MicrosoftSQL 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?
  • 346.
    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.
  • 347.
    Implementing a MicrosoftSQL 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 administrator’s perspective, the primary concerns are the number of users, the number of transactions, and the throughput. From the user’s 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?
  • 348.
    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.
  • 349.
    Implementing a MicrosoftSQL 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?
  • 350.
    10-10 Managing Transactions and Locks MCT USE ONLY. STUDENT USE PROHIBITED Demonstration: Introducing Transactions Question: What happens when a transaction is rolled back?
  • 351.
    Implementing a MicrosoftSQL 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.
  • 352.
    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.
  • 353.
    Implementing a MicrosoftSQL 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?
  • 354.
    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.
  • 355.
    Implementing a MicrosoftSQL 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.
  • 356.
    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?
  • 357.
    Implementing a MicrosoftSQL 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.
  • 358.
    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?
  • 359.
    Implementing a MicrosoftSQL 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.
  • 360.
    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?
  • 361.
    Implementing a MicrosoftSQL 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.
  • 362.
    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?
  • 363.
    Implementing a MicrosoftSQL 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
  • 364.
    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.
  • 365.
    Implementing a MicrosoftSQL 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.
  • 366.
    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.
  • 367.
    Implementing a MicrosoftSQL 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?
  • 368.
    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?
  • 369.
    Implementing a MicrosoftSQL 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.
  • 370.
    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 table- level. 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.
  • 371.
    Implementing a MicrosoftSQL 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?
  • 372.
    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).
  • 373.
    Implementing a MicrosoftSQL Server 2008 Database 10-33 MCT USE ONLY. STUDENT USE PROHIBITED Existing granted lock Requested Lock IS S U IX SIX X Intent shared (IS) Yes Yes Yes Yes Yes No Shared (S) Yes Yes Yes No No No Update (U) Yes Yes No No No No Intent exclusive (IX) Yes No No Yes No No Shared with intent Yes No No No No No exclusive (SIX) Exclusive (X) 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?
  • 374.
    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.
  • 375.
    Implementing a MicrosoftSQL 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.
  • 376.
    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 Description READ COMMITTED with Directs SQL Server to use shared locks READ_COMMITTED_SNAPSHOT OFF while reading. At this level, you cannot experience dirty reads. READ COMMITTED with Directs SQL Server to use row READ_COMMITTED_SNAPSHOT ON versioning instead of locking. The data is not protected from updates made by other transactions. READ UNCOMMITTED Directs SQL Server not to issue shared locks and does not honor exclusive locks. You can experience dirty reads. REPEATABLE READ Indicates that dirty reads and nonrepeatable reads cannot occur. Shared locks are held until the end of the transaction. SERIALIZABLE Prevents other users from updating or inserting new rows that match the criteria in the WHERE clause of the transaction. Phantoms cannot occur. 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
  • 377.
    Implementing a MicrosoftSQL Server 2008 Database 10-37 MCT USE ONLY. STUDENT USE PROHIBITED The following results show the output of these statements. Set option Value textsize 2147483627 language us_english dateformat mdy datefirst 7 ... isolation level read uncommitted (13 row(s) affected) 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
  • 378.
    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?
  • 379.
    Implementing a MicrosoftSQL 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
  • 380.
    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.
  • 381.
    Implementing a MicrosoftSQL 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 cost- effective 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.
  • 382.
    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.
  • 383.
    Implementing a MicrosoftSQL 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 transaction’s 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.
  • 384.
    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. Notifies the deadlock victim’s application (with message number 1205). 3. Cancels the deadlock victim’s current request. 4. 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.
  • 385.
    Implementing a MicrosoftSQL 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?
  • 386.
    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.
  • 387.
    Implementing a MicrosoftSQL 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?
  • 388.
    10-48 Managing Transactions and Locks MCT USE ONLY. STUDENT USE PROHIBITED Demonstration: Viewing Locking Information Question: What locking information does Activity Monitor provide?
  • 389.
    Implementing a MicrosoftSQL 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. In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd.
  • 390.
    10-50 Managing Transactions and Locks MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Create and commit a transaction 1. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. 2. Open the script E:Mod10LabfilesStarterTran1.sql and connect to the NY-SQL-01 instance by using Windows authentication. 3. Review the script. 4. Add a statement to begin a transaction in the appropriate place. 5. Execute the script. Notice that the transaction has not ended. 6. Add a statement to commit the transaction in the appropriate place. 7. Execute the statement that you have just added to end the transaction. 8. Execute the last two statements of the script to verify that the changes have been committed to the database. 9. Close the file. Task 3: Create and rollback a transaction 1. Open the script E:Mod10LabfilesStarterTran2.sql and connect to the NY-SQL-01 instance by using Windows authentication. 2. Review the script. 3. Add a statement to roll back the transaction in the appropriate place. 4. Execute the script and verify that the changes are not made and the transaction is complete. 5. Close SQL Server Management Studio. Results: After this exercise, you should have committed and rolled back transactions.
  • 391.
    Implementing a MicrosoftSQL 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. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. 2. Use the Activity Monitor window to review the current lock information. 3. Create a new query to select the following columns from the sys.dm_tran_locks dynamic management view. • resource_type • request_mode • request_type • request_status • request_session_id 4. Execute the query and review the results that show the lock on the master database. 5. Open the script E:Mod10LabfilesStarterLock1.sql and connect to the NY-SQL-01 instance by using Windows authentication. 6. Review and execute the script, noting the SPID of your connection. 7. Execute the query against the sys.dm_tran_locks dynamic management view and note the new locks listed. 8. Use the Activity Monitor window to review the additional locks held. 9. 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.
  • 392.
    10-52 Managing Transactions and Locks MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Set locking options 1. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. 2. Open E:Mod10LabfilesStarterLock1.sql and connect to the NY-SQL-01 instance by using Windows authentication. 3. Review the contents of the file and execute the script. 4. Open E:Mod10LabfilesStarterLock2.sql and connect to the NY-SQL-01 instance by using Windows authentication. 5. Review the contents of the file and execute the script. 6. Open E:Mod10LabfilesStarterLockList.sql and connect to the NY-SQL- 01 instance by using Windows authentication. 7. Execute the script and notice the WAIT entry in the request_status column. 8. Cancel the Lock2.sql script and verify that the waiting transaction has been cancelled. Task 3: Set the lock timeout 1. Add a SET statement to the start of the Lock2.sql script to change the lock timeout to five seconds. 2. Execute the query and note that the query now times out. 3. 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.
  • 393.
    Implementing a MicrosoftSQL Server 2008 Database 10-53 MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. What is the default Transaction Isolation Level in SQL Server? 2. How long is a lock held in a read operation when using the READ COMMITTED isolation level? 3. What happens when an Update (U) lock needs to modify data.
  • 394.
    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 Troubleshooting tip 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. 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-out- transaction errors and handle them accordingly. • Monitor the locking information for your applications.
  • 395.
    Implement a MicrosoftSQL Server 2008 Database 11-1 MCT USE ONLY. STUDENT USE PROHIBITED Module 11 Using Service Broker Contents: Lesson 1: Service Broker Overview 11-3 Lesson 2: Creating Service Broker Objects 11-14 Lesson 3: Sending and Receiving Messages 11-22 Lab: Using Service Broker 11-27
  • 396.
    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.
  • 397.
    Implement a MicrosoftSQL 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.
  • 398.
    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.
  • 399.
    Implement a MicrosoftSQL 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.
  • 400.
    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.
  • 401.
    Implement a MicrosoftSQL 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.
  • 402.
    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.
  • 403.
    Implement a MicrosoftSQL 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.
  • 404.
    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.
  • 405.
    Implement a MicrosoftSQL 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.
  • 406.
    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.
  • 407.
    Implement a MicrosoftSQL 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.
  • 408.
    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.
  • 409.
    Implement a MicrosoftSQL 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.
  • 410.
    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.
  • 411.
    Implement a MicrosoftSQL 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.
  • 412.
    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.
  • 413.
    Implement a MicrosoftSQL 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.
  • 414.
    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.
  • 415.
    Implement a MicrosoftSQL Server 2008 Database 11-21 MCT USE ONLY. STUDENT USE PROHIBITED Demonstration: Creating Service Broker Objects Question: What must a contract contain and why?
  • 416.
    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.
  • 417.
    Implement a MicrosoftSQL 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?
  • 418.
    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.
  • 419.
    Implement a MicrosoftSQL 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?
  • 420.
    11-26 Using Service Broker MCT USE ONLY. STUDENT USE PROHIBITED Diagnostic Tools for SendingReceiving 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.
  • 421.
    Implement a MicrosoftSQL 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 company’s Web site. To minimize the impact to the site’s 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.
  • 422.
    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 Value Name //AW/EMail/CustomerDetails Validation WELL_FORMED_XML • Use the following details to create a contract that will be supported by the EmailService service. Property Value Name //AW/EMail/SendCustomerDetails Message type //AW/EMail/CustomerDetails Message Direction SENT BY INITIATOR
  • 423.
    Implement a MicrosoftSQL 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 Value Name CustomerSvc.NewCustomerQueue Queue status 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 Value Name EMailSvc.NewCustomerEmailQueue Queue status OFF • Use the following details to create the CustomerService service. Property Value Name //AW/Sales/CustomerService Queue CustomerSvc.NewCustomerQueue • Use the following details to create the EmailService service. Property Value Name //AW/EMail/EmailService Queue EMailSvc.NewCustomerEmailQueue Contract //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. Launch SQL Server Management Studio. 2. Create the AW_ServiceBroker SQL Server Scripts project.
  • 424.
    11-30 Using Service Broker MCT USE ONLY. STUDENT USE PROHIBITED 3. Configure the AdventureWorks database for Service Broker. 4. 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. Open SQL Server Management Studio and connect to the default database engine. 2. Create a new project named AW_ServiceBroker in the E:MOD11LabfilesStarter folder. Task 3: Configure the AdventureWorks database for Service Broker 1. Create a new query named PrepareDatabase.sql in the AdventureWorks2008 database. 2. 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 e- mail solution 1. Create a new query named CreateServiceBrokerObjects.sql in the AdventureWorks2008 database. 2. 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.
  • 425.
    Implement a MicrosoftSQL 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.
  • 426.
    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 Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project. 2. Implement the CustomerService service. Task 1: Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project 1. Use the Add Existing Item option to add an item to the project. 2. Add the CreateEmailNewCustomerSP.sql query file in the E:MOD11LabfilesStarter folder to the project. Task 2: Implement the CustomerService service 1. Execute the CreateEmailNewCustomerSP.sql query. 2. 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.
  • 427.
    Implement a MicrosoftSQL 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 Transact- SQL 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 Value Name EMailSvc.NewCustomerEmailQueue Queue status ON Activation status ON Procedure name AdventureWorks.EMailSvc.uspSendCustomerEmail Maximum readers 5 Execute as 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. Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project. 2. Implement the EmailService service. 3. Configure the target service for automatic activation. 4. Test the EmailService service.
  • 428.
    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. Use the Add Existing Item option to add an item to the project. 2. Add the CreateSendEmailSP.sql query file in the E:MOD11LabfilesStarter folder to the project. Task 2: Implement the EmailService service 1. Execute the CreateSendEmailSP.sql query. 2. 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. Create a new query named AlterServiceBrokerQueue.sql. 2. 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. 3. Execute the query. Task 4: Test the EmailService service 1. Use the Add Existing Item option to add an item to the project. 2. Add the TestEmailService.sql query file in the E:MOD11LabfilesStarter folder to the project. 3. 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.
  • 429.
    Implement a MicrosoftSQL Server 2008 Database 11-35 MCT USE ONLY. STUDENT USE PROHIBITED Module Review and Takeaways Review Questions 1. What does Service Broker security rely on and why? 2. How can you ensure that message delivery is correctly supported? 3. How can you access SQL Trace to monitor Service Broker events?
  • 430.
    MCT USE ONLY.STUDENT USE PROHIBITED
  • 431.
    Lab: Creating Databasesand 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. 3. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. 4. 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. 5. Maximize Microsoft SQL Server Management Studio. 6. In Object Explorer expand NY-SQL-01, right-click Databases, and then click New Database. 7. The New Database window appears. Maximize the window. 8. On the General page, in the Database name field, enter AW_IT_Assets. 9. 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.
  • 432.
    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:MOD01Labfiles, enter AW_IT_Assets_DBScript in the File name field, and then click Save. 34. Close the New Database window.
  • 433.
    Lab: Creating Databasesand 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. In Microsoft SQL Server Management Studio, click File, point to Open, and then click File. The Open File dialog box appears. 2. Browse to E:MOD01Labfiles, select AW_IT_Assets_DBScript, and then click Open. 3. 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. Right-click NY-SQL-01 | Databases in Object Explorer and then click Refresh. 5. Expand NY-SQL-01 | Databases. The AW_IT_Assets database has been added to the Databases folder. 6. Close the query editor without saving the query. 7. 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. In SQL Server Management Studio expand NY-SQL-01 | Databases | AW_IT_Assets | Security, right-click Users, and then click New User. 2. In the Database User window, enter Katie in the User name field and NY- SQL-01Katie in the Login name field, and then click OK.
  • 434.
    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. Click New Query on the Standard toolbar. 2. 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. On the toolbar, click Execute. 4. Close the query editor without saving the query. Task 3: Create a schema and assign ownership to a user 1. In SQL Server Management Studio, on the toolbar, click New Query. 2. In the new, blank query window, type the following T-SQL statement: SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'TechSupport'; GO 3. On the toolbar, click Execute. 4. Close the query editor without saving the query. 5. 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.
  • 435.
    Lab: Creating Databasesand Database Files L1-5 MCT USE ONLY. STUDENT USE PROHIBITED Exercise 3: Creating a Database Snapshot Task 1: Create a database snapshot 1. In SQL Server Management Studio, on the toolbar, click New Query. 2. 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:MOD01LabfilesSnapshotsAW_IT_Assets_Data1.ss' ), ( NAME = AW_IT_Assets_Data2, FILENAME = ‘E:MOD01LabfilesSnapshotsAW_IT_Assets_Data2.ss’ ) AS SNAPSHOT OF AW_IT_Assets; GO 3. On the toolbar, click Execute. 4. Close the query editor without saving the query. 5. In Object Explorer, right-click NY-SQL-01 | Databases, and then click Refresh. 6. Expand NY-SQL-01 | Databases | Database Snapshots and review the new database snapshot named AW_IT_Assets_Snapshot1. Task 2: Alter the database 1. Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables, right-click the TechSupport.Hardware table, and then click Delete. 2. The Delete Object window appears. Click OK. 3. Expand NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas, right-click the TechSupport schema, and then click Delete. 4. The Delete Object window appears. Click OK.
  • 436.
    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. In Object Explorer, expand NY-SQL-01 | Databases, right-click the AW_IT_Assets database, and then click New Query. 2. 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. On the toolbar, click Execute. 4. Right-click NY-SQL-01 | Databases, and then click Refresh. 5. 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. 6. 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.
  • 437.
    Lab: Creating DataTypes 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. 3. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. 4. 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. 5. Maximize Microsoft SQL Server Management Studio. 6. Expand NY-SQL-01 | Databases, right-click the AdventureWorksDW2008 database, and then click New Query. 7. In the new, blank query window, type the following T-SQL statement: CREATE TYPE ShortDescription FROM nvarchar(10) NOT NULL; 8. On the toolbar, click Execute. 9. 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.
  • 438.
    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. Right-click the AdventureWorksDW2008 database, and then click New Query. 2. In the new, blank query window, type the following T-SQL statement: CREATE TYPE CashValue FROM decimal(8,2) NOT NULL; 3. On the toolbar, click Execute. 4. 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. 5. Close the query editor without saving the query. 6. 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.
  • 439.
    Lab: Creating DataTypes 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. Right-click the AdventureWorksDW2008 database, and then click New Query. 2. In the new, blank query window, type the following T-SQL statement: SELECT CAST('2007-05-08 12:35:29.1234567 +12:15' AS time(7)) AS 'time' ,CAST('2007-05-08 12:35:29.1234567 +12:15' AS date) AS 'date' ,CAST('2007-05-08 12:35:29.123' AS smalldatetime) AS 'smalldatetime' ,CAST('2007-05-08 12:35:29.123' AS datetime) AS 'datetime' ,CAST('2007-05-08 12:35:29.1234567 +12:15' AS datetime2(7)) AS 'datetime2' ,CAST('2007-05-08 12:35:29.1234567 +12:15' AS datetimeoffset(7)) AS 'datetimeoffset'; 3. On the toolbar, click Execute and then review the results. 4. Close the query editor without saving the query. Task 2: Convert sample data into new data type formats using T-SQL 1. Right-click the AdventureWorksDW2008 database, and then click New Query. 2. 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
  • 440.
    L2-10 Module 2: Creating Data Types and Tables MCT USE ONLY. STUDENT USE PROHIBITED 3. On the toolbar, click Execute and then review the results. 4. Close the query editor without saving the query. 5. 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. In SQL Server Management Studio, on the toolbar, click New Query. 2. 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. On the toolbar, click Execute. 4. 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. 5. Close the query editor without saving the query. Task 2: Create a table named Refunds 1. Right-click the AdventureWorksDW2008 database, and then click New Query. 2. 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.
  • 441.
    Lab: Creating DataTypes 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. 5. Close the query editor without saving the query. 6. 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. Exercise 4: Creating Partitioned Tables Task 1: Limit result sets by using the INTERSECT clause with the SELECT statement 1. On the SQL Server Management Studio toolbar, click File, point to Open, and then click File. 2. Browse to E:MOD02LabfilesScripts, select the file named partition_prep.sql, and then click Open. 3. On the toolbar, click Execute. 4. Close the query editor without saving the query.
  • 442.
    L2-12 Module 2: Creating Data Types and Tables MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Create a partitioned table named ReturnsArchive 1. In SQL Server Management Studio, on the toolbar, click New Query. 2. 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. On the toolbar, click Execute. 4. 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. 5. Close the query editor without saving the query. Task 3: Review the partitioning implementation 1. In Object Explorer, right-click the AdventureWorksDW2008 database, and then click Refresh. 2. Expand NY-SQL-01 | AdventureWorksDW2008 | Tables, right-click the dbo.ReturnsArchive table, and then click Properties. 3. In the Table Properties window, click Storage on the left. 4. Review the Compression, Filegroups, and Partitioning information in the right pane of the Table Properties window, and then click OK. 5. 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.
  • 443.
    Lab: Creating andOptimizing 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on as Student with the password of Pa$$w0rd. Task 2: Create a SQL Server Scripts project 1. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, click Connect. 3. On the File menu, click New, and then click Project. 4. In the New Project dialog box, in the Name field, type AW_Indexes. Change the Location field to E:MOD03LabfilesStarter. 5. Clear the Create directory for solution check box, and then click OK.
  • 444.
    L3-14 Module 3: Creating and Optimizing Indexes MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Create the Ix_Product_Supply_Chain index 1. On the Project menu, click New Query. 2. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type CreateIndex.sql, and then press ENTER. 3. 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. On the toolbar, click Execute. 5. On the File menu, click Save All. 6. If Object Explorer is not visible, on the View menu, click Object Explorer. 7. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Tables. 8. Expand Production.Product, expand Indexes, and then verify that the Ix_Product_Supply_Chain index is listed. 9. 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.
  • 445.
    Lab: Creating andOptimizing Indexes L3-15 MCT USE ONLY. STUDENT USE PROHIBITED Exercise 2: Optimizing Indexes Task 1: Add the sample products to the database 1. In Microsoft SQL Server Management Studio, on the File menu, click Open, and then click File. 2. In the Open File dialog box, browse to the E:MOD03LabfilesStarter folder, click the aw2008sampleproductadd.sql file, and then click Open. 3. In Microsoft SQL Server Management Studio, on the toolbar, click Execute. 4. 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. In Object Explorer, make sure that Databases | AdventureWorks2008 | Tables | Production.Product | Indexes is still expanded. 2. Right-click AK_Product_ProductNumber (Unique, Non-Clustered), and then click Properties. 3. In the Index Properties – AK_Product_ProductNumber dialog box, in the Select a page pane, click Fragmentation. 4. In the details pane, under Fragmentation, notice that Total Fragmentation is 66.67%. 5. Click Cancel. 6. In Object Explorer, right-click AK_Product_ProductNumber (Unique, Non- Clustered), and then click Reorganize. 7. In the Reorganize Indexes dialog box, click OK. 8. In Object Explorer, right-click AK_Product_ProductNumber (Unique, Non- Clustered), and then click Properties. 9. 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.
  • 446.
    L3-16 Module 3: Creating and Optimizing Indexes MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Rebuild AK_Product_Name 1. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Properties. 2. In the Index Properties – AK_Product_Name dialog box, in the Select a page pane, click Fragmentation. 3. In the details pane, notice that Total fragmentation is 80.00%. 4. Click Cancel. 5. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Rebuild. 6. In the Rebuild Indexes dialog box, click OK. 7. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Properties. 8. In the Index Properties – AK_Product_Name dialog box, in the Select a page pane, click Fragmentation. 9. 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.
  • 447.
    Lab: Implementing DataIntegrity 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on as Student with the password of Pa$$w0rd. Task 2: Create a SQL Server Scripts project 1. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, click Connect. 3. On the File menu, click New, and then click Project. 4. In the New Project dialog box, in the Name field, type AW_DataIntegrity. Change the Location field to E:MOD04LabfilesStarter. 5. Clear the Create directory for solution check box, and then click OK.
  • 448.
    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. On the Project menu, click New Query. 2. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type TableAndContraints.sql, and then press ENTER. 3. 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. On the toolbar, click Execute. 5. On the File menu, click Save All. 6. If Object Explorer is not visible, on the View menu, click Object Explorer. 7. In Object Explorer, expand Databases, expand AdventureWorks2008, expand Tables, and then verify that the HumanResources.JobCandidateHistory table is listed. You may need to right- click Tables, and then click Refresh to see the new table. 8. In Object Explorer, expand the HumanResources.JobCandidateHistory table. 9. In the HumanResources.JobCandidateHistory table, expand the Columns, Keys, Indexes, and Constraints folders, and then verify that the necessary constraints have been implemented.
  • 449.
    Lab: Implementing DataIntegrity by Using Constraints L4-19 MCT USE ONLY. STUDENT USE PROHIBITED Task 4: Test the JobCandidateHistory table and constraints 1. In SQL Server Management Studio, on the File menu, click Open, and then click File. 2. In the Open File dialog box, browse to E:MOD04LabfilesStarter, click TestConstraints.sql, and then click Open. 3. 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. 4. Below the comment This should succeed, select the code, and then on the toolbar, click Execute. The INSERT operation should succeed. 5. 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. Exercise 2: Disabling Constraints Task 1: Insert multiple rows into the JobCandidateHistory table 1. In Microsoft SQL Server Management Studio, on the File menu, click Open, and then click File. 2. In the Open File dialog box, browse to the E:MOD04LabfilesStarter folder, click the InsertTestData.sql file, and then click Open. 3. On the toolbar, click the Include Client Statistics button, and then click Execute. 4. Click the Client Statistics tab, and verify that the Time Statistics have been recorded. Task 2: Disable constraints on the JobCandidateHistory table 1. On the Project menu, click New Query. 2. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type Constraints.sql, and then press ENTER.
  • 450.
    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. On the toolbar, click Execute. 5. Verify that the commands completed successfully. 6. On the File menu, click Save All. 7. Switch to the InsertTestData.sql query window. 8. On the toolbar, click Execute. 9. 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. Switch to the Constraints.sql query window. 2. 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. Select the new statements, and then on the toolbar, click Execute. 4. Verify that the commands completed successfully. 5. On the File menu, click Save All. 6. 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.
  • 451.
    Lab: Implementing DataIntegrity by Using Constraints L4-21 MCT USE ONLY. STUDENT USE PROHIBITED Exercise 3: Creating Triggers Task 1: Create the dJobCandidate trigger 1. In SQL Server Management Studio, on the Project menu, click New Query. 2. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type Trigger.sql, and then press ENTER. 3. 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. On the toolbar, click Execute. 5. On the File menu, click Save All. 6. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Tables. Right-click Tables, and then click Refresh. 7. Expand the HumanResources.JobCandidate table, expand Triggers, and then verify that the dJobCandidate trigger is listed.
  • 452.
    L4-22 Module 4: Implementing Data Integrity by Using Constraints MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Test the dJobCandidate trigger 1. On the File menu, click Open, and then click File. 2. In the Open File dialog box, browse to the E:MOD04LabfilesStarter folder, click the TestTrigger.sql query file, and then click Open. 3. On the toolbar, click Execute to execute the query script. 4. 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. 5. 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. 6. 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.
  • 453.
    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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. 3. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. 4. If the Connect to Server dialog box appears, click Connect. 5. On the File menu, point to Open, and then click Project/Solution. 6. The Open Project dialog box appears. Browse to the E:Mod05LabfilesStarter folder, click the XML.ssmssln solution, and then click Open. a. If the Connect to Server dialog box appears, click Connect. b. If Solution Explorer is not visible, on the View menu, click Solution Explorer. c. If necessary, in the Solution Explorer pane, expand XML | Queries. 7. In the Solution Explorer, double-click the FORXML.sql query to open it. 8. Switch to the FORXML query. 9. 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.
  • 454.
    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.
  • 455.
    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.
  • 456.
    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. In the Solution Explorer pane, double-click the OPENXML.sql query to open it. 2. 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. 3. 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 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)
  • 457.
    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. On the toolbar, click Execute. 8. Examine the Results and Messages boxes and verify that the script completed without any errors. 9. 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. On the File menu, point to New, and then click Project. 2. The New Project dialog box appears. In the Templates box, makes sure SQL Server Scripts is highlighted. 3. In the Name field, type Job Candidate History. 4. In the Location field, type E:Mod05LabfilesStarter. 5. Click OK. 6. In the Solution Explorer, right-click Connections, and then click New Connection. 7. The Connect to Server dialog box appears. Click OK.
  • 458.
    L5-28 Module 5: Using XML MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Create the HumanResources.JobCandidateHistory table 1. In the Solution Explorer, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. 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. On the toolbar, click Execute. 5. If the Connect to Server dialog box appears, click Connect. 6. Examine Messages box and verify that the script completed without any errors. 7. On the File menu, click Save SQLQuery1.sql As. 8. The Save File As dialog box appears. In the File name field, type CreateJobCandidateHistoryTable.sql, and then click Save. 9. 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.
  • 459.
    Lab: Using XML L5-29 MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Create a new query file 1. In the Solution Explorer, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery2.sql As. 4. 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. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. 2. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click XML Files. 3. Navigate to the E:Mod05LabfilesStarter folder. 4. Click HistoricResumeSchema.xml, and then click Add. 5. In the details pane, examine the new schema definition. 6. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. 7. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. 8. Navigate to the E:Mod05LabfilesStarter folder. 9. Click CreateXMLSchema.sql, and then click Add. 10. If the Connect to Server dialog box appears, click Connect.
  • 460.
    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/adventure- works/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>
  • 461.
    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>
  • 462.
    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>
  • 463.
    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" />
  • 464.
    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. In the Solution Explorer, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery3.sql As. 4. The Save File As dialog box appears. In the File name field, type AlterCandiateTable.sql, and then click Save. 5. 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. On the toolbar, click Execute. 7. Examine Messages box and verify that the script completed without any errors. 8. In Object Explorer, right-click AdventureWorks2008, and then click Refresh. 9. In Object Explorer, expand Databases | AdventureWorks2008 | Tables | HumanResources.JobCandidateHistory | Columns. 10. Notice that the Resume column is now associated with the HumanResources.HistoricResumeSchemaCollection.
  • 465.
    Lab: Using XML L5-35 MCT USE ONLY. STUDENT USE PROHIBITED Task 6: Test the HistoricResumeSchema XML schema 1. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. 2. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. 3. Navigate to the E:Mod05LabfilesStarter folder. 4. Click TestXMLSchema.sql, and then click Add. 5. If the Connect to Server dialog box appears, click Connect. 6. In the details pane, below the comment This should fail, select the INSERT code. 7. On the toolbar, click Execute. 8. 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.
  • 466.
    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. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. 2. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. 3. Navigate to the E:Mod05LabfilesStarter folder. 4. Click AddCandidate.sql, and then click Add. 5. If the Connect to Server dialog box appears, click Connect. 6. On the toolbar, click Execute. 7. Examine the Message box and verify that the script completed without any errors. 8. In the Solution Explorer, double-click SelectCandidates.sql. 9. 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.
  • 467.
    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. In the Solution Explorer pane, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery5.sql As. 4. The Save File As dialog box appears. In the File name field, type xmlMethods.sql, and then click Save. 5. 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/adventure- works/Resume' AS "RES") SELECT NationalIDNumber, Resume.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources.JobCandidateHistory GO 6. On the toolbar, click Execute. 7. Examine the Results and Messages boxes and verify that the script completed without any errors. 8. Verify that the desired results are returned.
  • 468.
    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/adventure- works/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. Select the statements you just added, and then on the toolbar, click Execute. 3. 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/adventure- works/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.
  • 469.
    Lab: Using XML L5-39 MCT USE ONLY. STUDENT USE PROHIBITED 3. Select the statements you just added, and then on the toolbar, click the Execute button. 4. Examine the Messages box and verify that the script completed without any errors. Task 4: Verify the updated candidate's address 1. Select the statements from Task 2. 2. On the toolbar, click Execute. 3. Verify that the desired results are returned as 7194 Fourth St. Rockhampton. 4. On the File menu, click Save All. 5. 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. In the Solution Explorer pane, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery6.sql As. 4. The Save File As dialog box appears. In the File name field, type CreateXMLIndexes.sql, and then click Save.
  • 470.
    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. On the toolbar, click Execute to execute the query. 4. Examine the Messages box and verify that the script completed without any errors. 5. On the File menu, click Save All. 6. In the navigation pane, expand Databases | AdventureWorks2008 | Tables | Production.Illustration | Indexes. 7. Verify that the new XML indexes are listed and are correct. 8. Close SQL Server Management Studio. 9. Turn off 6232A-NY-SQL-01 and delete changes. Results: After this exercise, you have created XML indexes.
  • 471.
    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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Administrator using the password Pa$$w0rd. 3. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. 4. The Connect to Server dialog box appears. Click Connect. 5. On the File menu, point to New, and then click Project. 6. The New Project dialog box appears. In the Templates box, make sure SQL Server Scripts is highlighted. 7. In the Name field, type AW_Views. 8. In the Location field, type E:Mod06LabfilesStarter. 9. 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.
  • 472.
    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. On the toolbar, click Execute. 3. Examine Messages box and verify that the script completed without any errors. 4. On the File menu, click Save All. 5. In Object Explorer, expand Databases | AdventureWorks2008 | Views. 6. Verify that the HumanResources.vEmployeeDetails view is listed.
  • 473.
    Lab: Implementing Views L6-43 MCT USE ONLY. STUDENT USE PROHIBITED 7. In Object Explorer, expand Databases | AdventureWorks2008 | Views | HumanResources.vEmployeeDetails | Columns. 8. Verify that the correct columns are listed in the view. Task 3: Test the HumanResources.vEmployeeDetails view 1. In the Solution Explorer, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery2.sql As. 4. The Save File As dialog box appears. In the File name field, type TestEmployeeView.sql, and then click Save. 5. In the query window, type the following code: Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails 6. On the toolbar, click Execute. 7. Examine the Results and Messages boxes and verify that the script completed without any errors. 8. Verify that correct data is returned from the view. 9. 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.
  • 474.
    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. In the Solution Explorer pane, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery3.sql As. 4. 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. On the toolbar, click Execute. 3. Examine Messages box and verify that the script completed without any errors. 4. On the File menu, click Save All. 5. In Object Explorer, expand Databases | AdventureWorks2008 | Views | HumanResources.vEmployeeDetails | Indexes. 6. Verify that the IX_vEmployeeDetails index is listed. 7. 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.
  • 475.
    Lab: Implementing Views L6-45 MCT USE ONLY. STUDENT USE PROHIBITED Exercise 3: Creating Partitioned Views Task 1: Prepare the SQL Server instances 1. Click Start, and then click Computer. 2. In Microsoft® Windows® Explorer, navigate to the E:Mod06LabfilesStarter folder. 3. Double-click LabSetup.cmd to run the script that configures the servers for the partitioned view. 4. When the script completes, close Windows Explorer. Task 2: Create a new query file 1. In the Solution Explorer pane, right-click Queries, and then click New Query. 2. If the Connect to Server dialog box appears, click Connect. 3. On the File menu, click Save SQLQuery4.sql As. 4. 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-01SQLINSTANCE2].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01SQLINSTANCE3].AW_Contacts.Person.Contact 2. On the toolbar, click Execute. 3. On the File menu, click Save All. 4. In Object Explorer, right-click Databases, and then click Refresh.
  • 476.
    L6-46 Module 6: Implementing Views MCT USE ONLY. STUDENT USE PROHIBITED 5. Expand Databases | AW_Contacts | Views. 6. Verify that the Person.vContact view is listed. 7. In Object Explorer, expand Databases | AW_Contacts | Views | Person.vContact | Columns. 8. Verify that the correct columns are listed. 9. 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.
  • 477.
    Lab: Implementing StoredProcedures 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on as Student with the password of Pa$$w0rd. 3. Click Start, right-click Computer and then click Explore. 4. In Windows Explorer browse to E:MOD07LabfilesStarter. 5. Double-click the AWProgrammability project file. The Microsoft SQL Server Management Studio window opens. 6. If the Solution Explorer is not visible in the right pane, click View | Solution Explorer. 7. In the Solution Explorer, double-click InitilizeData.sql. 8. If the Connect to Sever dialog box appears, connect to server NY-SQL-01 using Windows Authentication. Click Connect. 9. 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.
  • 478.
    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. Select the text between the --Create GetDiscountsForCategory comment and the following comment. 2. On the toolbar, click the Execute button to execute the selected text. 3. To test the GetDiscountsForCategory stored procedure: select the text between the -- Test GetDiscountsForCategory comment and the following comment. 4. On the toolbar, click the Execute button. 5. Verify the query runs with no errors. Task 3: Create and test the GetDiscountsForCategoryAndDate stored procedure 1. Select the text between the --Create GetDiscountsForCategoryAndDate comment and the following comment. 2. On the toolbar, click the Execute button to execute the selected text 3. To test the GetDiscountsForCategoryAndDate stored procedure: select the text between the -- Test GetDiscountsForCategoryAndDate comment and the following comment. 4. On the toolbar, click the Execute button. 5. Verify the query runs with no errors. 6. Select the text between the comment -- Test GetDiscountsForCategoryAndDate with both parameters and the following comment. 7. On the toolbar, click the Execute button. 8. Verify the query runs with no errors.
  • 479.
    Lab: Implementing StoredProcedures L7-49 MCT USE ONLY. STUDENT USE PROHIBITED Task 4: Create and test the AddDiscount stored procedure 1. Select the text between the – Create AddDiscount comment and the following comment. 2. On the toolbar, click the Execute button to execute the selected text. 3. To test the AddDiscount stored procedure: select the text between the -- Test AddDiscount comment and the following comment. 4. On the toolbar, click the Execute button. 5. Verify the query runs with no errors. 6. 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. 7. 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. Exercise 2: Working with Execution Plans Task 1: View the text-based execution plan 1. In the Query window, select the code between the comment –Test the text- based execution plan and the following comment. 2. On the toolbar, click Execute. 3. Observe in the results pane both the query and the text based execution plan are displayed instead of query results. 4. 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. In the Query window, select the code between the comment –Test the graphical execution plan and the following comment. 2. Right-click the selection and then click Include Actual Execution Plan. 3. On the toolbar, click Execute.
  • 480.
    L7-50 Module 7: Implementing Stored Procedures MCT USE ONLY. STUDENT USE PROHIBITED 4. In the Results pane, observe that query results are returned. Observe the Execution Plan tab above the returned results. 5. Click the Execution Plan tab. 6. Observe that the execution plan shows that 0% of the execution’s 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. In the Query window select the code between the comment --Tune the database. Create an index on Name and the following comment. 2. On the toolbar, click Execute. Task 4: View the revised execution plan 1. In the Query window select the code below the comment –Retest the graphical execution plan. 2. In the toolbar, click Execute. 3. In the Results pane observe that query results are returned. Observe the Execution Plan tab above the returned results. 4. Click the Execution Plan tab. 5. Observe that the execution plan shows that 0% of the execution’s 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. 6. 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.
  • 481.
    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 User- defined function 1. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on as Administrator with the password of Pa$$w0rd. 3. From the Start Menu, right-click Computer, and then click Explore. 4. In Windows Explorer, browse to E:MOD08LabfilesStarter. 5. Double-click createnewuser.vbs. Click OK. 6. Open Command Prompt. Browse to E:MOD08LabfilesStarter. 7. Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER. 8. Log off Administrator and then log on as Student with the password of Pa$$w0rd. 9. From the Start Menu, right-click Computer, and then click Explore. 10. In Windows Explorer, browse to E:MOD08LabfilesStarter. 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.
  • 482.
    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.
  • 483.
    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. Select the CREATE FUNCTION statement. On the toolbar, click Execute. 3. In the Results pane, review the query results, verifying that the statement executed successfully. 4. Locate the Test Sales.GetDiscountsForDate comment, select the Transact- SQL statement shown below in the following Transact-SQL example: SELECT * FROM Sales.GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC 5. On the toolbar, click Execute. In the query results, verify that some rows are displayed. 6. On the File menu, click Save UserDefinedFunctions.sql.
  • 484.
    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 *
  • 485.
    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. On the toolbar, click Execute. 3. In the Results pane, review the query results. Verify that the statement executed successfully. 4. 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. On the toolbar, click Execute. In the query results, view the number of rows returned by each query. 6. On the File menu, click Save UserDefinedFunctions.sql. Results: After this exercise, you should have created and tested 3 user-defined functions.
  • 486.
    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. In Solution Explorer, double-click the ExecutionContext.sql query file. 2. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. 3. Select the USE AdventureWorks2008 statement. On the toolbar, click Execute. 4. Locate the Create Sales.GetCurrencyRate comment, and then create the user- defined 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. Select the CREATE FUNCTION statement. On the toolbar, click Execute. 6. In the Results pane, review the query results. Verify that the statement executed successfully. 7. Locate the Test Sales.GetCurrencyRate comment, and then test the function, as shown in the following Transact-SQL example: SELECT Sales.GetCurrencyRate('GBP')
  • 487.
    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-01Adam" 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. In Solution Explorer, double-click the TrustRelationship.sql query file. 2. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. 3. Select the USE AdventureWorksDW2008 statement. Click Execute. 4. Locate the Create the user for the NY-SQL-01Adam login comment, and then create a user called Adam in the AdventureWorksDW2008 database for the NY-SQL-01Adam 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-01Adam] GO 5. Select the IF and CREATE statements. On the toolbar, click Execute. 6. Verify that the statements executed successfully. 7. Locate the Grant AUTHENTICATE permission on the database comment. 8. 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
  • 488.
    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 Transact- SQL 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.
  • 489.
    Lab: Implementing Functions L8-59 MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Create and test the GetCurrencyDiscountedProducts User- defined Function 1. In Solution Explorer, double-click the ExecutionContext.sql query file. 2. Select the USE AdventureWorks2008 statement. On the toolbar, click Execute. 3. 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
  • 490.
    L8-60 Module 8: Implementing Functions MCT USE ONLY. STUDENT USE PROHIBITED 4. Select the CREATE FUNCTION statement. On the toolbar, click Execute. 5. Verify that the statement executed successfully. 6. 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. Select the SELECT statement. On the toolbar, click Execute. 8. Review the query results and verify that the statement executed successfully. 9. 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.
  • 491.
    Lab: Implementing ManagedCode 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Administrator using the password of Pa$$w0rd. 3. Click Start, point to All Programs, point to Microsoft® SQL Server® 2008, and then click SQL Server Management Studio™. 4. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Value Server type Database Engine Server name NY-SQL-01 Authentication Windows Authentication
  • 492.
    L9-62 Module 9: Implementing Managed Code in a Database MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Import the AWorksUtilities assembly 1. On the File menu, point to Open, and then click Project/Solution. 2. In the Open Project dialog box, browse to the E:MOD09LabfilesStarter folder click the AWorks_CLR.ssmssln file, and then click Open. 3. If Solution Explorer is not visible, on the View menu, click Solution Explorer. 4. In Solution Explorer, expand the Queries node, and then double-click the Initialize.sql query file. 5. On the toolbar, click Execute, and then confirm that no errors occur. 6. In Solution Explorer, double-click the ImportAssembly.sql query file. 7. Below the Enable CLR integration comment, add the following code: sp_configure 'clr enabled', 1 GO RECONFIGURE GO 8. On the toolbar, click Execute, and then verify that the statements executed successfully. 9. Below the Create assembly comment, add the following code: USE AdventureWorks2008 CREATE ASSEMBLY AWorksUtilities FROM 'E:MOD09LabfilesStarterAWorksUtilities.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.
  • 493.
    Lab: Implementing ManagedCode 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. In Solution Explorer, double-click the SaveXML.sql query file. 2. 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. Below the Create managed stored procedure comment, select the code, and then on the toolbar, click Execute. 4. Verify that the statements executed successfully. 5. Below the Test managed stored procedure comment, select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. 6. Confirm that an error message is displayed. The assembly does not have the required permissions to write to the file system. 7. Below the Change security permissions to allow file access comment, add the following code: ALTER ASSEMBLY AWorksUtilities WITH PERMISSION_SET = EXTERNAL_ACCESS GO 8. Select the ALTER ASSEMBLY statement, and then on the toolbar, click Execute. 9. 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.
  • 494.
    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:MOD09LabfilesStarter 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.
  • 495.
    Lab: Implementing ManagedCode 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. In Solution Explorer, double-click the GetLongDate.sql query file. 2. 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. Below the Create managed user-defined function comment, select the code, and then on the toolbar, click Execute. 4. Verify that the statements executed successfully. 5. Below the Test managed user-defined function comment, select the SELECT statement, and then on the toolbar, click Execute. 6. Verify that a list of orders is displayed that includes the day of the week in the OrderDate column. 7. Confirm that the records are displayed with a long OrderDate value. 8. On the File menu, click Save GetLongDate.sql.
  • 496.
    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. In Solution Explorer, double-click the EmailChange.sql query file. 2. 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. Below the Create trigger comment, select the code, and then on the toolbar, click Execute. 4. Verify that the statements executed successfully. 5. Below the Test trigger comment, select the first UPDATE statement, and then on the toolbar, click Execute. 6. Confirm that a message is displayed, noting the new e-mail address in the Messages pane. 7. Below the Test trigger comment, select the second UPDATE statement, and then on the toolbar, click Execute. 8. Confirm that there is no message because the statement did not update the e- mail 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. 9. On the File menu, click Save EmailChange.sql.
  • 497.
    Lab: Implementing ManagedCode in a Database L9-67 MCT USE ONLY. STUDENT USE PROHIBITED Task 4: Create the Concatenate managed aggregate function referencing the external assembly 1. In Solution Explorer, double-click the Concatenate.sql query file. 2. 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. Below the Create aggregate function comment, select the code, and then on the toolbar, click Execute. 4. Verify that the statements executed successfully. 5. Below the Test aggregate function comment, select the SELECT statement, and then on the toolbar, click Execute. 6. Confirm that orders are displayed as a concatenated string for each account in the Messages pane. 7. On the File menu, click Save Concatenate.sql.
  • 498.
    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. In Solution Explorer, double-click the IPAddress.sql query file. 2. Below the Create managed user-defined type comment, add the following code: USE AdventureWorks2008 GO CREATE TYPE IPAddress EXTERNAL NAME AWorksUtilities.IPAddress GO 3. Below the Create managed user-defined type comment, select the code, and then on the toolbar, click Execute. 4. Verify that the statements executed successfully. 5. Below the Test managed user-defined type comment, select the statements, and then on the toolbar, click Execute. 6. Confirm that three result sets are displayed that show the IPAddress value in various forms. 7. On the File menu, click Save IPAddress.sql. 8. Close the SQL Server Management Studio solution. 9. 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.
  • 499.
    Lab: Managing Transactionsand 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. In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Task 2: Create and commit a transaction 1. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect: Property Value Server type Database Engine Server name NY-SQL-01 Authentication Windows Authentication 3. On the File menu, point to Open, and then click File. 4. In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder, click Tran1.sql, and then click Open.
  • 500.
    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 Value Server name NY-SQL-01 Authentication 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. 8. 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 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.
  • 501.
    Lab: Managing Transactionsand Locks L10-71 MCT USE ONLY. STUDENT USE PROHIBITED Task 3: Create and rollback a transaction 1. On the File menu, point to Open, and then click File. 2. In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder, click Tran2.sql, and then click Open. 3. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect: Property Value Server name NY-SQL-01 Authentication 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. 5. 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 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. 7. On the File menu, click Save Tran2.sql. 8. Close SQL Server Management Studio. Results: After this exercise, you should have committed and rolled back transactions.
  • 502.
    L10-72 Module 10: Managing Transactions and Locks MCT USE ONLY. STUDENT USE PROHIBITED Exercise 2: Managing Locks Task 1: View locking information 1. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect: Property Value Server type Database Engine Server name NY-SQL-01 Authentication Windows Authentication 3. In SQL Server Management Studio, in the console tree, right-click NY-SQL-01, and then click Activity Monitor. 4. Review the information that is displayed in Processes, ResourceWaits, and Data File I/O, and Recent Expensive Queries. 5. On the File menu, point to New, and then click Query with Current Connection. 6. 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. Click Execute to execute the statement. 8. Review the information that shows the current lock in the master database. 9. On the File menu, point to Open, and then click File. 10. In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder, click Lock1.sql, and then click Open.
  • 503.
    Lab: Managing Transactionsand 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 Value Server name NY-SQL-01 Authentication 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-SQL- 01, 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.
  • 504.
    L10-74 Module 10: Managing Transactions and Locks MCT USE ONLY. STUDENT USE PROHIBITED Task 2: Set locking options 1. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect: Property Value Server type Database Engine Server name NY-SQL-01 Authentication Windows Authentication 3. On the File menu, point to Open, and then click File. 4. In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder, click Lock1.sql, and then click Open. 5. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect: Property Value Server name NY-SQL-01 Authentication Windows Authentication 6. Review the contents of the file, and then execute the query. 7. On the File menu, point to Open, and then click File. 8. In the Open File dialog box, browse to the E:Mod10LabfilesStarter folder, click Lock2.sql, and then click Open. 9. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect: Property Value Server name NY-SQL-01 Authentication Windows Authentication
  • 505.
    Lab: Managing Transactionsand 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:Mod10LabfilesStarter 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 Value Server name NY-SQL-01 Authentication 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.
  • 506.
    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. Click Execute to execute the query and wait five seconds. Notice that the query no longer waits indefinitely for the lock to be granted. 3. Close SQL Server Management Studio without saving the changes to the files. 4. Turn off the virtual machine and delete changes. Results: After this exercise, you should have set locking options and timeouts.
  • 507.
    Lab: Using ServiceBroker 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. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. 3. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. 4. 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. 5. Maximize the Microsoft SQL Server Management Studio window. Task 2: Create the AW_ServiceBroker SQL Server Scripts project 1. On the File menu, point to New, and then click Project. 2. In the New Project dialog box, in the Name field, type AW_ServiceBroker. 3. In the Location field, type E:MOD11LabfilesStarter. 4. Clear Create directory for solution and then click OK. Task 3: Configure the AdventureWorks database for Service Broker 1. On the Project menu, click New Query to add a new query file to the project. 2. If the Connect to Database Engine dialog box appears, click Connect. 3. If Solution Explorer is not visible, on the View menu, click Solution Explorer. 4. In Solution Explorer, in the Queries folder, right-click SQLQuery1.sql, click Rename, type PrepareDatabase.sql, and then press ENTER. 5. Notice how the name of the query in the design pane has automatically changed to PrepareDatabase.sql.
  • 508.
    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. On the toolbar, click Execute to execute the query. 8. On the File menu, click Save All.
  • 509.
    Lab: Using ServiceBroker L11-79 MCT USE ONLY. STUDENT USE PROHIBITED Task 4: Create the Service Broker objects required for the customer e- mail solution 1. On the Project menu, click New Query. 2. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type CreateServiceBrokerObjects.sql, and then press ENTER. 3. 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])
  • 510.
    L11-80 Module 11: Using Service Broker MCT USE ONLY. STUDENT USE PROHIBITED 4. On the toolbar, click Execute to execute the query. 5. On the File menu, click Save All. 6. If Object Explorer is not visible, on the View menu, click Object Explorer. 7. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Service Broker. 8. 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. 9. 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. Exercise 2: Implementing the Initiating Service Task 1: Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project 1. On the Project menu, click Add Existing Item. 2. In the Add Existing Item – AW_ServiceBroker dialog box, browse to the E:MOD11LabfilesStarter folder, click the CreateEmailNewCustomerSP.sql query file, and then click Add.
  • 511.
    Lab: Using ServiceBroker 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. 2. On the toolbar, click Execute to execute the query. 3. On the File menu, click Save All. 4. In Object Explorer, under AdventureWorks2008, expand Programmability, and then expand Stored Procedures. 5. Verify that the CustomerSvc.uspEmailNewCustomer stored procedure is listed. 6. 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. Exercise 3: Implementing the Target Service Task 1: Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project 1. On the Project menu, click Add Existing Item. 2. In the Add Existing Item – AW_ServiceBroker dialog box, browse to the E:MOD11LabfilesStarter folder, click the CreateSendEmailSP.sql query file, and then click Add.
  • 512.
    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. 2. On the toolbar, click Execute to execute the query. 3. On the File menu, click Save All. 4. In Object Explorer, right-click Stored Procedures, and then click Refresh. 5. Verify that the EMailSvc.uspSendCustomerEmail stored procedure is listed. Task 3: Configure the target service for automatic activation 1. On the Project menu, click New Query. 2. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type AlterServiceBrokerQueue.sql, and then press ENTER. 3. 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. On the toolbar, click Execute to execute the query. 5. On the File menu, click Save All.
  • 513.
    Lab: Using ServiceBroker L11-83 MCT USE ONLY. STUDENT USE PROHIBITED Task 4: Test the EmailService service 1. On the Project menu, click Add Existing Item. 2. In the Add Existing Item – AW_ServiceBroker dialog box, browse to the E:MOD11LabfilesStarter folder, click the TestEmailService.sql query file, and then click Add. 3. 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. 4. On the toolbar, click Execute to execute the query. 5. 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). 6. On the File menu, click Save All. 7. 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.
  • 514.
    MCT USE ONLY.STUDENT USE PROHIBITED