You are on page 1of 442

O F F I C I A L

M I C R O S O F T

L E A R N I N G

P R O D U C T

6232B

Implementing a Microsoft® SQL Server® 2008 R2 Database

Volume 2

ii

Implementing a Microsoft® SQL Server® 2008 R2 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. © 2011 Microsoft Corporation. All rights reserved. Microsoft, and Windows 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.

Product Number: 6232B Part Number: X17-52971 Released: 03/2011

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. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that may be included with the Licensed Content. “Student Content” means the learning materials accompanying these license terms that are for use by Students and Trainers during an Authorized Training Session. Student Content may include labs, simulations, and courseware files for a Course. “Trainer(s)” means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer and b) such other individual as authorized in writing by Microsoft and has been engaged by an Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its behalf.

g.

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

j.

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. Survival. Your duty to protect confidential information survives this agreement.

ii.

iii. Exclusions. You may disclose confidential information in response to a judicial or governmental order. You must first give written notice to Microsoft to allow it to seek a protective order or otherwise protect the information. Confidential information does not include information that    d. becomes publicly known through no wrongful act; you received from a third party who did not breach confidentiality obligations to Microsoft or its suppliers; or you developed independently.

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

e.

f.

5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.
a. Authorized Learning Centers and Trainers: i. Software.

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

o o o o 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. You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or downloaded from Devices on which you installed them. You will strictly comply with all Microsoft instructions relating to installation, use, activation and deactivation, and security of Virtual Machines and Virtual Hard Disks. You may not modify the Virtual Machines and Virtual Hard Disks or any contents thereof. You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.

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: © 2010 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 noninfringement. 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 pouv ez 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 partic ulier 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 R2 Database ix .

x Implementing a Microsoft® SQL Server® 2008 R2 Database Acknowledgements Microsoft Learning would like to acknowledge and thank the following for their contribution towards developing this title. Greg has worked with SQL Server since version 4. Greg Low – Lead Developer Dr Greg Low is a SQL Server MVP. Mark Hions – Technical Reviewer Mark's passion for computing and skill as a communicator were well suited to his position as an instructor at Honeywell Canada. mainframes. Chris Barker – Technical Reviewer Chris Barker is an MCT in New Zealand and currently employed as a staff trainer at Auldhouse. and has delivered training on every version since. Chris has also been an infrastructure trainer and has both Novell and Microsoft networking qualifications. and author focusing on SQL Server technologies. which is the largest provider of SQL Server training in the Toronto area. He has been programming from the early 1970s—his first program was written in assembly language and debugged in binary (literally)! While focusing training on programming (mostly . has designed SQL Server exams for Microsoft. Greg is best known for his SQL Down Under podcast (at www. He works as a trainer. an MCT. He is a regular speaker at conferences and is a co-author of the SQL Server 2008 R2 Upgrade Technical Reference Guide and SQL Server 2005 Step-by-Step Applied Techniques.com) where he interviews SQL Server MVPs and product team members on topics of interest to the SQL Server community. He is the CEO of SolidQ Australia which is part of Solid Quality Mentors. He has several Microsoft certifications including being an MCT since 1997. Herbert Albert – SolidQ Technical Reviewer Herbert Albert started his career in 1994. He has been an instructor in the Microsoft SQL Server Masters certification program for several years and was one of the first two people to achieve the SQL Server 2008 Master certification. he is a highly-rated presenter at TechEd. consultant. where he started working with minicomputers. Austria.sqldownunder. consultant. Together with Gianluca Hotz.NET) and databases (mostly Microsoft SQL Server). and mature students in 1984. . and trainer. and a Microsoft Regional Director for Australia. He is the author of a number whitepapers on the Microsoft MSDN and TechNet web sites and a number of SQL Server related books. He first met Microsoft SQL Server when it ran on OS/2.2 as an active mentor. and has delivered deep-dive courses through the Microsoft Partner Channel. Herbert writes a regular column at the SolidQ Journal. Herbert is a mentor and Managing Director of Solid Quality Mentors Central Europe located in Vienna. Their effort at various stages in the development has ensured that you have a good classroom experience. one of New Zealand’s major CPLS training centers in Wellington. An independent MCT and consultant for many years. Mark is now the Principal SQL Server Instructor and Consultant at DesTech.

Implementing a Microsoft® SQL Server® 2008 R2 Database xi Contents Module 13: Designing and Implementing User-Defined Functions Lesson 1: Overview of Functions Lesson 2: Designing and Implementing Scalar Functions Lesson 3: Designing and Implementing Table-Valued Functions Lesson 4: Implementation Considerations for Functions Lesson 5: Alternatives to Functions Lab 13: Designing and Implementing User-Defined Functions 13-3 13-7 13-14 13-19 13-26 13-29 Module 14: Ensuring Data Integrity through Constraints Lesson 1: Enforcing Data Integrity Lesson 2: Implementing Domain Integrity Lesson 3: Implementing Entity and Referential Integrity Lab 14: Ensuring Data Integrity through Constraints 14-3 14-10 14-18 14-28 Module 15: Responding to Data Manipulation via Triggers Lesson 1: Designing DML Triggers Lesson 2: Implementing DML Triggers Lesson 3: Advanced Trigger Concepts Lab 15: Responding to Data Manipulation via Triggers 15-3 15-13 15-20 15-30 Module 16: Implementing Managed Code in SQL Server 2008 R2 Lesson 1: Introduction to SQL CLR Integration Lesson 2: Importing and Configuring Assemblies Lesson 3: Implementing SQL CLR Integration Lab 16: Designing and Implementing Views 16-3 16-16 16-23 16-43 Module 17: Storing XML Data in SQL Server 2008 R2 Lesson 1: Introduction to XML and XML Schemas Lesson 2: Storing XML Data and Schemas in SQL Server Lesson 3: Implementing the XML Data Type Lab 17: Storing XML Data in SQL Server 17-3 17-15 17-26 17-31 Module 18: Querying XML Data in SQL Server Lesson 1: Using the T-SQL FOR XML Statement Lesson 2: Getting Started with XQuery Lesson 3: Shredding XML Lab 18: Querying XML Data in SQL Server 18-3 18-15 18-25 18-34 .

xii Implementing a Microsoft® SQL Server® 2008 R2 Database Module 19: Working with SQL Server® 2008 R2 Spatial Data Lesson 1: Introduction to Spatial Data Lesson 2: Working with SQL Server Spatial Data Types Lesson 3: Using Spatial Data in Applications Lab 19: Working with SQL Server Spatial Data 19-3 19-13 19-27 19-38 Module 20: Working with Full-Text Indexes and Queries Lesson 1: Introduction to Full-Text Indexing Lesson 2: Implementing Full-Text Indexes in SQL Server Lesson 3: Working with Full-Text Queries Lab 20: Working with Full-Text Indexes and Queries 20-3 20-10 20-21 20-33 Lab Answer Keys .

Designing and Implementing User-Defined Functions 13-1 Module 13 Designing and Implementing User-Defined Functions Contents: Lesson 1: Overview of Functions Lesson 2: Designing and Implementing Scalar Functions Lesson 3: Designing and Implementing Table-Valued Functions Lesson 4: Implementation Considerations for Functions Lesson 5: Alternatives to Functions Lab 13: Designing and Implementing User-Defined Functions 13-3 13-7 13-14 13-19 13-26 13-29 .

any code that must perform the logic can call the function. you will be able to: • • • • Design and implement scalar functions Design and implement table-valued functions Describe implementation considerations for functions Describe alternatives to functions . or to modify and maintain existing functions written by other developers. Rather than having to repeat all the function logic. you will learn the design and implementation of user-defined functions that enforce business rules or data consistency. Objectives After completing this lesson. In this lesson.13-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Functions are routines that are used to encapsulate frequently performed logic.

Objectives After completing this lesson.Designing and Implementing User-Defined Functions 13-3 Lesson 1 Overview of Functions Functions are routines made up of one or more Transact-SQL statements that can be used to encapsulate code for reuse. Functions do not support output parameters. but do return results. either a single value or a table. you will be able to: • • Describe different types of functions Use system functions . This lesson provides an overview of functions and describes system functions. A function takes zero or more input parameters and returns either a scalar value or a table.

SQL Server has several types of functions: scalar functions. While this is similar to a view. Inline table-valued functions An inline table-valued function returns a table that is the result of a single SELECT statement. An inline table-valued function could be written. Multi-statement table-valued functions are created for the same reasons as inline table-valued functions. Scalar Functions Scalar functions return a single data value of the type defined in a RETURNS clause. that takes the state code or ID as a parameter. For example. An example of a scalar function would be a function that extracts the protocol from a URL. an inline table-valued function is more flexible in that parameters can be passed to the SELECT statement. the function would return the string "http". and system functions.com". In this way. but are used when the logic that the function needs to implement is too complex to be expressed in a single SELECT statement. From the string "http://www. Table-valued functions can be created in two ways. rather than separate views for each state. . tablevalued functions. individual views could be created to return details of sales for particular states within the country. if a table holds details of sales for an entire country.13-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of Functions Key Points Most high-level programming languages offer functions as blocks of code that are called by name and which can process input parameters.microsoft. These are known as inline functions or multi-statement functions. only a single function would be needed to provide details for all states. 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.

Designing and Implementing User-Defined Functions 13-5 System Functions System functions are built-in functions provided by SQL Server to help you perform a variety of operations. They cannot be modified. Question: How have you used functions in other programming languages? .

Ranking functions such as ROW_NUMBER. Question: What would a cryptographic function be used for? . and NTILE perform windowing operations on rows of data. DENSE RANK. System Functions Most of the functions are scalar functions and provide the functionality commonly provided by functions in other high-level languages such as operations on data types (including strings and dates and times) and conversions between data types. SUM. Many of these functions automatically ignore NULL rows. A library of mathematical and cryptographic functions is provided. MAX. Aggregates such as MIN.13-6 Implementing a Microsoft® SQL Server® 2008 R2 Database System Functions Key Points SQL Server has a wide variety of built-in function that you can use in queries to return data or to perform operations on data. and COUNT perform calculations across groups of rows. RANK. AVG. Other functions provide details of the configuration of the system and its security.

and that functions can take zero or more input parameters and return either scalar values or a tables. in addition to the syntax for creating them.Designing and Implementing User-Defined Functions 13-7 Lesson 2 Designing and Implementing Scalar Functions You have seen that functions are routines made up of one or more Transact-SQL statements that can be used to encapsulate code for reuse. This lesson provides an overview of scalar functions and explains why and how you use them. Objectives After completing this lesson. you will be able to: • • • • Explain a scalar function Create scalar functions Describe data type limitations Explain deterministic and non-deterministic functions .

13-8

Implementing a Microsoft® SQL Server® 2008 R2 Database

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.

Scalar Functions
Unlike the definition of a stored procedure, where the use of a BEGIN…END that wraps the body of the stored procedure is optional, the body of the function must be defined in a BEGIN…END block. The function body contains the series of Transact-SQL statements that return the value. For example, consider the following function definition:
CREATE FUNCTION dbo.ExtractProtocolFromURL ( @URL nvarchar(1000)) RETURNS nvarchar(1000) AS BEGIN RETURN CASE WHEN CHARINDEX(N':',@URL,1) >= 1 THEN SUBSTRING(@URL,1,CHARINDEX(N':',@URL,1) - 1) END; END; GO

Note that the body of the function comprises a single RETURN statement that is wrapped in a BEGIN…END block. This function can be used as an expression wherever a single value could be used:
SELECT dbo.ExtractProtocolFromURL(N'http://www.microsoft.com'); GO IF (dbo.ExtractProtocolFromURL(@URL) = N'http') ...

Designing and Implementing User-Defined Functions

13-9

Scalar functions can also be implemented in managed code. Managed code will be discussed in Module 16. The allowable return values for scalar functions differ between functions that are defined in T-SQL and functions that are defined using managed code.

13-10

Implementing a Microsoft® SQL Server® 2008 R2 Database

Creating Scalar 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. Even though the body of the function (apart from inline functions) must be wrapped in a BEGIN…END block, the CREATE FUNCTION must be the only statement in the batch.

Scalar User-defined Functions
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.

Guidelines
Consider the following guidelines when you create scalar user-defined functions: • • Make sure that you use two-part naming for the function and for all database objects referenced by the function. 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.

Side-effects
A function that modifies the underlying database is considered to have "side-effects". In SQL Server, functions are not permitted to have side-effects. You may not change data in a database within a function, may not call a stored procedure and may not execute dynamic SQL code.

Designing and Implementing User-Defined Functions

13-11

Deterministic and Non-deterministic Functions

Key Points
Both built-in and user-defined functions fall into one of two categories: deterministic and nondeterministic. This distinction is important as it determines where a function can be used.

Deterministic Functions
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. Consider the following function definition:
CREATE FUNCTION dbo.AddInteger (@FirstValue int, @SecondValue int) RETURNS int AS BEGIN RETURN @FirstValue + @SecondValue; END; GO

Every time the function is called with the same two integer values, it would return exactly the same result.

Non-deterministic Functions
A non-deterministic 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. Consider the following function:
CREATE FUNCTION dbo.CurrentTimeInLondonAsString() RETURNS varchar(40) AS BEGIN RETURN CONVERT(varchar(40),SYSUTCDATETIME(),100); END;

13-12

Implementing a Microsoft® SQL Server® 2008 R2 Database

GO

Each time the function is called, it would return a different value, even though no input parameters are supplied. The OBJECTPROPERTY() function can be used to determine if a function is deterministic or not.

Designing and Implementing User-Defined Functions

13-13

Demonstration 2A: Scalar Functions

Key Points
In this demonstration you will see: • • • • How to create scalar user-defined functions How to query scalar user-defined functions How to determine if a scalar user-defined function is deterministic How to drop scalar user-defined functions

Demonstration Setup
1. 2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_13_PRJ\6232B_13_PRJ.ssmssln and click Open. Open and execute the 00 – Setup.sql script file from within Solution Explorer. Open the 21 – Demonstration 2A.sql script file. Follow the instructions contained within the comments of the script file.

3. 4. 5.

13-14

Implementing a Microsoft® SQL Server® 2008 R2 Database

Lesson 3

Designing and Implementing Table-Valued Functions

In this lesson you will learn how to work with functions that return tables instead of single values. There are two types of table-valued functions (TVFs): inline and multi-statement. Both types of TVF will be covered in this lesson. The ability to return a table of data is important as it allows a function to be used as a source of rows in place of a table in a T-SQL statement. In many cases, this can avoid the need to store data temporarily in tables.

Objectives
After completing this lesson, you will be able to: • • • Describe table-valued functions Describe Inline table-valued functions Describe multi-statement table-valued functions

Designing and Implementing User-Defined Functions

13-15

What are Table-valued Functions?

Key Points
Unlike scalar functions, TVFs return a table that can contain many rows of data, each with many columns.

Table-valued Functions
There are two ways to create TVFs. Inline TVFs return an output table defined by a RETURN statement that is comprised of a single SELECT statement. If the logic of the function is too complex to include in a single SELECT statement, the function needs to be implemented as a multi-statement TVF. Multi-statement TVFs construct a table within the body of the function and then return the table. They also need to define the schema of the table to be returned. Both types of TVF can be used as the equivalent of parameterized views.

The output table schema is derived from the SELECT statement that you provide within the RETURN statement. You do not explicitly define the schema of the returned table. The definition of the columns of the table is not shown. However. note that the return type is TABLE. For inline functions. Inline TVFs In the syntax example shown on the slide. You have learned that tables do not have a predefined order. 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. the body of the function is not enclosed in a BEGIN…END block.13-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Inline Table-Valued Functions Key Points You can use inline functions to achieve the functionality of parameterized views. Question: TVFs return rows of data as tables. Why does the example function in the slide include an ORDER BY clause? . the CREATE FUNCTION statement must be the only statement in the batch.

For each row. two columns are returned: the position of the date within the range of dates.Designing and Implementing User-Defined Functions 13-17 Multi-statement Table-valued Functions Key Points A multi-statement table-valued function allows for more complexity in how the table to be returned is constructed. This is very useful when the logic required for constructing the return table is more complex than would be possible within the definition of a view. you can use a table-valued function in the FROM clause of a Transact-SQL statement. You can use user-defined functions that return a table to replace views. Multi-statement TVFs A table-valued function (like a stored procedure) can use complex logic and multiple Transact-SQL statements to build a table. This cannot be implemented in a single SELECT statement unless another object such as a table of numbers. is already present in the database. In the example on the slide. an INSERT is performed into the table that is later returned. Question: Can you think of a situation where you would need to use a Multi-statement Table-valued Function rather than an Inline Table-valued Function? . In the same way that you use a view. As the system does not already include a table of dates. In each iteration of the loop. and the calculated date. a loop needs to be constructed to calculate the required range of dates. a function is created that returns a table of dates.

type Proseware in the Server name text box and click Connect. click Project/Solution. • 2. click Open. Question: What are some commonly used SQL Scalar functions that you can think of? . Open and execute the 00 – Setup. click Microsoft SQL Server 2008 R2.sql script file from within Solution Explorer. 3. click All Programs. click SQL Server Management Studio. Follow the instructions contained within the comments of the script file. navigate to D:\6232B_Labs\6232B_13_PRJ\6232B_13_PRJ.sql script file. In the Connect to Server window. Open the 31 – Demonstration 3A.13-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Implementing Table-Valued Functions Key Points In this demonstration you will see: • • • How to create a table-valued function How to query a table-valued function How to drop a table-valued function Demonstration Steps 1.ssmssln and click Open. click Start. From the File menu. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine.

it is important to avoid negative performance impacts through inappropriate use of functions. there are some key considerations that need to be made when creating functions.Designing and Implementing User-Defined Functions 13-19 Lesson 4 Implementation Considerations for Functions While the ability to create functions in T-SQL is very important. you will be able to: • • • • • Describe performance impacts of scalar functions Describe performance impacts of table-valued functions Control execution context Use EXECUTE AS clause Explain guidelines for creating functions . Performance problems due to such inappropriate usage are very common. In particular. This lesson provides guidelines for the implementation of functions and describes how to control their security context. Objectives After completing this lesson.

Common Performance Problems The over-use of scalar functions is a common cause of performance problems in SQL Server systems. In many cases. extracting the code from the function definition and incorporating it directly into the query will resolve the performance issue. .13-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Performance Impacts of Scalar Functions Key Points The code for views is incorporated directly into the code for the query that accesses the view. This is not the case for scalar functions. You will see an example of this in the next lab.

Common Performance Problems Multi-statement TVFs are not incorporated into the code of the query that uses them. The inappropriate usage of such TVFs is a common cause of performance issues in SQL Server. The CROSS APPLY operator is used to call a table-valued function for each row in the left-hand table within the query. Designs that require the calling of a TVF for every row in a table can lead to significant performance overhead.Designing and Implementing User-Defined Functions 13-21 Performance Impacts of Multi-statement Table-valued Functions Key Points Whether or not the code for a TVF is incorporated into the query that uses the function depends upon the type of table-valued function. You should examine the design to see if there is a way to avoid the need to call the function for each row. Inline TVFs are directly incorporated into the code of the query that uses them. .

usually determines execution context. . or executing (calling) a module. The user or login calling a module. Execution context establishes the identity against which permissions are checked. 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.13-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Controlling Execution Context Key Points Execution context is determined by the user or login connected to the session. such as a stored procedure or function. the code is said to “impersonate” the alternative user.

You can use the EXECUTE AS clause in a stored procedure or function to set the identity used as the execution context for the stored procedure or function. EXECUTE AS allows you to create procedures that execute code that the user executing the procedure is not permitted to execute. without the need for concerns regarding broken ownership chains or dynamic SQL execution.Designing and Implementing User-Defined Functions 13-23 The EXECUTE AS Clause Key Points The EXECUTE AS clause sets the execution context of a session. .

. This will avoid code complexity but will also increase the opportunities for reusing the functions. Avoid building large general purpose functions. Use two-part naming to qualify the name of any database objects referred to within the function and also use two-part naming when choosing the name of the function. • Avoid statements that will raise T-SQL errors. note that a WHERE clause that uses a predicate like: WHERE Function(CustomerID) = Value • • is likely to remove the usefulness of an index on CustomerID.13-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Guidelines for Creating Functions Key Points Consider the following guidelines when you create user-defined functions: • • The performance of inline functions is. Exception handling is not allowed within functions. In particular. try to implement functions as inline functions. much higher than the performance of multistatement functions. Keep functions relatively small and targeted at a specific purpose. Wherever possible. Consider the impact of using functions in combination with indexes. in many cases.

navigate to D:\6232B_Labs\6232B_13_PRJ\6232B_13_PRJ. click Open. In the virtual machine. 3. In the Connect to Server window. click Microsoft SQL Server 2008 R2. • 2. From the File menu. click All Programs. .Designing and Implementing User-Defined Functions 13-25 Demonstration 4A: Execution Context Key Points In this demonstration you will see how to alter the execution context of a function. click SQL Server Management Studio. Follow the instructions contained within the comments of the script file. Open and execute the 00 – Setup.sql script file from within Solution Explorer. type Proseware in the Server name text box and click Connect.ssmssln and click Open.sql script file. Open the 41 – Demonstration 4A. Demonstration Steps 1. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Start. click Project/Solution.

you will be able to: • • Compare table-valued functions and stored procedures Compare inline functions and views .13-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 5 Alternatives to Functions Functions are only one option for implementing code. This lesson explores situations where other solutions may or may not be appropriate and helps you make decisions about which solution to use. Objectives After completing this lesson.

Stored procedures can execute dynamic SQL statements. Functions cannot contain exception handling. For example. Stored procedures can modify data in database tables. . Functions can have significant performance impacts when not inlined and called for each row in a query. Functions are not permitted to execute dynamic SQL statements. Functions cannot modify data in database tables. There is no mechanism to permit the return of multiple rowsets from a single function call. Table-valued functions are able to return a single rowset from a function call.GetCriticalPathNodes). It is important to realize that not all client applications can call both and so they cannot necessarily be used interchangeably.Designing and Implementing User-Defined Functions 13-27 Comparing Table-valued Functions and Stored Procedures Key Points Table-valued functions and stored procedures can often be used to achieve similar outcomes. The output of a function could be assigned to a variable in code. you cannot execute the following code: SELECT * FROM (EXEC dbo. While it is possible to access the output rows of a stored procedure with an INSERT EXEC statement. Stored procedures can include detailed exception handling. Stored procedures can return multiple resultsets from a single stored procedure call. it is easier to consume the output of a function in code than the output of a stored procedure. There are also pros and cons of each approach. Functions that include such "side-effects" are not permitted.

This is mostly used to provide for updatable views based on multiple base tables. . Views and parameter-less TVFs are usually able to be consumed by most client application that can access tables. Not all such applications can pass parameters to a table-valued function.13-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Comparing Table-valued Functions and Views Key Points TVFs can provide similar outcomes to views. Views can have INSTEAD OF triggers associated with them. Views and inline TVFs can be updatable. Multi-statement TVFs are not updatable. Views and inline table-valued functions are incorporated into surrounding queries. Scalar and multistatement table-valued functions are not incorporated into surrounding queries and often lead to performance issues when used inappropriately. Inline TVFs are updatable.

Before you begin the lab. and then click Other User. Right-click 623XB-MIA-SQL and click Connect. you must complete the following steps: 1. In the Virtual Machines list. click Start. click on the Revert toolbar icon. Click Switch User. In Virtual Machine Connection window. Right-click 623XB-MIA-DC and click Start. If you are prompted to confirm that you want to revert. 7.Designing and Implementing User-Defined Functions 13-29 Lab 13: Designing and Implementing User-Defined Functions Lab Setup For this lab. In the Virtual Machine Connection window. you will use the available virtual machine environment. if the virtual machine 623XB-MIA-DC is not started: • • • 4. Right-click 623XB-MIA-DC and click Connect. 5. click Revert. and then click Hyper-V Manager. On the host computer. click the Ctrl-Alt-Delete menu item. 3. 2. and then close the Virtual Machine Connection window. if the user is not already logged on: • • On the Action menu. 6. In the Virtual Machine Connection window. point to Administrative Tools. Wait for the revert action to complete. In the Virtual Machines list. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. wait until the Press CTRL+ALT+DELETE to log on message appears. wait until the Press CTRL+ALT+DELETE to log on message appears. . if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start.

11. Requirements: Comma-Delimited List Function You need to create another version of this function called dbo.13-30 Implementing a Microsoft® SQL Server® 2008 R2 Database • Log on using the following credentials: i. and click Project/Solution. in the Virtual Machine Connection window. When the query window opens. open the project D:\6232B_Labs\6232B_13_PRJ\6232B_13_PRJ. 9. she would also like you to explore a performance-related problem with another existing function. 10. 14. In Connect to Server window. You need to design. Finally.LastName) AS FullName . check the Do not show me this console at logon check box and close the Server Manager window. Lab Scenario The existing marketing application includes some functions. In the Authentication drop-down list box. Supporting Documentation Function Specifications: Phone Number Function Name: FormatPhoneNumber (created in the dbo schema) Input Parameter: PhoneNumberToFormat nvarchar(16) Return Value: nvarchar(16) Rules to apply in formatting: • • • • • • • Any phone number beginning with the international dialing code (ie: a + sign).ssmssln. click All Programs.IntegerListToTable that takes a commadelimited list of integers and returns a similar table. You can assume that all integers sent to the function will be eight digits or less in length. In the File menu. select Windows Authentication and click Connect.JoinNames(FirstName. implement and test the function. click Full Screen Mode. type Proseware in the Server name text box. 15. In the virtual machine. click Open. From the View menu. Problematic Query SELECT dbo. should be left unformatted. 13. click Start. and click SQL Server Management Studio. if you have time. Password: Pa$$w0rd 8. 12. In Solution Explorer. In the Open Project window. click Microsoft SQL Server 2008 R2. User name: AdventureWorks\Administrator ii.sql. Your manager has requested your assistance in creating a new function for formatting phone numbers. double-click the query 00-Setup.MiddleName. click Execute on the toolbar. If the Server Manager window appears. She also needs you to modify an existing function to improve its usability. Phone numbers that contain 10 digits should be formatted as: (XXX) XXX-XXXX Phone numbers that contain 8 digits should be formatted as: XXXX-XXXX Phone numbers that contain 7 digits should be formatted as: XXX-XXXX Phone numbers that contain 6 digits should be formatted as: XXX-XXX All other characters should be stripped out Phone numbers that have different numbers of digits should have only the digits returned ie: (9234) 2345-2342 should be returned as 923423452342.

Designing and Implementing User-Defined Functions 13-31 FROM Marketing. .Prospect ORDER BY FullName.

She has asked you to create a function that will be used to format the phone numbers. implement and test the function.  Task 1: Review the design requirements • Review the Function Specifications: Phone Number in the supporting documentation. you should have created a new FormatPhoneNumber function within the dbo schema.  Task 2: Design and create the function • Design and create the function for reformatting phone numbers. The main tasks for this exercise are as follows: 1. Design and create the function. You need to design.13-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Formatting Phone Numbers Scenario ScenarioYour manager has noticed that phone numbers that are entered into the database tend to be formatted in different ways by different users. 3.  Task 3: Test the function • Execute the FormatPhoneNumber function to ensure function correctly formats the phone number. Test the function. Results: After this exercise. . 2. Review the requirements.

IntegerListToTable function and pass in an alternate delimiter such as the pipe | character. this causes issues with data types as the list often contains integers rather than just simple strings. In some application code. 4. Test the function with an alternate delimiter such as the pipe | character. Design and create the function. Review the requirements.IntegerListToTable function to ensure it returns the correct results.  Task 4: Test the function with an alternate delimiter such as the pipe | character • Test the dbo.  Task 2: Design and create the function • Design and create the dbo.  Task 3: Test the function • Execute the dbo. The main tasks for this exercise are as follows: 1.StringListToTable takes a comma-delimited list of strings and returns a table. Results: After this exercise. 3. Test the function.Designing and Implementing User-Defined Functions 13-33 Exercise 2: Modifying an Existing Function Scenario An existing function dbo.IntegerListToTable function.  Task 1: Review the requirements • Review the requirement for the dbo. 2.IntegerListToTable function in the Supporting Documentation. you should have created a new IntegerListToTable function within a dbo schema. .

Review the query Design an alternate query Use SET STATISTICS TIME ON to compare the performance of the new and old queries  Task 1: Review the query • Review the problematic query in the Supporting Documentation. Use the times returned to test how your new query compares with the original. You need to investigate it and suggest changes that might improve its performance.13-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 3: Resolve a Function-related Performance Issue (Only if time permits) Scenario The operations team manager has approached you about a query that is performing badly.  Task 3: Use SET STATISTICS TIME ON to compare the performance of the new and old queries • • Turn SET STATISTICS TIME ON. The main tasks for this exercise are as follows: 1. . 2. Results: After this exercise. you should have created an alternate query for the poorly-performing query.  Task 2: Design an alternate query • Design the query. 3.

2. 2. Avoid calling multi-statement TVFs for each row of a query. what privileges should the login or user creating the code have? Best Practices 1. . does not have. When using the EXECUTE AS clause. you can dramatically improve performance by extracting the code from the query into the surrounding query.Designing and Implementing User-Defined Functions 13-35 Module Review and Takeaways Review Questions 1. Use the WITH EXECUTE AS clause to override the security context of code that needs to perform actions that the user that is executing the code. what privileges should the login or user being impersonated have? When using the EXECUTE AS clause. In many cases.

13-36 Implementing a Microsoft® SQL Server® 2008 R2 Database .

Ensuring Data Integrity through Constraints 14-1 Module 14 Ensuring Data Integrity through Constraints Contents: Lesson 1: Enforcing Data Integrity Lesson 2: Implementing Domain Integrity Lesson 3: Implementing Entity and Referential Integrity Lab 14: Ensuring Data Integrity through Constraints 14-3 14-10 14-18 14-28 .

You should enforce data integrity at all levels of an application from first entry or collection through storage. . Describe how domain integrity can be maintained. Microsoft® SQL Server® provides a variety of features that simplify the enforcement of data integrity. and it can play a major role in the success or failure of an organization or a business venture. Describe how entity and referential integrity can be maintained. you will be able to: • • • Explain the available options for enforcing data integrity and the levels at which they should be applied. Objectives After completing this module.14-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview The quality of data in your database largely determines the usefulness and effectiveness of applications (and people) that rely on it. Ensuring data integrity is a critical step in maintaining high-quality data.

Explain the available options for enforcing data integrity. Describe the different types of data integrity. . Objectives After completing this lesson. you will be able to: • • • Explain how data integrity checks need to apply across different layers of an application. Data integrity refers to the consistency and accuracy of data that is stored in a database.Ensuring Data Integrity through Constraints 14-3 Lesson 1 Enforcing Data Integrity An important step in database planning is deciding the best way to enforce the integrity of the data.

The middle tier is often where the bulk of those requirements exist in code. User-Interface Level There are several advantages of enforcing integrity at the user-interface level.14-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Data Integrity Across Application Layers Key Points Data integrity can be applied at different levels within an application. Application Levels Applications are often structured in levels. There is no right and wrong answer for all situations. Common examples of application levels are: • • • User interface level Middle tier (sometimes referred to as business logic) Data tier Data integrity could be enforced at each of these levels. At this level. . Implementing integrity at this level helps avoid different rules and checks being applied by different user interfaces. The responsiveness to the end user is usually higher as minor errors can be trapped before any calls are made to other layers of code. the logic is still quite aware of the functions that cause errors so the error messages returned to the user can still be quite specific. This is done to keep related functionality together and to improve the maintainability of code and the chance of it being reusable. Middle Tier Many integrity issues are directly related to business logic requirements. The middle tier is often also reused by multiple user interfaces. Error messages are often clearer as the code is more aware of the action taken by the user that caused the error to occur.

Ensuring Data Integrity through Constraints 14-5 It is also easy for integrity checks that are only applied in the middle tier to be ineffective due to race conditions. so the error messages returned from this layer tend to be very precise in describing the issue but quite cryptic for an end user to understand. it is common for the same data to be accessed by multiple applications or even directly through tools such as SQL Server Management Studio. though. The challenge with this. They typically need to be retranslated by upper layers of code before being presented to the end users. In particular. all applications need to consistently apply all the rules and checks. though. Consider. it might seem easy to check that a customer exists and then allow an order to be placed for the customer. . For example. Multiple Tiers The correct solution in most situations involves rules and checks being applied at multiple levels. the possibility that the customer could be removed by another user between the time that you check for the customer's existence and the time that you record the order. The challenge of implementing some forms of integrity at the data tier (usually within the database) is that the data tier is often unaware of the user actions that caused an error to occur. If integrity is not maintained at the data tier level. Data Tier The advantage of implementing integrity at the data tier is that it cannot be bypassed by upper layers. is in maintaining consistency between the rules and checks at different application levels.

This is commonly called a primary key value. 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. format. . As an example of referential integrity. based on referential integrity. You are not permitted to insert a value in the referencing column that doesn’t exist in the referenced column in the target table. 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. assigning a tinyint data type to a column ensures that only values from 0 to 255 can be stored in that column. You can define referential integrity relationships within the same table or between separate tables. For example. entity integrity. and referential integrity. 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. or range of possible values allowed in a column. Domain integrity is often enforced by using validity checking and can be enforced by restricting the data type. Entity Integrity Entity (or table) integrity requires that all rows in a table have a way of being uniquely identified.14-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of Data Integrity Key Points There are three basic forms of data integrity commonly enforced in database applications: domain integrity. 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 a form of cascading action is permitted. you may need to ensure that an order cannot be placed for a nonexistent customer.

Ensuring Data Integrity through Constraints 14-7 Question: When might more than one type of integrity apply to a scenario? .

a tinyint column can have values from 0 to 255. then a value must be placed in it whenever a new row is inserted. This is often referred to as to whether a column is mandatory or not. Default Values If a column is not nullable. A default value allows a specific value to be inserted into a column when no value is supplied in the statement that inserted the row. For example. For example. Data Types The first option for making sure that data has integrity is to ensure that only the correct type of data is stored. The choice of a data type will also define the permitted range of values that can be stored. You . the smallint data type only allows values from -32768 to 32767. For example. you are not able to place alphabetic characters into a column that has been defined as storing integers. Constraints can also be applied at the table level and enforce relationships between the columns of a table. you might have a column that holds an order number but it is not mandatory. Nullability The nullability of a column determines whether or not a value must be present in the column. For example. You might decide to further constrain the column so that only values between 1 and 9 are permitted in the column. Constraints Constraints are used to further constrain the allowable values in a column than the limits provided by the data type.14-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Options for Enforcing Data Integrity Key Points The table summarizes the mechanisms provided by SQL Server for enforcing data integrity.

you can then enforce even more complex rules for integrity. which data integrity features are currently implemented in one of your databases? . Triggers are discussed in Module 15.Ensuring Data Integrity through Constraints 14-9 might then add a constraint which specifies that the column must have a value if the salesperson column also has a value. These were separate objects that were then bound to columns. In the code for the trigger. Triggers Triggers are procedures (somewhat like stored procedures) that are executed whenever specific events like INSERT or UPDATE occur on a specific object such as a table. Question: In your organization. They were reused across multiple columns. Note that defaults were a type of object and not the same as default constraints. In general. rules should be replaced by check constraints and defaults should be replaced by default constraints. Objects From Earlier Versions Early versions of SQL Server supported objects called rules and defaults. These objects have been deprecated and code that is based on them should be replaced.

you will be able to: • • • • Describe how data types can be used to enforce domain integrity. Describe how check constraints can be used to enforce domain integrity. processing errors can occur when unexpected or out-of-range values are encountered. If domain integrity is not enforced. Describe how column nullability can be used to enforce domain integrity. Objectives After completing this lesson.14-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Implementing Domain Integrity Domain integrity limits the range and type of values that can be stored in a column. Describe how default constraints can be used to provide default values for columns. It is usually the most important form of data integrity when first designing a database. .

alias data types allow the creation of a data type called ProductWeight. another column might be defined as decimal(12.5).NET Framework common language runtime System Data Types System data types are supplied by SQL Server.Ensuring Data Integrity through Constraints 14-11 Data Types Key Points Choosing an appropriate data type for each column is one of the most important decisions you need to take when designing a table as part of a database. and another column might be defined as decimal(16.2). One column might be defined as decimal(18.3). and then use it as the data type of all the columns. you may have several tables that store the weight of a product that was sold. This is even more common when the tables are designed by more than a single person. Alias Data Types It is common for consistency problems to occur when tables are designed.3). define it as decimal(18. For example. Data types can be assigned to a column by one of the following methods: • • • Using SQL Server system data types Creating alias data types that are based on system data types Creating user-defined data types from data types created in the Microsoft . This can help lead to more consistent database designs. A large range of data types are available as you have seen in Module 2. An additional advantage of alias data types is that code generation utilities can create more consistent code when the utilities have the additional information about the data types that alias data types provide. a user-interface design program could decide to always display and/or prompt for product weights in a specific way. Choosing a data type determines both the types of data that can be stored and the range of values that are permitted. For consistency. For example. .

For example. they are still effectively subsets of the existing system data types.14-12 Implementing a Microsoft® SQL Server® 2008 R2 Database User-defined Data Types The addition of managed code to SQL Server as part of SQL Server 2005 onwards brought the ability to create entirely new data types. User-defined data types created in managed code allow for the design of not only the data that is stored in a data type but the behavior of the data type. you could decide that it could be updated by calling a predesigned Resize method. . Besides designing how it would store images. you could design a jpeg data type. Designing user-defined data types is discussed in Module 16. While alias data types are user-defined.

This may be determined quite some time after the row was initially inserted. A NULL value is one that is unknown. In fact. . there is no logical value that could be placed in this column. Storage of NULL Another form of confusion arises about how NULL is stored. Note that database designers will argue as to whether or not a column such as LastSaleDate should even exist as it could be derived from the lack of sales but often such columns are created for pragmatic performance reasons. it is not a value but the lack of a value that makes it NULL. Columns that must have values are often referred to as mandatory columns. This confusion is further heightened by some other database engines (not current versions of SQL Server) that have no way of storing zero or an empty string as being different to the column being NULL.Ensuring Data Integrity through Constraints 14-13 Column Nullability Key Points Column nullability determines whether or not a value must be provided for the column. For example. Mandatory Columns An important decision that needs to be made when designing tables is whether or not each column must have a value in every row. the likely closing date for the opportunity may not be known. Even if no sales have been made. consider a YTD_Sales column. This concept is commonly misunderstood and misused. Another common reason for allowing a column to be NULL is because of the lack of information on what eventually will be placed in the column. It is zero. A column that is NULL is not the same as a numeric column being zero or a string column containing an empty string. In the example shown in the slide. the total of the sales for the year is not unknown. When no sales have been made. But consider another related column that is called LastSaleDate.

If a name is not supplied. DEFAULT Constraint At times a column is mandatory. However. that is. The value is retrieved from the evaluation of an expression and the data type returned by the expression must be compatible with the data type of the column. and a DEFAULT constraint exists on the column. It may wish to have a rule applied by which the value of the column is automatically generated. If a column is nullable and no value is provided for the column in the statement that inserted the row.14-14 Implementing a Microsoft® SQL Server® 2008 R2 Database DEFAULT Constraints Key Points A DEFAULT constraint provides a value for a column when no value is specified in the statement that inserted the row. However.default_constraints view. NULLable Columns and DEFAULT Constraints If a column is nullable and no value is provided for the column in the statement that inserted the row. DEFAULT constraints are associated with a database column. the names that are generated are not very . a value must be provided for the column. the column would be left NULL. They are used to provide a default value for the column when no value is supplied by the user. You can view the existing definition of DEFAULT constraints by querying the sys. SQL Server will automatically generate a name. if the statement that inserted the row explicitly inserted NULL. the application or program that is inserting the row might not be providing a value for that column. then the default value will be used. then the default value will not be used. However. Named Constraints SQL Server does not require you to supply names for constraints that you create.

. (Locating the name of a query would involve querying the sys. Having a consistent naming standard for constraints helps you know what that name is likely to be rather than having to execute a query to find the name.Ensuring Data Integrity through Constraints 14-15 intuitive. Dropping a constraint requires you to provide a name for the constraint you are dropping.constraints system view). it is generally considered a good idea to provide names for constraints as you create them and to do so in a consistent naming pattern. you must first remove any constraints associated with the column. Therefore. A good example of why naming constraints is important is that if a column needs to be deleted.

This does not include NULL return values. For example. . CHECK constraints reject values that evaluate to FALSE. Table-Level CHECK Constraints Apart from checking the value in a particular column. CHECK constraints are used as a form of “sanity” check. you may wish to further restrict the values that can be placed into the column.14-16 Implementing a Microsoft® SQL Server® 2008 R2 Database CHECK Constraints Key Points CHECK constraints limit the values that are accepted by a column by controlling the values that can be put in the column. FALSE. Logical Expression CHECK constraints work with any logical (Boolean) expression that can return TRUE. For example. Particular care must be given to any expression that could have a NULL return value. you might decide that a salary needs to be within a certain range or a person’s age must be in the range 0 to 150. you could decide that the FromDate column should not have a larger value than the ToDate column in the same row. More commonly. or UNKNOWN. For example. They will not be rejected. CHECK constraints can be applied at the table level to check the relationship between the values in more than a single column. CHECK Constraints After determining the data type for a column. you might decide that a varchar(7) column must be 5 characters long if the first character is the letter A.

2. In the Connect to Server window. click Project/Solution. Demonstration Setup 1. . click Microsoft SQL Server 2008 R2. Open and execute the 00 – Setup. 3. Open the 21 – Demonstration 2A. click Start.ssmssln and click Open.Ensuring Data Integrity through Constraints 14-17 Demonstration 2A: Data and Domain Integrity Key Points In this demonstration you will see how to enforce data and domain integrity. type Proseware in the Server name text box and click Connect. In the virtual machine. 4. Follow the instructions contained within the comments of the script file. 5. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.sql script file from within Solution Explorer. click Open.sql script file. click SQL Server Management Studio. From the File menu. click All Programs. navigate to D:\6232B_Labs\6232B_14_PRJ\6232B_14_PRJ.

you will be able to: • • • • • Explain how primary key constraints are used to enforce entity integrity Describe how unique constraints differ from primary key constraints Explain how foreign key constraints are used to enforce referential integrity Describe how table relationships can be maintained while deleting or updating data through cascading relationships Explain the common considerations for constraint checking .14-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Implementing Entity and Referential Integrity It is important to be able to uniquely identify rows within tables and to be able to establish relationships across tables. For example. Objectives After completing this lesson. This can be enforced via a combination of entity and referential integrity. you will need to make sure that a customer can be identified and that the customer exists before you allow an order to be placed for that customer.

. in the example shown in the slide. A surrogate key is a value that is unrelated to the data. None of the columns that are part of a candidate key are permitted to be nullable. A natural key is formed from one or more columns that exist in the data within the table. Natural vs. you might give a customer a number. They must be unique and not NULL. Surrogate Keys A near religious debate exists in the database community about the use of natural vs. size. you might identify a product by its description. SQL Server will internally create an index to support the PRIMARY KEY constraint. PRIMARY KEY Constraints In database terminology. For example.Ensuring Data Integrity through Constraints 14-19 PRIMARY KEY Constraints Key Points Primary key constraints are used to uniquely identify each row in a table. They may involve multiple columns. For example. For example. the OpportunityID column has been chosen as the PRIMARY KEY. it is desirable to choose a name for the constraint rather than allowing SQL Server to do so. A PRIMARY KEY is a candidate key that has been chosen as the primary way to identify each row in a table. the term “candidate key” is used to describe the column or combination of columns that are required to be able to uniquely identify a row of data within a table. As was described with other types of constraints. and color. surrogate keys. Surrogate keys are often chosen as they are typically smaller than natural keys (which in some situations can help with performance) and because it can be very difficult to locate appropriate natural keys. even though a name is not required when defining a PRIMARY KEY constraint.

consider a Person table. what combinations of columns would be needed to create a candidate key? .14-20 Implementing a Microsoft® SQL Server® 2008 R2 Database For example. Question: In the example table shown in the slide. What attributes of a person you might need to combine before you could uniquely identify that person. which of these attributes will never change? Ideally. Further. if the table did not have the OpportunityID column. primary keys for tables should not change values over time.

even though a name is not required when defining a UNIQUE constraint. SQL Server will internally create an index to support the UNIQUE constraint.Ensuring Data Integrity through Constraints 14-21 UNIQUE Constraints Key Points A UNIQUE constraint indicates that the column or combination of columns is unique. you would store one of these values. UNIQUE Constraints A UNIQUE constraint is used to ensure that more than one row does not have a single value. . you would include a CHECK constraint to make sure the value is in one of the two valid formats and you would have a UNIQUE constraint on the column that stores these values. NULL and UNIQUE While it is possible for a value that is required to be unique to be NULL. For example. If you were storing a tax identifier for employees in Spain. In practice. all Spanish citizens over the age of 14 are issued with a national identity document called a DNI (Documento Nacional de Identidad). this is only permitted for a single row. this means that nullable unique columns are rare. As was described with other types of constraints. it is desirable to choose a name for the constraint rather than allowing SQL Server to do so. Note that this may be unrelated to the fact that the table has another unique identifier such as an EmployeeID that is used as a primary key for the table. in Spain. One row can be NULL. It is a unique number in the format 99999999-X where 9 is a digit and X is a letter used as a checksum of the digits. People from other countries that need a Spanish identification number are given an NIE (Numero de Indentificacion de Extranjeros) with a slightly different format X-99999999-X.

For example. you might want to make sure that a customer exists before you allow an order to be entered for the customer. This can be enforced in this form of integrity (referred to as referential integrity) with FOREIGN KEY constraints. A FOREIGN KEY constraint must refer to either a PRIMARY KEY or a UNIQUE constraint in the target table if the value in the referencing table is not NULL. The NOCHECK option can be applied to other types of constraints as well.14-22 Implementing a Microsoft® SQL Server® 2008 R2 Database FOREIGN KEY Constraints Key Points A FOREIGN KEY constraint is used to establish a link between the data in tables and can be used to enforce the relationship. FOREIGN KEY Constraints As mentioned earlier. SQL Server does not apply the check to existing rows and will only check the reference in future when rows are inserted or updated. it is desirable to choose a name for the constraint rather than allowing SQL Server to do so. if you specify WITH NOCHECK. Note that you cannot change the length of a column that is defined with a FOREIGN KEY constraint. WITH NOCHECK When you add a FOREIGN KEY constraint to a column (or columns) in a table. As described with other types of constraints. However. even though a name is not required when defining a FOREIGN KEY constraint. an employee row might reference a manager that is another row in the same employee table. SQL Server will check the data already in the column to make sure that the reference to the target table is valid. . The target table can be the same table.

Ensuring Data Integrity through Constraints 14-23 REFERENCES Permission Before you can place a FOREIGN KEY constraint on a table. . by a brute force attempt that involves trying all possible values. This avoids the situation where another user could place a reference to one of your tables and then you would be unable to drop or substantially change your own table until that reference was removed by the other user. keep in mind that providing REFERENCES permission to a user on a table that they do not have SELECT permission on does not totally prevent them from working out what the data in the table is. you must at least have REFERENCES permission on the target table. In terms of security though.

this means that the orders would still exist but they would not refer to any customer. Cascading Referential Integrity By using cascading referential integrity constraints. This allows for more control than the SET NULL option which always sets the values to NULL. Cautions While cascading referential integrity is easy to set up. if you attempt to delete a customer and there are orders for the customer. SET NULL causes the values in the columns in the referencing table to be nullified. SET DEFAULT causes the values in the columns in the referencing table to be set to their default values. extreme caution should be exercised in using it within database designs.14-24 Implementing a Microsoft® SQL Server® 2008 R2 Database 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. their orders will be deleted as well. . This action is referred to as cascading referential integrity. you can define the actions that SQL Server takes when a user tries to update or delete a key column (or columns) to which a FOREIGN KEY constraint references. The action to be taken is separately defined for UPDATE and DELETE actions and can have four values. CASCADE makes the required changes to the referencing tables. NO ACTION is the default. If the customer is being deleted. For the customer and orders example. If the customer primary key is being updated (note this is undesirable anyway). then the customer key in the orders table will also be updated so that the orders still refer to the correct customer. the delete will fail. For example.

What types of cascading options would be appropriate for updating or deleting records? . you remove the orders. Also. But there may be other tables referencing the orders table (such as order details or even invoices). would it really be okay for the orders for the customer to be removed when you decide to remove a customer. When you remove the customer. keep in mind the cascading nature of this situation. in the CASCADE option. Question: Think of a scenario involving data for a human resources department.Ensuring Data Integrity through Constraints 14-25 For example. based on business rules? Most organizations might be okay with orders disappearing but might be much less happy to see other objects like invoices disappearing. These will be removed as well.

alter. Changing Constraints You can create. High Performance Data Loading or Updates When performing bulk loading or updates of data. you should specify meaningful names for constraints rather than having SQL Server select a name. .14-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Considerations for Constraint Checking Key Points There are a few common considerations that need to be made when working with constraints. altered. Doing so will allow for more responsive systems (that go through less layers of code) and provide more meaningful errors back to users as the code is closer to the business-related logic that led to the errors. or dropped with the ALTER TABLE statement. Naming As mentioned earlier in the module. Error Checking in Applications Even though you have specified constraints in your database layer. you need to refer to constraints by name. Constraints are added. Therefore. you may also want to be checking these same references in higher layers of code. or drop constraints without having to drop and recreate the underlying table. better performance will often be achieved by disabling constraints (CHECK and FOREIGN KEY constraints) while performing the bulk operations and then reenabling them afterwards. The challenge though is in keeping the checks between different layers consistent. SQL Server provides complicated system-generated names. rather than having them checked row by row during the bulk operation. Often. it is better to have chosen them yourself and to have applied a consistent naming convention when doing so.

click All Programs.sql script file. navigate to D:\6232B_Labs\6232B_14_PRJ\6232B_14_PRJ. Follow the instructions contained within the comments of the script file. click Project/Solution. click SQL Server Management Studio. type Proseware in the Server name text box and click Connect. • 2.sql script file from within Solution Explorer. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Start. Open and execute the 00 – Setup. click Open. click Microsoft SQL Server 2008 R2.ssmssln and click Open. From the File menu. .Ensuring Data Integrity through Constraints 14-27 Demonstration 3A: Entity and Referential Integrity Key Points In this demonstration you will see how to define: • • • Entity integrity for tables Referential integrity for tables Cascading referential integrity constraints Demonstration Steps 1. 3. In the virtual machine. In the Connect to Server window. Open the 31 – Demonstration 3A.

Log on using the following credentials: . wait until the Press CTRL+ALT+DELETE to log on message appears. and then close the Virtual Machine Connection window. Maximize the Hyper-V Manager window. you will use the available virtual machine environment. you must complete the following steps: 1. In the Virtual Machines list. click Start. click the Ctrl-Alt-Delete menu item. Right-click 623XB-MIA-SQL and click Connect. Click Switch User. In the Virtual Machine Connection window. and then click Other User. click Revert. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-DC and click Start. click on the Revert toolbar icon. In the Virtual Machine Connection window. If you are prompted to confirm that you want to revert. 6. Right-click 623XB-MIA-DC and click Connect. 7.14-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 14: Ensuring Data Integrity through Constraints Lab Setup For this lab. 2. wait until the Press CTRL+ALT+DELETE to log on message appears. 3. Before you begin the lab. On the host computer. Wait for the revert action to complete. In the Virtual Machine Connection window. if the virtual machine 623XB-MIA-DC is not started: • • • 4. In the Virtual Machines list. 5. and then click Hyper-V Manager. In Virtual Machine Connection window. point to Administrative Tools. if the user is not already logged on: • • • On the Action menu.

When the query window opens. User name: AdventureWorks\Administrator ii. 15. In Solution Explorer. In Connect to Server window. you will implement the required constraints to ensure data integrity and.Yield has recently been added to the Marketing system in the MarketDev database but has no constraints in place. In this lab. Lab Scenario A table named Marketing. 10. 11. If the Server Manager window appears. in the Virtual Machine Connection window. click Start. In the Authentication drop-down list box. double-click the query 00-Setup. and click Project/Solution. click Full Screen Mode. From the View menu. In the File menu. and click SQL Server Management Studio.ssmssln. type Proseware in the Server name text box. 12. 9. click Execute on the toolbar. Password: Pa$$w0rd 8.Ensuring Data Integrity through Constraints 14-29 i. 13. click Microsoft SQL Server 2008 R2. 14. open the project D:\6232B_Labs\6232B_14_PRJ\6232B_14_PRJ. if you have time. test that constraints work as specified. click All Programs. click Open.Yield Note: Primary key should be a combination of ProspectID and LanguageID and should be a clustered primary key.sql. In the virtual machine. Supporting Documentation Table Marketing. check the Do not show me this console at logon check box and close the Server Manager window. Mandatory Field Required Required Required Column ProspectID LanguageID YieldOutcome Data Type int nchar(6) int Validation rule Must be a valid prospect Must be a valid language Default value should be zero if not supplied Must be a value between 0 and 9 RowID uniqueidentifier Required Default value should be a new uniqueidentifier if not supplied Must be unique LastUpdate datetime2 Required Default value should be SYSDATETIME() if not supplied Notes nvarchar(MAX) Optional . In the Open Project window. select Windows Authentication and click Connect.

you should have altered the Marketing.Yield table.Yield table • Work through the list of requirements and alter the table with appropriate constraints based on the requirements. Results: After this exercise.Yield.Yield table  Task 1: Review the supporting documentation • Review the table design requirements supplied in the supporting documentation.14-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Constraint Design Scenario You have been provided with the design for a table called Marketing. You need to alter the table with the appropriate constraints based upon the provided specifications. . The main tasks for this exercise are as follows: 1.  Task 2: Alter the Marketing. 2. Review the supporting documentation Alter the Marketing.

 Task 3: Test the foreign key reference on language • Execute T-SQL statements to ensure that the foreign key reference on LanguageID works as expected. Results: After this exercise. Test the primary key. 3. 2.Ensuring Data Integrity through Constraints 14-31 Challenge Exercise 2: Test the constraints (Only if time permits) Scenario You should now test each of the constraints that you designed to ensure they work as expected. you should have tested and confirmed that the constraints that are functioning as expected.  Task 1: Test the default values and data types • Execute T-SQL statements to ensure that the default values and data types work as expected. 4.  Task 4: Test the foreign key reference on prospect • Execute T-SQL statements to ensure that the foreign key reference on ProspectID works as expected. Test the foreign key reference on language. The main tasks for this exercise are as follows: 1. Test the default values and data types. . Test the foreign key reference on prospect.  Task 2: Test the primary key • Execute T-SQL statements to ensure that the primary key reference works as expected.

2. if you do not specify a name for the constraint. . However. Why implement check constraints if an application is already checking the input data? What are some scenarios in which you may want to temporarily disable constraint checking? Best Practices 1. SQL will generate a unique name for the constraint. When you create a constraint on a column.14-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. you may want to be sure to always name constraints to adhere to your naming conventions.

Responding to Data Manipulation via Triggers 15-1 Module 15 Responding to Data Manipulation via Triggers Contents: Lesson 1: Designing DML Triggers Lesson 2: Implementing DML Triggers Lesson 3: Advanced Trigger Concepts Lab 15: Responding to Data Manipulation via Triggers 15-3 15-13 15-20 15-30 .

entity. you will learn what DML triggers are and how they enforce data integrity. In this lesson. and how to define triggers in your database. the different types of triggers available to you. Objectives After completing this module. you will be able to: • • • Design DML triggers Implement DML triggers Explain advanced DML trigger concepts . The enforcement of integrity helps you to build reliable applications. and referential data integrity and business logic.15-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Data manipulation language (DML) triggers are a powerful tool that enables you to enforce domain.

DML triggers need to be able to work with both the previous state of the database and its changed state. It is important to know what they do and how they work and it is also important to understand how they differ from DDL triggers. SET NOCOUNT ON helps avoid side effects of triggers. Avoid impacting existing applications by using SET NOCOUNT ON. . Explain how AFTER triggers differ from INSTEAD OF triggers and where each should be used. you will be able to: • • • • • Describe DML triggers. Access both the prior and final states of the database data by using the inserted and deleted virtual tables. it is important to become familiar with how they should be designed. to avoid making common design errors. You will see how the inserted and deleted virtual tables provide that capability. Several types of DML triggers are available. Describe performance-related considerations for triggers. As DML triggers are often added after applications are built. Objectives After completing this lesson. it is important then to make sure that adding a trigger does not cause errors in the applications that were designed without them being in place.Responding to Data Manipulation via Triggers 15-3 Lesson 1 Designing DML Triggers Before beginning to create DML triggers.

these changes can be executed more efficiently by using cascading referential integrity constraints. UPDATE. 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. however. Complex Logic and Meaningful Error Messages Triggers can guard against malicious or incorrect INSERT. DDL events occur for most CREATE. ALTER or DROP statements in the T-SQL language. Triggers can cascade changes through related tables in the database. that outer transaction is also rolled back. The ability to roll back a transaction allows you to undo the effect of a T-SQL statement if the logic in your triggers decides that the statement should not have been executed. Trigger Operation The trigger and the statement that fires it are treated as a single operation. DDL triggers are similar to DML triggers but DDL triggers fire when DDL events occur. such as modifying the data or displaying a user-defined error message. which can be rolled back from within the trigger. or DELETE statement modifies the data in a specified table or view. If the statement is part of another transaction. This includes any INSERT. A trigger can query other tables and can include complex Transact-SQL statements. a trigger could check referential integrity for one column. Unlike CHECK constraints. . UPDATE. There is no concept of a Logoff trigger at present. triggers can reference columns in other tables. in many cases. or DELETE statement that form part of a MERGE statement. and DELETE operations and enforce other restrictions that are more complex than those defined by using CHECK constraints. For example. only when another column holds a specific value.15-4 Implementing a Microsoft® SQL Server® 2008 R2 Database What are DML Triggers? Key Points A DML trigger is a special kind of stored procedure that executes when an INSERT. Logon triggers are a special form of trigger that fire when a new session is established. UPDATE.

if the person processing the change is not a manager. Multiple Triggers Multiple triggers of the same type (INSERT. or DELETE) on a table allow multiple different actions to take place in response to the same modification statement. you may wish to check that the balance of a customer's account does not change by more than a certain amount. Triggers also allow the use of custom error messages for when constraint violations occur. Question: Why would you choose to use a DML trigger instead of a constraint? . This could make the messages that are passed to end users more meaningful. UPDATE.Responding to Data Manipulation via Triggers 15-5 Triggers can evaluate the state of a table before and after a data modification and take actions based on that difference. For example.

or DELETE statement executes and modifies the data in the database. The main difference between them relates to when they fire. This means that an INSERT. AFTER Triggers AFTER triggers fire after the data modifications that are part of the event that they relate to completes. trigger-based code can be replaced by other forms of code. Default values and calculated values are typically implemented via DEFAULT constraints and persisted . Each type of DML trigger can be implemented in either T-SQL or in managed code. After that modification has completed. Implementing default values or calculated values within rows. the other fires instead of the event. One fires after the event. INSTEAD OF Triggers Key Points There are two types of DML triggers: AFTER triggers and INSTEAD OF triggers. auditing might be provided by SQL Server Audit (discussed in course 6231B – Maintaining a SQL Server 2008 R2 Database). UPDATE. AFTER triggers associated with that event then fire. For that reason. For example. the trigger only fires a single time.15-6 Implementing a Microsoft® SQL Server® 2008 R2 Database AFTER Triggers vs. you will explore how they are designed and implemented using T-SQL. Implementing complex rules involving the relationship between tables. In many cases. triggers need to be designed to handle multiple rows. In this module. This design is different to other database engines where triggers are written to target single rows and are called multiple times when a statement affects multiple rows. Common reasons for implementing AFTER triggers are: • • • Providing auditing of the changes that were made. Relationships between tables are more typically implemented via foreign key constraints. Managed code is described in Module 16: Implementing Managed Code in SQL Server. It is important to realize that even if an UPDATE (or other data modification statement) modifies many rows.

A very common use case for INSTEAD OF triggers is to allow views that are based on multiple base tables to be updatable. only the code in the trigger is executed. If that statement was part of a larger transaction. that other transaction would be rolled back too. INSTEAD OF Triggers INSTEAD OF triggers are a special type of trigger that executes alternate code instead of executing the statement that they were fired from. the complexity of the logic required will make triggers a good solution. In some situations though. Question: Why would the ability to run alternate code help to allow views with multiple base tables to be updatable? . the data modification statement that it is associated with will be rolled back.Responding to Data Manipulation via Triggers 15-7 calculated columns. If the trigger executes a ROLLBACK statement. It is important to realize that with an INSTEAD OF trigger.

inserted Virtual Table After an INSERT operation. the inserted and deleted virtual tables hold details of the modifications that need to be made but have not yet been made. the inserted virtual table holds details of the rows just inserted. it is important to be able to make decisions based on what changes have been made to the data. deleted Virtual Table After a DELETE operation. The underlying table also has those rows in it. DELETE. The underlying table no longer contains those rows. or UPDATE statement is attempted and an INSTEAD OF trigger is associated with the event on the table.15-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Inserted and Deleted Virtual Tables Key Points When designing a trigger. These virtual tables are often then joined to the modified table data as part of the logic within the trigger. the deleted virtual table holds details of the rows just deleted. To arrive at effective decisions. After an UPDATE operation. INSTEAD OF Triggers and the inserted and deleted Virtual Tables When an INSERT. DML triggers provide this via a pair of virtual tables called inserted and deleted. . the inserted virtual table holds details of the modified versions of the rows. After an UPDATE operation. The underlying table holds the modified versions. The underlying table also has those rows in the modified form. access is needed to details of both the unmodified and modified versions of the data. the deleted virtual table holds details of the rows prior to the modification being made.

.Responding to Data Manipulation via Triggers 15-9 Scope of inserted and deleted The inserted and deleted virtual tables are only available during the execution of the trigger code and are scoped directly to the trigger code. This means that if the trigger code was to execute a stored procedure. that stored procedure would not have access to the inserted and deleted virtual tables.

every modification to the row causes a change in the rowversion column.15-10 Implementing a Microsoft® SQL Server® 2008 R2 Database SET NOCOUNT ON Key Points When adding a trigger to a table.Address = @NewAddress WHERE Customer. . The application was designed so that the update only occurs if the Concurrency column has not been altered. it is important to avoid breaking any existing applications that are accessing the table unless the intended purpose of the trigger is to avoid misbehaving applications from making inappropriate data changes. The application then checks the count of updated rows that is returned by SQL Server. This situation can be avoided by the SET NOCOUNT ON statement. writes an audit row into an audit table). When the application sees that only a single row has been modified. consider the following code: UPDATE Customer SET Customer. A common mistake when adding triggers is that if the trigger also causes row modifications (for example. It also knows that no other user had modified the row since the application read the data.Concurrency = @Concurrency. Customer. In this case. For example. When the application intends to modify a single row. With rowversion columns. It is common for application programs to issue data modification statements and to check the returned count of the number of rows affected. that count is returned in addition to the expected count. Most triggers should include this statement. it issues an UPDATE statement for that row. This is often done as part of an optimistic concurrency check. the application knows that only the row it intended to change was changed.CustomerID = @CustomerID AND Customer.FullName = @NewName. the column Concurrency is a rowversion data type column.

In SQL Server 2008 R2. there is a configuration setting ‘disallow results from triggers’ which when set to 1.Responding to Data Manipulation via Triggers 15-11 Returning Rowsets While it is possible to include a SELECT statement within a trigger and for it to return rows. In future versions of SQL Server. the creation of this type of side-effect is discouraged. . will disallow this capability. the ability to do this is likely to be removed.

it does so by executing a ROLLBACK statement. Constraints are used when the checks that need to be performed are relatively simple. Constraints are checked before any data modification is attempted and so often provide much higher performance than is possible with triggers. Constraints vs. constraints are preferred to triggers for performance reasons. the inserted and deleted virtual tables were essentially like a view above the data in the transaction log. This special table holds copies of the data in the inserted and deleted virtual tables for the duration of the trigger. trigger performance has been improved when compared to earlier versions. Triggers are also complex to debug as the actions they perform are not visible directly in the code that causes them to fire. This causes the entire work done by the statement to then be undone by the ROLLBACK. particularly in ROLLBACK situations.15-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Trigger Performance Considerations Key Points In general. Higher performance is obtained by avoiding the data modification ever occurring. Triggers also increase the time taken for data modification transactions as they add extra steps that SQL Server needs to process during these operations. RowVersions and tempdb Since SQL Server 2005. Triggers When an AFTER trigger decides to disallow a data modification. . a special rowversion table was provided in the tempdb database. From SQL Server 2005 onwards. In earlier versions. The data in these tables needed to be reconstructed when it was required. This design improved the performance of triggers but means that excessive usage of triggers could cause performance issues within the tempdb database. Triggers allow complex logic to be checked.

Objectives After completing this lesson. . Implement AFTER DELETE triggers.Responding to Data Manipulation via Triggers 15-13 Lesson 2 Implementing DML Triggers Lesson 1 provided information on designing DML triggers. Implement AFTER UPDATE triggers. you will be able to: • • • Implement AFTER INSERT triggers. It is now important to consider how to implement the designs that have been created.

insertions to the table Sales. The trigger can examine the inserted virtual table to determine whether or how the trigger actions should be executed. A common error when designing AFTER INSERT triggers is to write them with the assumption that only a single row is being inserted. Note that the trigger processes all inserted rows at once. The action of the INSERT statement is completed before the trigger fires. AFTER INSERT Trigger Actions When an AFTER INSERT trigger fires. Multi-Row Inserts In the example shown.OpportunityAudit. The inserted virtual table holds a copy of the rows that have been inserted into the base table.15-14 Implementing a Microsoft® SQL Server® 2008 R2 Database AFTER INSERT Triggers Key Points An INSERT trigger is a trigger that executes whenever an INSERT statement enters data into a table or a view on which the trigger is configured. new rows are added to both the base table and to the inserted virtual table.Opportunity are being audited to a table called Sales. Question: When would you use an INSERT trigger? .

sql script file from within Solution Explorer. In the Connect to Server window. 4. Open the 21 – Demonstration 2A. click Microsoft SQL Server 2008 R2. navigate to D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ.Responding to Data Manipulation via Triggers 15-15 Demonstration 2A: AFTER INSERT Triggers Key Points In this demonstration you will see how to: • • • Create an AFTER INSERT trigger Test the trigger action Drop the trigger Demonstration Steps 1. click Start. click Project/Solution. From the File menu. Follow the instructions contained within the comments of the script file. click SQL Server Management Studio. click Open. . Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. 3. Open and execute the 00 – Setup. 5. In the virtual machine. click All Programs.ssmssln and click Open.sql script file. 2. type Proseware in the Server name text box and click Connect.

Product table are being flagged as discontinued if the product category row they are associated with in the Product.Category table is deleted. rows are removed from the base table and added to the deleted virtual table. It does not fire any AFTER DELETE triggers associated with the table. rows in the Product. The trigger can examine the deleted virtual table to determine whether or how the trigger actions should be executed. AFTER DELETE Trigger Actions When an AFTER DELETE trigger fires. any AFTER DELETE triggers are fired when the deletion is completed. TRUNCATE TABLE When rows are deleted from a table using a DELETE statement. The action of the DELETE statement is completed before the trigger fires. The deleted virtual table holds a copy of the rows that have been deleted from the base table.15-16 Implementing a Microsoft® SQL Server® 2008 R2 Database AFTER DELETE Triggers Key Points A DELETE trigger is a trigger that executes whenever a DELETE statement deletes data from a table or view on which the trigger is configured. A common error when designing AFTER DELETE triggers is to write them with the assumption that only a single row is being deleted. Note that the trigger processes all deleted rows at once. Multi-Row Deletes In the example shown. It needs additional permissions above those required for deleting rows. Question: What performance and archival considerations should you think about when planning how to handle deleted records? . TRUNCATE TABLE is an administrative option that removes all rows from a table.

In the Connect to Server window. navigate to D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click All Programs. click Microsoft SQL Server 2008 R2. click Project/Solution. • 2. From the File menu. . Open and execute the 00 – Setup. click Open.sql script file from within Solution Explorer. click Start. type Proseware in the Server name text box and click Connect.Responding to Data Manipulation via Triggers 15-17 Demonstration 2B: AFTER DELETE Triggers Key Points In this demonstration you will see how to: • • • Create an AFTER DELETE trigger Test the trigger Drop the trigger Demonstration Steps 1. Follow the instructions contained within the comments of the script file. In the virtual machine. click SQL Server Management Studio. 3. Open the 22 – Demonstration 2B.sql script file.ssmssln and click Open.

Note that the trigger processes all updated rows at once. The trigger is being used to ensure that as changes are made to the Product.15-18 Implementing a Microsoft® SQL Server® 2008 R2 Database AFTER UPDATE Triggers Key Points An UPDATE trigger is a trigger that executes whenever an UPDATE statement modified data in a table or a view on which the trigger is configured. AFTER UPDATE Trigger Actions When an AFTER UPDATE trigger fires. Multi-Row Updates In the example shown. The inserted virtual table holds a copy of the rows in their modified state. The action of the UPDATE statement is completed before the trigger fires.ProductReview contains a column called ModifiedDate. the table Product. A common error when designing AFTER UPDATE triggers is to write them with the assumption that only a single row is being updated.ProductReview table that the value in this column always reflects when any changes last happened. The trigger can examine both the inserted and deleted virtual tables to determine whether and how the trigger actions should be executed. Rows that are to be modified in the base table are copied to the deleted virtual table and the updated versions of the rows are copied to the inserted virtual table. Question: When would you imagine you might use an UPDATE trigger in your own coding? . update actions are treated as a set of deletions of how the rows were and insertions of how the rows now are. the same as how the rows appear now in the base table.

click SQL Server Management Studio.sql script file from within Solution Explorer. In the Connect to Server window. Open the 23 – Demonstration 2C. navigate to D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ. click Start. click All Programs.triggers view Demonstration Steps 1. click Microsoft SQL Server 2008 R2. From the File menu. • 2. Follow the instructions contained within the comments of the script file. type Proseware in the Server name text box and click Connect.Responding to Data Manipulation via Triggers 15-19 Demonstration 2C: AFTER UPDATE Triggers Key Points In this demonstration you will see how to: • • • Create an AFTER UPDATE trigger Test the trigger Query the sys. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Open. Open and execute the 00 – Setup. 3. .ssmssln and click Open.sql script file. In the virtual machine. click Project/Solution.

It is also important to understand where to use triggers and where to consider alternatives to triggers. you will be able to: • • • • • • Implement INSTEAD OF DML triggers. Explain how nested triggers work and how configurations might affect their operation. Explain additional considerations for recursive triggers that is triggers that include actions that cause the same trigger to fire again. Objectives After completing this lesson. Explain the alternatives to using triggers. Describe the limited control that can be exerted over the order that triggers fire in when multiple triggers are defined for the same event on the same object. . Provide a brief introduction to this lesson in normal text.15-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Advanced Trigger Concepts In Lessons 1 and 2. There are additional areas of complexity related to triggers that also need to be understood to make effective use of them. A module must have at least two lessons. you have learned to design and implement DML AFTER triggers. Use the UPDATE function to build logic based on the columns being updated.

You cannot create an INSTEAD OF trigger on views that have the WITH CHECK OPTION defined. INSTEAD OF vs BEFORE Triggers Some other database engines provide BEFORE triggers. UPDATE. This trigger executes instead of the original triggering action. The original operation that caused the trigger to fire is not executed. INSTEAD OF triggers increase the variety of types of updates that you can perform against a view. INSTEAD OF triggers can be defined on views with one or more base tables. It is important to realize that with an INSTEAD OF trigger as implemented in SQL Server. or DELETE). Updatable Views A very common use case for INSTEAD OF triggers is to allow views that are based on multiple base tables to be updatable. SQL Server INSTEAD OF triggers are different from the BEFORE triggers that you may have come across in other database engines. Question: What sort of situations would lead you to need to execute different statements to the data modification statements requested? .Responding to Data Manipulation via Triggers 15-21 INSTEAD OF Triggers Key Points INSTEAD OF triggers cause the execution of alternate code instead of executing the statement that they were fired from. the action in the BEFORE trigger happens before the data modification statement which also occurs. where they can extend the types of updates a view can support. only the code in the trigger is executed. Each table or view is limited to one INSTEAD OF trigger for each triggering action (INSERT. In those databases. You can specify an INSTEAD OF trigger on both tables and views.

sql script file. 3. Open and execute the 00 – Setup.ssmssln and click Open. In the virtual machine. type Proseware in the Server name text box and click Connect. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Open the 31 – Demonstration 3A. click Open.15-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: INSTEAD OF Triggers Key Points In this demonstration you will see how to: • • Create an INSTEAD OF trigger Test the trigger Demonstration Steps 1. click SQL Server Management Studio. • 2. click Project/Solution. click Start. In the Connect to Server window. navigate to D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ.sql script file from within Solution Explorer. Follow the instructions contained within the comments of the script file. Question: Why does the DELETE succeed when INSERT and UPDATE fail? . click Microsoft SQL Server 2008 R2. From the File menu. click All Programs.

Nested triggers are essential for full auditing to occur. Otherwise. or DELETE statements. these actions are permitted via a configuration option at the server level. A failure at any level of a set of nested triggers cancels the entire original statement. and all data modifications are rolled back. actions would occur on tables without being audited. INSERT. By default. When these statements on one table cause triggers on another table to fire. Nested Triggers Triggers are often used for auditing purposes. Nested and recursive triggers are particularly difficult to debug. One common method that is used during debugging is to include PRINT statements within the trigger code bodies so that you can determine where a failure occurred. It is possible to control whether or not nested trigger actions are permitted. a trigger does not call itself in response to a second update to the same table within the trigger. Complexity of Debugging It was mentioned in an earlier lesson that debugging triggers can be difficult. Question: How might nested triggers work in an Employee database? . the triggers are considered to be nested. A nested trigger will not fire twice in the same trigger transaction.Responding to Data Manipulation via Triggers 15-23 How Nested Triggers Work Key Points Triggers can contain UPDATE.

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. and subsequently causes an update to occur on the original table. with an intermediate generation inserted)? . If a trigger modifies a table that causes another trigger to fire. an application updates table T1. Trig3 in turn updates table T2. which causes Trig2 to fire again. an application updates table T2. which causes trigger Trig3 to fire. For example. With the recursive trigger option enabled. 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. or DELETE statement that affects the same table or another table. causes the original trigger to fire again. Trig1 updates table T1 again.15-24 Implementing a Microsoft® SQL Server® 2008 R2 Database 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. turn off the nested triggers option. This. You can use the RECURSIVE_TRIGGERS database option to enable or disable direct recursion in triggers. For example. To prevent indirect recursion of this sort. INSERT. Trig2 updates table T3. which causes trigger Trig1 to fire again. Question: Think of a database containing genealogy data. in a recursive execution. the original trigger will fire recursively. Indirect Recursion Indirect recursion occurs when a trigger fires and performs an action that causes another trigger to fire (in the same or a different table). a trigger that changes data in a table can activate itself again. which causes trigger Trig1 to fire. Any trigger can contain an UPDATE. and the second trigger modifies the original table. then. which causes trigger Trig2 to fire.

Responding to Data Manipulation via Triggers 15-25 UPDATE Function Key Points It is a common requirement to build logic that only takes action if particular columns are being updated. This function returns a bitmap that indicates which columns are being updated. The UPDATE function allows detection of whether or not a particular column is being updated in the action of an UPDATE statement. For example. It only indicates if the column is part of the list of columns in the SET clause of the UPDATE statement. COLUMNS_UPDATED Function SQL Server also provides a function called COLUMNS_UPDATED. . you might wish to take a particular action only when the Size of a product changes. To detect if the value in a column is actually being changed to a different value. The column is referenced by the name of the column. The values in the bitmap depend upon the positional information for the columns. Change of Value Note that this function does not indicate if the value is actually changing. Hard-coding that sort of information in the code within a trigger is generally not considered good coding practice as it affects the readability (and hence the maintainability) of your code. the inserted and deleted virtual tables need to be interrogated. UPDATE Function The UPDATE function should not be confused with the UPDATE statement.

. For example. An error will occur if the First and Last triggers both refer to the same trigger. The value for the @stmttype parameter is INSERT. Only limited control is available over the firing order of these triggers. or DELETE for DML triggers. The value for the @order parameter is either First. a developer might create three AFTER INSERT triggers on the same table. code within one trigger should not depend upon the order of execution of other triggers. In general. each implementing different business rules or administrative tasks. sp_settriggerorder Developers often seek to control the firing order of multiple triggers defined for a single event on a single object.15-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Trigger Firing Order Key Points It is possible to assign multiple triggers to a single event on a single object. Limited control of firing order is available through the sp_settriggerorder system stored procedure. or None. UPDATE. Last. It allows you to specify which trigger fires first and which trigger fires last. None is the default action. from a set of triggers that all apply to the same event on the same object.

Defaults Triggers can be used to provide default values for columns when no values have been provided in INSERT statements. Computed Columns Triggers can be used to maintain the value in one column based on the value in other columns. In general. In general. In general. In general. FOREIGN KEY constraints should be used for this. CHECK constraints should be used for this instead of triggers as they are checked before the data modification is attempted. used in situations where other alternatives would be preferable. Checking Values Triggers could be used to check that values in columns are valid or within given ranges. Pre-calculating Aggregates Triggers can be used to maintain pre-calculated aggregates in one table. Foreign Keys Triggers can be used to check the relationship between tables. Triggers are often though. based on the values in rows in another table. in general table-level CHECK constraints should be created instead. DEFAULT constraints should generally be used for this instead.Responding to Data Manipulation via Triggers 15-27 Alternatives to Using Triggers Key Points Triggers allow for complex logic and are sometimes necessary. . indexed views should be used to provide this functionality. computed columns or persisted computed columns should be used for this. If the trigger is being used to check the correlation of values across multiple columns within the table.

replacing the triggers with these alternatives is not always possible. triggers can be used to ensure this sort of relationship. . As another example. While this typically indicates a poor database design. Consider a column that holds an employee number only if another column holds the value ‘E’. For example.15-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Constraint Use Is Not Always Possible While general guidelines are provided here. a FOREIGN KEY cannot be contained on a column that is also used for other purposes. the logic required when checking values might be too complex for a CHECK constraint.

Open the 32 – Demonstration 3B. • 2. click Project/Solution. click SQL Server Management Studio.sql script file.Responding to Data Manipulation via Triggers 15-29 Demonstration 3B: Replacing Triggers with Computed Columns Key Points In this demonstration you will see how a trigger could be replaced by a computed column. click Open. . navigate to D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ.ssmssln and click Open.sql script file from within Solution Explorer. If Demonstration 2A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. 3. In the Connect to Server window. In the virtual machine. Open and execute the 00 – Setup. click Microsoft SQL Server 2008 R2. click All Programs. Follow the instructions contained within the comments of the script file. Demonstration Steps 1. type Proseware in the Server name text box and click Connect. From the File menu. click Start.

point to Administrative Tools. Right-click 623XB-MIA-DC and click Connect. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-DC and click Start. 6. if the virtual machine 623XB-MIA-DC is not started: • • • 4. click Revert. Maximize the Hyper-V Manager window. click the Ctrl-Alt-Delete menu item. Before you begin the lab. In the Virtual Machines list. 7. In the Virtual Machine Connection window. click on the Revert toolbar icon. and then click Hyper-V Manager. In the Virtual Machine Connection window. Right-click 623XB-MIA-SQL and click Connect. and then close the Virtual Machine Connection window. you will use the available virtual machine environment. In the Virtual Machines list. In the Virtual Machine Connection window. 5. wait until the Press CTRL+ALT+DELETE to log on message appears. click Start. and then click Other User. wait until the Press CTRL+ALT+DELETE to log on message appears. If you are prompted to confirm that you want to revert. On the host computer.15-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 15: Responding to Data Manipulation via Triggers Lab Setup For this lab. 3. if the user is not already logged on: • • On the Action menu. 2. Wait for the revert action to complete. Click Switch User. . In Virtual Machine Connection window. you must complete the following steps: 1.

the data required in each column is as shown in the following table: Column CampaignAuditID AuditTime ModifyingUser RemainingBalance Data Type int datetime2 sysname decimal(18. and click Project/Solution.CampaignAudit table is used to hold audit entries. open the project D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ. check the Do not show me this console at logon check box and close the Server Manager window. click Execute on the toolbar. and click SQL Server Management Studio. click All Programs. 11.Responding to Data Manipulation via Triggers 15-31 • Log on using the following credentials: I. 14.sql. Lab Scenario You are required to audit any changes to data in a table that hold sensitive balance data. From the View menu. When the query window opens. In the Open Project window. click Microsoft SQL Server 2008 R2. If the Server Manager window appears. In the Authentication drop-down list box. double-click the query 00-Setup.ssmssln. You have decided to implement this via DML triggers as the requirements in this case are not provided for directly by the SQL Server Audit mechanism.` Supporting Documentation The Marketing. 12. click Open. In Connect to Server window. click Full Screen Mode. 10. In Solution Explorer. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. When inserting rows into this table. II. type Proseware in the Server name text box. In the virtual machine. 15. click Start. 9.2) Value to Insert IDENTITY SYSDATETIME() ORIGINAL_LOGIN() RemainingBalance after update . 13. in the Virtual Machine Connection window. In the File menu. select Windows Authentication and click Connect.

if either the existing balance or the new balance is greater than 10000. Note: Inserts or Deletes to the table do not need to be audited. 2. The main tasks for this exercise are as follows: 1. you should have created a new trigger.CampaignBalance table.  Task 2: Design a trigger to meet the requirements as stated in the scenario for this exercise • Design and create a trigger that meets the needs identified in Task 1. Design a trigger to meet the requirements as stated in the scenario for this exercise. Any time an update is made to the table.CampaignAudit table and the values required in each column. an entry needs to be written to the audit table Marketing.15-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Creating and Testing the Audit Trigger Scenario The Marketing.  Task 3: Write code to test the behavior of the trigger • Execute data modification statements designed to test that the trigger is working as expected. Review the supporting documentation and existing system.CampaignAudit. Tests should have shown that it is working as expected. based on the supporting documentation. Write code to test the behavior of the trigger. Results: After this exercise. Details of the current user can be taken from the function ORIGINAL_LOGIN().  Task 1: Review the supporting documentation and existing system • • Review the existing structure of the Marketing. 3.CampaignBalance table includes a column called RemainingBalance. Review the existing structure of the Marketing. .

CampaignAudit table • Execute a DELETE statement to remove all existing rows from the Marketing.CampaignAudit table. Use an ALTER TRIGGER statement to change the existing trigger so that it will meet the updated requirements. 2.CampaignAudit table. you should have altered the trigger. 3. Results: After this exercise. the operations team is complaining that too many entries are being audited. The main tasks for this exercise are as follows: 1.  Task 3: Test the modified trigger • Execute data modification statements designed to test that the trigger is working as expected.Responding to Data Manipulation via Triggers 15-33 Challenge Exercise 2: Improve the Audit Trigger (Only if time permits) Scenario Now that the trigger that was created in Exercise 1 has been deployed to production.  Task 2: Delete all rows from the Marketing. Modify the trigger based on the updated requirements. . Delete all rows from the Marketing. Test the modified trigger. Tests should show it is now working as expected. You need to modify the trigger so that only changes in the balance of more than 10000 are audited instead. Many accounts have more than 10000 as a balance and minor movements of money are causing audit entries.  Task 1: Modify the trigger based on the updated requirements • • Review the design of the existing trigger and decide what modifications need to be made to it.

and the IT staff can perform purges or archival of the deleted records. Best Practices 1. 3. 2. 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. How do constraints and triggers differ regarding timing of execution? Why would you use the UPDATE function rather than the COLUMNS_UPDATED function when designing a trigger? 2. Note that the numbers in the numbered list are not auto generated. Refer to the template instructions for further help. the data is not lost. List the module review questions here. You will need to enter the numbers manually.15-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. In many business scenarios. . Avoid using triggers in situations where constraints could be used instead.

Implementing Managed Code in SQL Server 2008 R2 16-1 Module 16 Implementing Managed Code in SQL Server 2008 R2 Contents: Lesson 1: Introduction to SQL CLR Integration Lesson 2: Importing and Configuring Assemblies Lesson 3: Implementing SQL CLR Integration Lab 16: Designing and Implementing Views 16-3 16-16 16-23 16-43 .

These objects can be developed using any . Import and configure assemblies.16-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview As a database professional. These requirements may include functionality such as: • • • Complex/compound data types like currency values that include culture information.NET Framework. there are times when the requirements go beyond the abilities of Transact-SQL.defined database objects that are managed by the . stored procedures. Implement objects that have been created within . you will learn about using CLR integrated code to create user. These requirements are examples of requirements that can be met using SQL Server CLR Integration. In this module. Objectives After completing this module. types. dates that include calendar system. you are asked to create databases and related objects to meet business needs.NET language and can be highly specialized. and triggers.NET assemblies. However. or storing entire arrays of values in a single column. Adding logic that verifies data such as available quantities within a database transaction and completing or rolling back the transaction based on specific criteria. aggregates. Accessing image files on the operating system and reading them or copying them into the database. . you will be able to: • • • Explain the importance of SQL Server CLR Integration. Most of the requirements can be met by using Transact-SQL. complex numbers. Integrated code is used to create user-defined functions.

Particular methods are more or less suited to particular needs and situations.NET Common Language Runtime environment. It is important to understand SQL Server CLR integration and its appropriate use cases. Objectives After completing this lesson. Explain the situations where T-SQL use is inappropriate. For example. SQL Server CLR Integration is one method for extending SQL Server. there is a constant desire to extend the built-in functionality of SQL Server. Explain the need for managed code in SQL Server. There is no right or wrong method to extend the product. Choose appropriate use cases for managed code in SQL Server. you will be able to: • • • • • • Explain the ways that SQL Server can be extended. Describe the .NET Framework.Implementing Managed Code in SQL Server 2008 R2 16-3 Lesson 1 Introduction to SQL CLR Integration Amongst database professionals. Describe the . . you might wish to add a new aggregate to the existing list of aggregates supplied by SQL Server.

16-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Options for Extending SQL Server Key Points Many SQL Server components have mechanisms that allow their functionality to be extended. The ability to create extended stored procedures is now deprecated. These are specially-crafted procedures that are written in C++ and are complex to code. they are executing directly within the process space of the SQL Server engine. It is then desirable to package that reusable functionality as an extension of the SQL Server product. . Many SQL Server components are extensible. That is not a safe place to be executing code as minor errors could cause failure or instability of the Database Engine itself. extending the Database Engine has been achieved by creating extended stored procedures. More concerning though is that when they are operating. The ability to reuse previously developed functionality though. Previous mechanisms for extending the Database Engine such as the use of extended stored procedures are limited in both effectiveness and safety. As an example. helps to produce higher quality outcomes. Managed code is a safer alternative. Component Extensibility Many applications can be created with the “out of the box” tools and functionality provided with SQL Server. SQL Server Reporting Services allows for the creation of: • • • • • • Rendering extensions Security extensions Data processing extensions Delivery extensions Custom code External assemblies Database Engine Extensibility Traditionally.

There seems to be a concern amongst database administrators about running managed code within the Database Engine but it is important to realize that even the most unsafe managed code that you write is always safer than any extended stored procedure code. Question: Are there any aspects of the Database Engine that you would like to extend? .Implementing Managed Code in SQL Server 2008 R2 16-5 Managed Code Managed code is code written to operate within the .NET Framework.

Win32 and Win64 APIs The Windows operating system evolved over a period of many years. largely due to their evolution over time rather than being designed with a single set of guidelines at one time.NET Framework Key Points The . It is not specific to any one programming language and also contains many thousands of prebuilt and pretested objects. This framework is written in a consistent fashion to a tightly-written set of design guidelines. The programming interfaces to the operating system are commonly referred to as the Win32 and Win64 Application Programming Interfaces (APIs). they are complex and inconsistent in the way they are designed. .NET Framework The . The . These objects are collectively referred to as the .NET Framework Class Libraries.NET framework is a layer of software that sits above the Win32 and Win64 APIs and abstracts away the underlying complexity.16-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Introduction to the .NET Framework is the foundation for developing Microsoft® Windows® applications and services including Microsoft SQL Server®. In general. Many people describe it as appearing to have been “written by one brain”.NET Framework offers the developer tools that make application and service development easier and provides a good basis for code to extend SQL Server. . These capabilities make the .NET Framework a good base for building code to extend SQL Server. These interfaces also evolved over the same period.

NET languages like Microsoft Visual C#® and Microsoft Visual Basic .NET language and deploy it for use. releasing memory when it was no longer needed was based on reference counting. It is important to distinguish the CLR from the Common Language Specification or CLS. The ability to create new resources using . . In older Component Object Model (COM) programming that was used with these APIs. .NET Framework that allows you to create programs and procedures in any . The idea was that the following sequence of events would occur: • • • • Object A creates Object B When Object B is created. The resulting resources are referred to as managed code.NET Common Language Runtime Key Points The . Memory Management A key problem that arose in development directly against the Win32 and Win64 APIs related to memory management.NET Common Language Runtime (CLR) is the layer in the . Object C might then acquire a reference to Object B as well. The .NET. Security features to ensure managed code will not compromise the server. Object B then notes that it has two references to itself. Object B then notes that it has only a single reference to itself.NET Common Language Runtime The CLR Integration feature within Microsoft® SQL Server® allows you to use .NET assemblies to customize your SQL databases. Object C releases its reference.Implementing Managed Code in SQL Server 2008 R2 16-7 .NET CLR offers: • • • Access to existing managed code. it notes that it has one reference to itself.

This then causes a leak (or loss) of the memory consumed by those objects. The . It specifies the rules that languages must conform to. and stability. these methods could not be called from another language that was not case sensitive. This allows SQL Server to exert great control over how the CLR operates. This sort of memory management scheme would not be suitable within the Database Engine. it provides details of what is called the signature of a function. As an example.NET Framework includes a sophisticated memory management system known as Garbage Collection that is designed to avoid any chance of such memory leaks. the CLR periodically checks which objects are "reachable" and disposes of the other objects. . it is as though the CLR thinks that SQL Server is the operating system. consider circular references. they can both sit in memory forever as long as they have a reference to each other. When a function or procedure is called. The caller assembles a list of any required parameters. all that is known to the caller is the address in memory of the function. For a simple example.16-8 Implementing a Microsoft® SQL Server® 2008 R2 Database • Object A then releases its reference as well. creation of such situations could cause the loss of all available memory on the system. Over time. Run Time Management Another common problem with Win32 and Win64 code relates to what is known as type safety. For example. The problem with this scheme is that it is easy to create situations where memory is lost. The CLS states that you should not create these two methods. Object B then notes that it now has no references to itself so it proceeds to destroy itself. Problems arise when the design of the function and/or its parameters change and the calling code is not updated. The function can then end up referring to memory locations that do not exist. so that interoperability between languages is possible. security. If two objects have references to each other but no other object has any reference to either of them. the CLS is the Common Language Specification. Hosting the CLR The CLR is also designed to be hostable. in terms of performance. With SQL Server CLR integration.NET CLR is designed to avoid such problems. Instead of objects needing to count references. even though it is possible to create a method in C# called SayHello and another method called Sayhello. The CLR will not allow a function to be called with the wrong number or types of parameters. CLS Many people get confused between the CLR and the CLS. SQL Server becomes the host for the CLR. The . places them in an area called the stack. As mentioned earlier. to avoid interoperability problems. and jumps to the memory address of the function. This specifies the data types of each of the parameters and the order that they need to be in. as well as providing details of the address of a function. This is referred to as "type safety". From the point of view of the CLR. This means that it can itself be operated within other programming environments.

The inclusion of managed code in SQL Server also allows for much easier access to external resources and in some cases provides higher performance. The .Implementing Managed Code in SQL Server 2008 R2 16-9 Why Use Managed Code in SQL Server? Key Points Managed code allows SQL Server to access thousands of available . Why Use Managed Code in SQL Server? In the last topic.NET libraries and assemblies created by third parties as well as those you develop.NET Framework is very powerful and can be utilized within SQL Server by the use of SQL Server CLR Integration. For efficient development though. Many objects can be created in either T-SQL or managed code but managed code also allows for the creation of new types of objects that cannot be created in T-SQL. the Regular Expression (RegEx) library in the .NET Framework offers a large set of libraries each of which contains a large set of prewritten (and pretested) objects (typically referred to as classes) that can easily be used directly in SQL Server via SQL Server CLR Integration. For example. the error handling provided by the T-SQL language still is well short of the type of error handling typically provided in higher-level languages. While advances in error handling in T-SQL have been made in recent years. A rich development environment (Visual Studio) is provided for building managed code. you also need to achieve a high degree of code reuse. the critical nature of type safety was discussed. Alternative to T-SQL Objects Many objects that can be created in T-SQL can also be created in managed code. Writing managed code allows advantage to be taken of these more extensive error handling capabilities. This includes the following set of objects: • • • Scalar user-defined functions Table-valued user-defined functions Stored procedures .

16-10 Implementing a Microsoft® SQL Server® 2008 R2 Database • • DML triggers DDL triggers New Object Types In managed code. you can also construct types of objects that cannot be constructed in T-SQL. These include the following set of objects: • • User-defined data types User-defined aggregates .

You cannot create a T-SQL schema within another T-SQL schema. Managed Code Key Points There is no right or wrong answer for all situations when considering if an object should be created in TSQL or in managed code. T-SQL T-SQL is the primary method for manipulating data within databases. particularly when working against very large sets of data. It is designed for direct data access and offers high performance.Implementing Managed Code in SQL Server 2008 R2 16-11 T-SQL vs. . the more likely it is that T-SQL will be the better answer. Managed code provides the ability to create a hierarchy of namespaces. you cannot create a stored procedure that takes a parameter of data type animal and pass a parameter of data type cat to it. Managed code works well in situations requiring intensive calculations (such as encryption) or string handling. T-SQL code does not support the object-oriented capabilities. SQL Server system objects almost all reside in a single sys schema. General Rules Two good general rules apply when making a choice between T-SQL and Managed Code: • The more data-oriented the need is. For example. a fully-fledged high-level programming language. though. T-SQL has no object-oriented capabilities. T-SQL is not. T-SQL is not designed for tasks such as intensive calculations or string handling and its objects are designed in a single flat namespace. It is important to realize though that this only applies within the managed code itself. T-SQL does offer a useful set of built-in functions. Managed Code Managed code provides full object-oriented capabilities.

string-oriented. or external-access-oriented the need is. . the more likely it is that managed code will be the better answer.16-12 Implementing a Microsoft® SQL Server® 2008 R2 Database • The more calculation.

environment variables. etc. about whether code that performs these tasks should be implemented within SQL Server at all. There are very few good use cases for managed code in stored procedures. however. Table-valued UDFs The more data-related these functions are. Managed code is often a good option for implementing scalar UDFs as long as the function does not depend on heavy data access. . DML Triggers Almost all DML triggers are heavily-oriented towards data access and are written in T-SQL.Implementing Managed Code in SQL Server 2008 R2 16-13 Appropriate Database Object use in Managed Code Key Points In the last topic. you saw some general rules for choosing between T-SQL and managed code. You need to consider how these rules would map to database objects in SQL Server. registry. A common use case for managed code in table-valued UDFs is for functions that need to access external resources such as the filesystem. It is important to again mention though that there is no right or wrong answer in all situations. Stored Procedures Stored procedures have traditionally been written in T-SQL. Scalar User-defined Functions (UDFs) Scalar UDFs written in T-SQL are well-known for causing performance problems in SQL Server environments. There are very few valid use cases for implementing DML triggers in managed code. There should be consideration. the more they are likely to be best implemented in T-SQL. The exceptions to this are stored procedures that need to access external resources or perform complex calculations. Most stored procedures should continue to be written in T-SQL.

. User-defined Data Types T-SQL offers the ability to create alias data types but these are not really new data types. The more that extensive XML processing is required. the more likely the DDL trigger would be best implemented in managed code. Managed code offers the ability to create entirely new data types and determine not only what data needs to be stored but also the behavior of the data type. Some DDL triggers though need to do extensive XML processing. These need to be implemented in managed code. They are more like subsets (or subclasses) of existing built-in data types. particularly based on the XML EVENTDATA structure passed to these triggers by SQL Server. Managed code would also be a better option if the DDL trigger needed to access external resources but this is rarely a good idea within any form of trigger.16-14 Implementing a Microsoft® SQL Server® 2008 R2 Database DDL Triggers DDL triggers are again often data-oriented. User-defined Aggregates T-SQL offers no concept of user-defined aggregates.

4. Open the 12 – Demonstration 1A Example 2. click All Programs.txt file. In the virtual machine. click Microsoft SQL Server 2008 R2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click SQL Server Management Studio. Question: Can you suggest ways that you could use T-SQL code that would be better as managed code? Question: Can you suggest ways that you could use managed code that would be better as T-SQL? .txt file.sql script file from within Solution Explorer.Implementing Managed Code in SQL Server 2008 R2 16-15 Demonstration 1A: Appropriate Use Cases for Managed Code and T-SQL Key Points In this demonstration you will see examples of code that is not ideally implemented in T-SQL.txt file. navigate to D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ. In the Connect to Server window.txt file. From the File menu. Open the 11 – Demonstration 1A Example 1. 3. 6. Open and execute the 00 – Setup. click Project/Solution. Open the 13 – Demonstration 1A Example 3. 2.ssmssln and click Open. type Proseware in the Server name text box and click Connect. 7. 5. click Open. Open the 14 – Demonstration 1A Example 4. Demonstration Steps 1. click Start.

Objectives After completing this lesson. Before you can start to work with managed code in SQL Server. .16-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Importing and Configuring Assemblies Assemblies are the unit of both deployment and security in the . Managed code in SQL Server resides within assemblies. Import an assembly. Detail the permission sets that are available for securing assemblies.NET Framework. you will be able to: • • • Explain what an assembly is. you need to learn about assemblies and how they can be imported into SQL Server and secured.

NET Framework. Deployment and Security Assemblies are the unit of managed code that is deployed.dll files and will refuse to import . and may contain resources. Managed code assemblies have a specific structure.dll files) contained only executable code. executable files (.dll files. are self-describing. SQL Server will only import . In the next topic. As well as executable code. Assemblies can contain other resources such as icons. they contain a manifest.Implementing Managed Code in SQL Server 2008 R2 16-17 What is an Assembly? Key Points Assemblies are the unit of both deployment and security in the . Assemblies also form a boundary at which security is applied. .exe files also include an area called the portable execution header (PE header) that is used by the operating system to find out where the executing code of a . SQL Server is able to gain a great deal of understanding of an assembly by reading this manifest when cataloging an assembly. The only difference between the two is that . They contain the code that will be executed. it is possible to share assemblies between SQL Server and business applications. As they are created external to SQL Server. Assemblies can be structured as either . Structure of an Assembly Prior to managed code.exe files or as .exe file starts. you will see how this security is configured. This manifest provides a list of contents of the assembly and of the programming interfaces provided by the assembly. This allows other code to interrogate an assembly to determine both what it contains and what it can do. Executable code is produced by compilers by converting instructions in higher-level languages into the binary codes required for execution by the computer’s processor. These are also listed in the manifest.exe files) and dynamic link libraries (.exe files. As an example.

EXTERNAL_ACCESS EXTERNAL_ACCESS is the permission set required before code in an assembly can access local and network resources. UNSAFE is required for code that calls external unmanaged code or code that holds state across function calls. EXTERNAL_ACCESS. There are three SQL Server permission sets that allow the administrator to control the server's exposure to security and integrity risks: SAFE. and the registry of the server. UNSAFE UNSAFE is the unrestricted permission set. Administrators should be fairly comfortable with the cataloging of EXTERNAL_ACCESS assemblies. SAFE SAFE should be regarded by administrators as really meaning what the name says. environment variables. Regardless of what the code in an assembly attempts to do. once a justification for the external access requirements is made. and UNSAFE.16-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Assembly Permission Sets Key Points Using the CLR offers several levels of trust that can be set within policies for the machine and host on which the assembly runs. It should be rarely used for general development. It is a particularly limited permission set but does allow access to the SQL Server database that it is cataloged in via a special type of connection known as a context connection. . Administrators should be comfortable with the cataloging of SAFE assemblies. Administrators should only allow the cataloging of UNSAFE assemblies in situations that have been very carefully considered and justified. SAFE is the default permission set. This permission set is still quite safe and is typically used when any form of external access is required. the permitted actions are determined by the permission set on the assembly that contains the code. etc.

and finally the login is granted the EXTERNAL ACCESS ASSEMBLY permission on the assembly. In general. An asymmetric key is created from the assembly file cataloged in the master database. A level of trust needs to be established.Implementing Managed Code in SQL Server 2008 R2 16-19 Setup for EXTERNAL_ACCESS and UNSAFE The EXTERNAL_ACCESS and UNSAFE permission sets require further configuration before they can be used. While this is the recommended method of granting permission to use EXTERNAL_ACCESS or UNSAFE permission sets. There are two ways to do this: • The database can be flagged as TRUSTWORTHY (via the ALTER DATABASE SET TRUSTWORTHY ON statement). this is not recommended without an understanding of what changes this makes to the database security environment. setting this up is an advanced topic beyond the scope of this course. then a login mapping to that key is created. • Question: Which permission set should be rarely allowed? .

SQL Server assigns the assembly a permission set based on the WITH PERMISSON_SET clause in the CREATE ASSEMBLY statement. the assembly must be cataloged within a database. You might be working with an . an assembly will be loaded from within the database when required. not from the filesystem. CREATE ASSEMBLY The CREATE ASSEMBLY statement is used to catalog an assembly within the current database. The drive may not be a mapped drive. A binary string containing the contents of the . the ‘clr enabled’ option must be set to 1 (enabled) at the database level. If no permission set is explicitly requested. An assembly and the objects within it can still be cataloged even if this option is disabled. After it is cataloged. the assembly will be cataloged as a SAFE assembly and the code within the assembly will only be able to execute tasks permitted by the SAFE permission set.dll file on a local drive. Before any code in a user-created assembly can be executed.dll file from a UNC path.dll file. It might at first seem odd to consider cataloging an assembly from a binary string but this is how Visual Studio catalogs assemblies if you deploy an assembly directly from Visual Studio. (A UNC path is of the form \\SERVER\Share\PathToFile\File. It only prevents code execution.16-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Importing an Assembly Key Points Before the code in an assembly can be used within SQL Server. Assembly Path There are three locations that an assembly can be cataloged from: • • • A . Once the assembly is cataloged in the database.dll). Visual Studio cannot make the assumption that you have access to the filesystem of the server. the contents of the assembly are contained within the database and the file that it was cataloged from is no longer needed by SQL Server. A .

Implementing Managed Code in SQL Server 2008 R2 16-21 instance of SQL Server or a database that is hosted by a hosting company and have no access to the filesystem of the server at all. Cataloging an assembly from a binary string allows you to stream an assembly to the server within the CREATE ASSEMBLY statement. . any contained assemblies will also be scripted as binary strings. It is worth noting that if you later generate a script for the database.

sql script file. click All Programs. What situations can you think of that would warrant the risk of using this trust level? Question: Is it wise to set a company policy to never use this level? (Why or why not?) . In the virtual machine. Question: Of the three trust levels. 3. navigate to D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ. click SQL Server Management Studio. click Open.ssmssln and click Open. Open the 21 – Demonstration 2A. Open and execute the 00 – Setup.sql script file from within Solution Explorer. In the Connect to Server window. click Project/Solution. • 2. click Start. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. the UNSAFE level is the least protected.16-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: Importing and Configuring an Assembly Key Points In this demonstration you will see: • • • How to catalog an assembly How to view system catalog information about loaded assemblies How to script an assembly Demonstration Steps 1. click Microsoft SQL Server 2008 R2. From the File menu. type Proseware in the Server name text box and click Connect. Follow the instructions contained within the comments of the script file.

there is a need to also catalog any objects within it. Implement scalar user-defined functions that have been written in managed code. Implement stored procedures that have been written in managed code and that require access to external resources. Objectives After completing this lesson. you will be able to: • • • • • • • • Explain how appropriate attribute usage is important when creating assemblies.Implementing Managed Code in SQL Server 2008 R2 16-23 Lesson 3 Implementing SQL CLR Integration Once an assembly has been cataloged. Implement user-defined data types that have been written in managed code. This will make the objects visible within SQL Server so that they can be called from within T-SQL code. Implement triggers that have been written in managed code. Implement user-defined aggregates that have been written in managed code. . Implement stored procedures that have been written in managed code. Implement table-valued user-defined functions that have been written in managed code.

you can still manually catalog the method as a function in SQL Server. and correctness reasons. You might wonder why SQL Server doesn’t just automatically catalog all methods as functions when cataloging an assembly. This is how SQL Server accesses the attributes that you associate with your code. If you do not add a SqlFunction attribute to a method. attributes are used for deployment. Attributes If you have not written any managed code. Deployment The first reason that attributes are helpful is for deployment. This does not change how the method operates but could be useful information for anyone using the method. Adding an attribute to a method is also referred to as “adorning” the method with the attribute. . The limitation is that automated deployment systems will not know to do so. and classes. performance. Attributes do not form a part of the logic of the objects but describe aspects of them.NET Framework also has a special set of logic called Reflection that allows one set of managed code to interrogate details of another set of managed code. Methods can be used for more than just functions and some methods are only used within the assembly and are not intended to be used by code that utilizes the functionality provided by the assembly.16-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Attribute Usage Key Points Attributes are metadata that is included within code and is used to describe that code. consider an attribute that records the name of the author of a method. Adding a SqlFunction attribute to a managed code method tells Visual Studio (or other code used for deployment) that the method should be cataloged as a function within SQL Server. Attributes are returned as part of this process. When implementing managed code within SQL Server. The . As an example. the concept of attributes may be unfamiliar to you. methods. Attributes are metadata (or data about data) used to describe functions.

This makes the function quicker to execute and reduces its memory requirements. In that case. As another example of how an attribute can help with performance. SQL Server knows it doesn’t need to call the method at all if the value is NULL. It would also prevent SQL Server from allowing the method to be called in a SELECT list or WHERE clause in a SELECT statement. SQL Server needs to know that if this method is called. This property tells SQL Server that no data context needs to be provided to this method. the internal state of the user-defined data type will be changed when the method returns. For example. SQL Server would then know that the method could be called in the SET clause of an UPDATE statement. it might provide a method called Shrink. This helps SQL Server know how the method can be used. It does not access data from the database.Implementing Managed Code in SQL Server 2008 R2 16-25 Performance The second reason why attributes are helpful relates to performance. . If a new Circle data type is created. Correctness The final reason for using attributes is for correctness. Consider the DataAccess property of the SqlFunction attribute as shown in the slide. consider an attribute that tells SQL Server that a method call always returns NULL if the parameter passed to the method is NULL.

you need to provide the details of the returned data type and a path to the method within the assembly. However. the UserDefinedFunctions class itself could be contained within another namespace. This normally consists of a three part name: • • The first part of the name refers to the alias for the assembly that was used in the CREATE ASSEMBLY statement The second part of the name must contain the namespace that contains the method. If that other namespace was called CompanyFunctions. EXTERNAL NAME When cataloging the function. In the statement.UserDefinedFunctions]. In the example shown.16-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Scalar User-defined Functions Key Points Scalar user-defined functions are a common use case for managed code and often offer a higherperforming alternative to their equivalent T-SQL functions. CREATE FUNCTION The CREATE FUNCTION statement is used to catalog a scalar user-defined function that has been written in managed code. The third part of the name refers to the method within the class. However. it is considered good practice to have these matched with each other to avoid confusion. the name UserDefinedFunctions is a class. • . the EXTERNAL NAME clause is used to point to where the method exists within the assembly. Note that the name that a function is called within SQL Server does not have to match the name that the method is called within the assembly. The auto-deployment attribute related to this is the SqlFunction attribute. the second part of the name would need to be specified as [CompanyFunctions.

Implementing Managed Code in SQL Server 2008 R2 16-27 Note that even if the code has been built in a case-insensitive language like Visual Basic and the database collation is set to case insensitive. the path provided in the EXTERNAL NAME clause is case sensitive. .

@EndValue int) RETURNS TABLE (PositionInList int. While it must be present. however. The properties of the attribute indicate: • • • That the function does not require access to database data. must be TABLE. CREATE FUNCTION The CREATE FUNCTION statement is also used to catalog TVFs written in managed code. you need to provide the definition of the schema of the table. In the example shown in the slide. both of integer data type. The name of the FillRow method (Do not be concerned with the FillRowMethodName method at this point. Parameter Naming The names chosen for the parameter in T-SQL do not need to match the names used in the managed code.RangeOfIntegers (@StartValue int. After the data type. it relates to the internal design of the function). IntegerValue int) . the table consists of two columns. For example. First. the SqlFunction attribute indicates that the method should be cataloged as a function. Deployment Attribute The definition of TVFs provides an example of why the properties of an attribute are useful. An automated deployment system (such as the one provided in Visual Studio) needs to know the format of the returned table to be able to automatically catalog this function in SQL Server. The return data type. The schema for the returned table. the function in the slide example could have been cataloged in the following way: CREATE FUNCTION dbo.16-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Table-valued User-defined Functions Key Points Table-valued functions (TVFs) are cataloged in a similar way to scalar functions but need to include the definition of the returned table.

Question: How could a TVF be used with environment variables? . you should create T-SQL parameters with the same name as the parameters in the managed code unless there is a compelling reason to make them different.Implementing Managed Code in SQL Server 2008 R2 16-29 AS EXTERNAL NAME SQLCLR6232B.RangeOfIntegers. Even in this situation.UserDefinedFunctions. However. a better option would be to change the parameter names in the managed code wherever possible. An example of this would be a parameter name that was used in managed code that was not a valid parameter name in T-SQL.

Open and execute the 00 – Setup. click All Programs. From the File menu.sql script file from within Solution Explorer. Open the 31 – Demonstration 3A.sql script file and execute steps 1 to 3. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Start. Open the 21 – Demonstration 2A. Use the table-valued function to find gaps in data. . Demonstration Steps 1. In the Connect to Server window. 3. Test the table-valued function. Test the scalar function. In the virtual machine. click Microsoft SQL Server 2008 R2. type Proseware in the Server name text box and click Connect. • • 2.16-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: User-defined Functions Key Points In this demonstration you will see how to: • • • • • Catalog a scalar function built in managed code. navigate to D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ. Follow the instructions contained within the comments of the script file. click SQL Server Management Studio. click Open.ssmssln and click Open. click Project/Solution. Catalog a table-valued function built in managed code.sql script file.

Like stored procedures written in T-SQL. Parameters that need to be passed to the stored procedure should be listed in the same way they are listed for a T-SQL stored procedure definition. The relevant deployment attribute is the SqlProcedure attribute. Most stored procedures written at present tend to be very data-access oriented. replacing a T-SQL stored procedure with a managed code stored procedure is unlikely to be useful. You will see the values returned in the Messages tab within SQL Server Management Studio. As such. The SqlPipe object is used within the stored procedure code to achieve this data. This attribute tells Visual Studio (or other deployment utility) that the method should be cataloged as a stored procedure. stored procedures written in managed code need a way to return rows of data. Rows of data can be returned by this object. CREATE PROCEDURE The CREATE PROCEDURE statement is used to catalog a stored procedure written in managed code. The EXTERNAL NAME clause works identically the same way as is used for cataloging scalar user-defined functions.Implementing Managed Code in SQL Server 2008 R2 16-31 Stored Procedures – T-SQL Replacement Key Points Stored procedures can also be written in managed code. You can see the SqlPipe object used in the following code: . SqlPipe Stored procedures written in managed code support both input and output parameters as per their T-SQL equivalent procedures. If you call the Send method of the SqlPipe object and pass a string value to it. the outcome is the same as if you had issued a PRINT statement in a T-SQL based stored procedure.

SqlCommand command = conn. } conn.16-32 Implementing a Microsoft® SQL Server® 2008 R2 Database public partial class StoredProcedures { [SqlProcedure] public static void ProductsByColor(SqlString Color) { SqlConnection conn = new SqlConnection("context connection=true"). } . SqlPipe outputPipe = SqlContext.Parameters. } else { command.CreateCommand().IsNull) { command.ExecuteReader()).CommandText = "SELECT * FROM Production.ToLongTimeString() + " at the server. outputPipe.Open().Send(command. Color.Product " + "WHERE (Color IS NULL) ORDER BY ProductID". outputPipe.Add( new SqlParameter("@Color".").Product " + "WHERE (Color = @Color) ORDER BY ProductID". command.Close().Pipe. }. It's now " + DateTime.Now.Send("Hello. if (Color.CommandText = "SELECT * FROM Production.Value)). conn.

This lets the applications perform operations at the filesystem level. EXTERNAL_ACCESS Permission Set A stored procedure that accepts data to be written to an operating system file would be a more useful example of implementing stored procedures in managed code. Access to the filesystem requires EXTERNAL_ACCESS permission when the assembly that contains the method is cataloged. you learned how simple it is to replace T-SQL stored procedures that perform data access with stored procedures written in managed code. yet many applications require it to be enabled. xp_cmdshell is an example of an extended stored procedure that is disabled by default in SQL Server.Implementing Managed Code in SQL Server 2008 R2 16-33 Stored Procedures – External Access Key Points In the previous topic. Avoid the Need for Many Extended Stored Procedures The use of managed code in stored procedures also removes the need for the use of many extended stored procedures. Question: What would be a good use case for stored procedures in managed code? . This is because the appropriate use cases for stored procedures written in managed code are more likely to involve access to external resources. The stored procedure would create the file and write the data to it. Enabling xp_cmdshell is undesirable from a security perspective and managed code provides alternate ways to implement this required functionality in a much safer form. You also learned how unlikely it is for stored procedure written in managed code to be useful.

16-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Triggers Key Points Both DML and DDL triggers can be implemented from within managed code. The relevant deployment attribute is SqlTrigger. access is provided to the inserted and deleted virtual tables in exactly the same way as in DML triggers written in T-SQL. Similarly. triggers written in managed code are able to access the details of the changes being made or the commands that have been executed. . within DDL triggers access is provided to the XML EVENTDATA structure. CREATE TRIGGER The CREATE TRIGGER statement is used to catalog methods in managed code assemblies as triggers. SqlTriggerContext A DML trigger can be associated with multiple events on an object. Within the code of a DML trigger. The SqlTriggerContext class can be used to build logic based on the event that caused the trigger to fire. Within DML triggers. you may need to know which event has caused the trigger to fire. The SqlTrigger attribute properties that are most useful are: • • • Name – this indicates the name that the trigger will be called when deployed Target – the name of the object that the trigger will be attached to Event – the event (or events) that the trigger will fire on Access to Modifications As with triggers written in T-SQL.

In the virtual machine. .ssmssln and click Open. click Microsoft SQL Server 2008 R2. click All Programs.sql script file and execute steps 1 to 3. click Project/Solution. 3.sql script file. Open the 32 – Demonstration 3B. Open the 21 – Demonstration 2A. click Open.Implementing Managed Code in SQL Server 2008 R2 16-35 Demonstration 3B: Stored Procedures and Triggers Key Points In this demonstration you will see how to: • • • • Catalog a stored procedure written in managed code Test the stored procedure Catalog a trigger written in managed code Test the trigger Demonstration Steps 1. navigate to D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ. Open and execute the 00 – Setup. In the Connect to Server window. • • 2. click SQL Server Management Studio. type Proseware in the Server name text box and click Connect. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.sql script file from within Solution Explorer. click Start. From the File menu. Follow the instructions contained within the comments of the script file.

Native shown in the slide example is indicating that the struct will be serialized using the standard serialization mechanisms built-in to the . The relevant deployment attribute is SqlUserDefinedAggregate. . Note that the path to a struct or class will be a two part name as shown in the EXTERNAL NAME clause on the slide. CREATE AGGREGATE The CREATE AGGREGATE statement is used to catalog UDAGGs written in managed code.NET Framework. you might decide that you need a MEDIAN aggregate but SQL Server does not supply one by default. Attribute Properties A few more useful attribute properties are shown in the example. In managed code. For example. including user-defined data types. as structs are easier to implement. the ability to save an object as a stream of data is called “serializing” the object. they can be implemented as either classes or structs (data structures). In managed code. Aggregates could also be created to operate on data types that are not supported by built-in aggregates. For more complex data types. The built-in serialization can only be used with simple data types. Another good use case for creating aggregates occurs when migrating code from another database engine that offers different aggregates or aggregates other than those provided by SQL Server. The property Format. user-defined serialization needs to be added.16-36 Implementing a Microsoft® SQL Server® 2008 R2 Database User-defined Aggregates Key Points User-defined aggregates (UDAGGs) are an entirely new type of object for SQL Server and cannot be created in T-SQL. Most UDAGGs would be implemented as structs rather than as classes. UDAGGs need to be Serializable. Serializable SQL Server needs to be able to store interim results while calculating the value of an aggregate. The ability to create aggregates allows you to provide additional aggregates that are not provided by the built-in set of aggregates.

Implementing Managed Code in SQL Server 2008 R2 16-37 • IsInvariantToDuplicates – this tells SQL Server that the result of the aggregate is the same even if it doesn’t see the values from every row. consider which rows the built-in MAX or MIN aggregates need to process and how this compares to which rows the built-in COUNT aggregate needs to see. just the most useful ones. IsInvariantToNulls – this tells SQL Server that the result of the aggregate is unaffected by seeing rows that do not have a value in the relevant column. IsNullIfEmpty – this tells SQL Server that if no rows at all need to be processed that the aggregate does not need to be called at all as the result will be NULL anyway. Question: Can you think of another common mathematical aggregate that would be useful in SQL Server? . Name – this tells Visual Studio (or the deployment utility) what name the aggregate should have when cataloged. To visualize this. It only needs to see unique values. • • • Note that this is not a complete list of all the possible properties.

but also how the data type behaves. Accessing Properties and Methods The properties of an instance of a managed code data type are accessed via: InstanceOfTheType. Userdefined data types allow for the determination not only what data is stored. System CLR Data Types The geometry. The deployment attribute is SqlUserDefinedType.16-38 Implementing a Microsoft® SQL Server® 2008 R2 Database User-defined Data Types Key Points The ability to create user-defined data types (UDDTs) in managed code allows you to extend the data type system available from within SQL Server. The methods of the managed code data type itself are accessed via: . Their operation is unrelated to the ‘clr enabled’ configuration setting at the SQL Server instance level.Property eg: @Shape. The 'clr enabled' option only applies to user-created managed code. and hierarchyid system data types are in fact system CLR data types. The data type will be defined as a class in a managed code assembly. Similar to user-defined aggregates.Method() eg: @Shape.STArea The methods of an instance of a managed code data type are accessed via: InstanceOfTyeType.STDistance(@OtherShape) Managed code data types might also include functionality that is useful without creating an object of the data type first. geography. CREATE TYPE The CREATE TYPE statement is used to catalog UDDTs. There is no T-SQL equivalent method of doing this. data types need to be Serializable as SQL Server needs to be able to store them. This allows you to expose functions from within a data type somewhat like a code library.

Implementing Managed Code in SQL Server 2008 R2 16-39 TypeName::Method() eg: GEOMETRY::STGeomFromText(‘POINT (12 15)’) .

For example. used in a SELECT DISTINCT clause. This means they cannot be sorted. the properties of the two data types can be compared as shown below: IF (@Shape1.16-40 Implementing a Microsoft® SQL Server® 2008 R2 Database Considerations for User-defined Data Types Key Points UDDTs are not directly comparable but their properties are. two geometry data types cannot be compared via code as shown below: IF (@Shape1 < @Shape2) BEGIN However. some system managed code data types have special indexes. or directly indexed. For example. User-defined data types cannot be compared using operations such as > (greater than) or < (less than). the geometry and geography data types can be indexed by a special type of index known as a spatial index. The individual properties of a data type are comparable. a variety of operations are defined for each data type. For example. Comparing Managed Code Data Types With the built-in set of system data types.X) BEGIN Indexing User-defined Data Type Properties While you cannot create indexes on user-defined data types.X < @Shape2. you can compare two integers or strings. . only a simple binary comparison is performed. The one exception to this is that binary comparisons are permitted when the IsByteOrdered property of the SqlUserDefinedDataType attribute is set to true. Even in this situation.

For example. User-defined data types do not offer this capability.Implementing Managed Code in SQL Server 2008 R2 16-41 For UDDTs. These columns can then be indexed. it is possible to define or change the operators that operate on the object. there is no method for creating new types of index to support them. a customized meaning for a > (greater than) operator cannot be defined. What you can do is create a persisted calculated column in the same table and use it to “promote” the properties of the UDDT into standard relational columns. Operator Overloading In object-oriented programming. .

If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.ssmssln and click Open. Follow the instructions contained within the comments of the script file. 3. click Open.sql script file and execute steps 1 to 3.sql script file. Open the 21 – Demonstration 2A.16-42 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3C: Aggregates and User. From the File menu. click Project/Solution. type Proseware in the Server name text box and click Connect. click SQL Server Management Studio. • • 2. In the virtual machine.defined Data Types Key Points In this demonstration. .sql script file from within Solution Explorer. Open the 33 – Demonstration 3C. you will see how to: • • • • • Catalog a user-defined aggregate Test a user-defined aggregate Catalog a user-defined data type Test a user-defined data type Create a table using a user-defined data type Demonstration Steps 1. Open and execute the 00 – Setup. click All Programs. In the Connect to Server window. click Microsoft SQL Server 2008 R2. click Start. navigate to D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ.

Right-click 623XB-MIA-DC and click Start. In the Virtual Machines list. Maximize the Hyper-V Manager window. 6. you will use the available virtual machine environment. If you are prompted to confirm that you want to revert. On the host computer. 5. click on the Revert toolbar icon. In the Virtual Machine Connection window. Wait for the revert action to complete. you must complete the following steps: 1. if the virtual machine 623XB-MIA-DC is not started: • • • 4. In the Virtual Machines list. . Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window. In the Virtual Machine Connection window. and then click Hyper-V Manager. 7. point to Administrative Tools. and then close the Virtual Machine Connection window. 2. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. click Start. wait until the Press CTRL+ALT+DELETE to log on message appears. In Virtual Machine Connection window. if the user is not already logged on: • • On the Action menu. Click Switch User. wait until the Press CTRL+ALT+DELETE to log on message appears. Right-click 623XB-MIA-DC and click Connect. click the Ctrl-Alt-Delete menu item. 3. and then click Other User. Before you begin the lab.Implementing Managed Code in SQL Server 2008 R2 16-43 Lab 16: Implementing Managed Code in SQL Server Lab Setup For this lab. click Revert.

10. 14.NET assembly.sql. If the Server Manager window appears. click Open. select Windows Authentication and click Connect. In the Authentication drop-down list box. click Microsoft SQL Server 2008 R2. in the Virtual Machine Connection window. ii. You will determine if this is appropriate. . Lab Scenario You are concerned that one of your company developers has decided to implement almost all of her logic in SQL CLR assemblies. Trigger that records balance movements with a value of more than 1000. 13. Proposed SQLCLR Functionality Table-valued function that returns a list of files in a particular folder. check the Do not show me this console at logon check box and close the Server Manager window. In the File menu. Function that counts rows in a table. In the Open Project window. From the View menu.ssmssln. type Proseware in the Server name text box. double-click the query 00-Setup. 11. click Full Screen Mode. and click Project/Solution. 15. and click SQL Server Management Studio. In the virtual machine. Supporting Documentation The following list details the proposed functionality being considered for managed code. 9. Also in this lab. you will implement and test a supplied . 12. A new Customer data type. When the query window opens.16-44 Implementing a Microsoft® SQL Server® 2008 R2 Database • Log on using the following credentials: i. In Connect to Server window. click Start. click Execute on the toolbar. open the project D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ. You will also investigate all installed assemblies on the system. click All Programs. Function that formats phone numbers as strings. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. In Solution Explorer. Stored procedure that writes an XML file for a given XML parameter.

decide if it should or should not be implemented in managed code and why. The main tasks for this exercise are as follows: 1. .Implementing Managed Code in SQL Server 2008 R2 16-45 Exercise 1: Assess Proposed CLR Code Scenario You need to assess a list of proposed functions and determine which functions should or should not be implemented via SQL CLR logic. Review the supporting documentation For each object listed. 2.  Task 1: Review the supporting documentation 1. determine if implementing it in managed code is appropriate or not. Work through the list of proposed objects and for each object. Review the proposed list of managed code objects  Task 2: For each object listed. you should have created a list of which objects should and should not be implemented in managed code and the reasons for your decision. determine if implementing it in managed code is appropriate or not 1. Results: After this exercise.

Use the CREATE FUNCTION statement to catalog the function dbo.FormatAustralianPhoneNumber.assemblies and sys. Use the CREATE FUNCTION statement to catalog the function dbo. Test the functions contained within the assembly. Use CREATE ASSEMBLY to catalog the supplied sample assembly as alias SQLCLRDemo.DLL. SELECT dbo.FolderList( 'D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ'. 2. GO SELECT * FROM dbo. It is found in the assembly at path: SQLCLRDemo. It is found in the assembly at path: SQLCLRDemo.NET assembly.  Task 1: Ensure the database is configured appropriately to support an EXTERNAL_ACCESS assembly 1.IsValidEmailAddress.IsValidEmailAddress('test@somewhere.FolderList. GO Results: After this exercise.IsValidEmailAddress('test. Ensure the database is configured appropriately to support an EXTERNAL_ACCESS assembly. Flag the MarketDev database as trustworthy. 3. Use the CREATE FUNCTION statement to catalog the function dbo.IsValidEmailAddress.FolderList.FormatAustralianPhoneNumber('039 87 2 41 23').FormatAustralianPhoneNumber('9 87 2 41 23'). 2. 5. It returns a table of filenames.FormatAustralianPhoneNumber('0419201410'). Query the sys. . 4.txt'). Ensure that SQL CLR integration is enabled for the SQL Server instance.somewhere.CLRDemoClass]. 2. SELECT dbo. you should have three functions working as expected. It takes a single parameter @PhoneNumber of type nvarchar(4000).com'). Execute the following T-SQL statements to test the functions that have been cataloged. It is found in the assembly at path: SQLCLRDemo.16-46 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 2: Implement a CLR Assembly Scenario You have been provided with an existing . GO SELECT dbo. The main tasks for this exercise are as follows: 1. It returns nvarchar(4000). It takes a parameter named @email of type nvarchar(4000) and returns a bit. GO SELECT dbo.[SQLCLRDemo. Catalog the assembly and the functions contained within it. You will implement it within SQL Server.FormatAustralianPhoneNumber. with one column called FileName of type nvarchar(4000). The path to the assembly is D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ\SQLCLRDemo. It takes two parameter @RequiredPath of type nvarchar(4000) and @FileMask of type nvarchar(4000). SELECT dbo.CLRDemoClass].  Task 3: Test the functions contained within the assembly 1.[SQLCLRDemo.[SQLCLRDemo.assembly_files system views to confirm the details of how the assembly has been cataloged. 3.'*.CLRDemoClass].  Task 2: Catalog the assembly and the functions contained within it 1.com').

2. 3. INSERT INTO dbo.CompressionPercentage()) FROM dbo. Execute T-SQL statements similar to the following to test the operation of the data type. dbo.TestTable ( RecID int IDENTITY(1. show how to call directly on the class so that you can see the difference). TextValue. 2.TestTable. You will now catalog and test these objects. rather than on an instance of the class.TestTable. TextValue zVarChar ). GO DROP TABLE dbo.CompressedValue().AggString takes a single nvarchar(4000) parameter and returns type nvarchar(4000). (The exact statements required would depend upon your table design).1). It is found in the assembly at path: SQLCLRDemo.CompressedLength(). GO compressible data'). 2.[SQLCLRDemo. show how to call the method on an instance.CompressionPercentage() FROM dbo.AggString].TestTable.zVarChar]. GO  Task 2: Catalog and test the user-defined data type 1.AggString. Then. It is found in the assembly at path: SQLCLRDemo.TestTable VALUES('Some GO SELECT TextValue. TextValue.zVarChar. SET @TestString = 'Some compressible PRINT @TestString. value'. (First. Catalog and test the user-defined aggregate Catalog and test the user-defined data type  Task 1: Catalog and test the user-defined aggregate 1. Use the CREATE TYPE statement to catalog the user-defined data type dbo. GO SELECT AVG(TextValue. Execute the following T-SQL statements to test the operation of the aggregate.ToString().AggString(DISTINCT ProductNumber) FROM Marketing. . Execute the following T-SQL statements to see how to call a method on the class itself. CREATE TABLE dbo. Use the CREATE AGGREGATE statement to catalog the user-defined aggregate dbo.Implementing Managed Code in SQL Server 2008 R2 16-47 Challenge Exercise 3: Implement a CLR User-defined Aggregate and CLR User-defined Data Type (Only if time permits) Scenario The sample assembly also includes a user-defined aggregate and a user-defined data type. SELECT dbo. The main tasks for this exercise are as follows: 1. 3. DECLARE @TestString zVarChar.Product WHERE Color = 'Black'.[SQLCLRDemo.

16-48 Implementing a Microsoft® SQL Server® 2008 R2 Database GO PRINT zVarChar::Compress( 'Some GO compressible value'). . you should have cataloged and tested both the user-defined aggregate and the user-defined data type. Results: After this exercise.

DBAs should set boundaries for developers: • No row-based code that should be set-based T-SQL operations • Limited use of EXTERNAL_ACCESS permissions and only after justification.Implementing Managed Code in SQL Server 2008 R2 16-49 Module Review and Takeaways Review Questions 1. . 3. 2. • Rare use of UNSAFE permissions and only after very serious justifications and testing. The biggest mistake made when deciding between T-SQL and Managed Code is to assume that either one is the correct answer for every situation. Which types of database objects can be implemented using managed code? What purpose do attributes have in CLR managed code? 2. As you have seen in this module. Developers should avoid implementing using SQL CLR to implement code that would be better placed on another application tier (such as on a client system). 4. DBAs should avoid refusing to allow SQL CLR code without consideration. List the module review questions here. You will need to enter the numbers manually. there is code that should be implemented in Managed Code rather than in T-SQL. Each has benefits and limitations and should be used for the appropriate tasks. Refer to the template instructions for further help. Note that the numbers in the numbered list are not auto generated. Best Practices 1. 3.

16-50 Implementing a Microsoft® SQL Server® 2008 R2 Database .

Storing XML Data in SQL Server 2008 R2 17-1 Module 17 Storing XML Data in SQL Server 2008 R2 Contents: Lesson 1: Introduction to XML and XML Schemas Lesson 2: Storing XML Data and Schemas in SQL Server Lesson 3: Implementing the XML Data Type Lab 17: Storing XML Data in SQL Server 17-3 17-15 17-26 17-31 .

It has become a very widely adopted standard for representing data structures rather than sending unstructured documents. you will be able to: • • • Describe XML and XML schemas Store XML data and associated XML schemas in SQL Server Implement the XML data type within SQL Server . SQL Server servers often need to use XML to interchange data with other systems and many SQL Server tools provide an XML based interface. Objectives After completing this module. including by queries written in a language called XQuery. The next module will show how XML data can be queried. This module introduces XML and shows how XML data can be stored within SQL Server. SQL Server has extensive handling of XML both for storage and for querying.17-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Extensible Markup Language (XML) provides rules for encoding documents in a machine-readable form.

Objectives After completing this lesson. It is important to gain an understanding of the appropriate uses for XML when working with SQL Server. One common problem with the use of XML in SQL Server is a tendency to over-use it. you will be able to: • • • • • Describe why XML matters in relation to SQL Server Explain core XML concepts Explain the difference between documents and fragments Describe the role of XML namespaces Describe the role of XML schemas Determine appropriate use cases for XML data storage in SQL Server • .Storing XML Data in SQL Server 2008 R2 17-3 Lesson 1 Introduction to XML and XML Schemas Before covering how to work with XML in SQL Server. Some core XML-related terminology needs to be understood along with concepts of how the structure of XML can be validated and enforced using schemas. it is important to gain an understanding of XML itself and how it is used external to SQL Server.

DDL triggers return details of the event that caused the trigger to fire via an XML data structure called EVENTDATA. Event notifications are used to send details of DDL events via a Service Broker queue. XML has often been seen more as an application developer topic. Extended events is a high-performance tracing capability that returns its trace data in XML format. . This means that even database administrators will benefit from a level of understanding of how to work with XML in SQL Server. It is also common to wish to provide XML-based output from SQL Server. Logon triggers return details through an EVENTDATA structure similar to the one provided by DDL triggers. Most data that travels on Service Brokers queues is XML based. These notifications are XML based. It is common for data arriving into SQL Server to already be in an XML format. Service Broker is a transaction based queuing system that is contained within a database. including: • • • • • • SQL Server can store XML data and XML schemas and can validate XML data against an XML schema. Question: Why do you imagine that two modules of this course have been dedicated to XML within SQL Server? XML is very useful for data interchange and for storing data with an arbitrary or complex structure. Many aspects and components of SQL Server are now XML-based.17-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Discussion: XML Usage in SQL Server Discussion The use of XML within SQL Server is new to many database administrators and database developers. if they wish to progress to more advanced usage of the product.

Consider the following XML document. It provides access to a wide range of technologies for manipulating.0" encoding="iso-8859-1" ?> <?xml-stylesheet href="orders. It follows the same basic structure rules as other markup languages (such as HTML) and is used as a self-describing language.xsl"?> <order id="ord123456"> <customer id="cust0921"> <first-name>Dare</first-name> <last-name>Obasanjo</last-name> <address> <street>One Microsoft Way</street> <city>Redmond</city> <state>WA</state> <zip>98052</zip> </address> </customer> </order> Question: With no knowledge apart from the document above. Data Interchange XML came to prominence as a format for interchanging data between systems. what would you imagine it contains details of? . structuring. transforming and querying data. language or operating system. Unicode-based meta-language (a language used to describe language). It can be used to hold both structured and semi-structured data and isn't tied to any particular vendor.Storing XML Data in SQL Server 2008 R2 17-5 Core XML Concepts Key Points XML is a plain-text. which is the same as on the slide: <?xml version="1.

0" of the XML specification is being used along with a specific encoding of "iso-8859-1". The third line of the example is the "order" element. then a shortcut form of element is available.17-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Without any context and information. The following example shows element-centric XML: <Customer> <Name>Tailspin Toys</Name> <Rating>12</ Rating > </Customer> The following example shows the equivalent data in attribute-centric XML: <Customer Name="Tailspin Toys" Rating="12"> </Customer> Note that if all data for an element is contained in attributes. Attribute-centric vs. XML Specifics The two first lines in the example document that start with "?xml" are referred to as processing instructions. The first instruction in the example shows that version "1. This explains why XML is defined as a self-describing language. The order element also has an associated attribute named "id". this is described as "deriving a schema" from a document. The second instruction indicates the use of the extensible style sheet (XSL) "orders. you can determine that this document holds the details about an order. Element-centric XML There are two basic ways to encode data in XML. These instructions are not a part of the data but determine the details of encoding. the two XML elements below are equivalent: <Customer Name="Tailspin Toys" Rating="12"></Customer> <Customer Name="Tailspin Toys" Rating="12" /> Question: Do you use XML for exchanging data between your organization and another organization? . As an example. if displaying the document is necessary. the customer who placed the order along with the customer's name and address details.xsl" to format the document for display. Note: It is important to realize that elements in XML (as in most other markup languages) are casesensitive. Note that the document data starts with an opening order element and finishes with a closing order element shown as "</order>". In formal terminology.

consider the following: <order id="ord123456"> <customer id="cust0921" /> </order> <order id="ord123457"> <customer id="cust0925" /> </order> This text contains the details of multiple orders. the XML needs to have a single root element as shown in the following: <orders> <order id="ord123456"> <customer id="cust0921" /> </order> <order id="ord123457"> <customer id="cust0925" /> . Documents Key Points Well-formed XML has only one top-level element and element tags are correctly nested within each other. Fragments Consider the following XML document: <order id="ord123456"> <customer id="cust0921" /> </order> This provides the details for a single order and would be considered to be a well-formed XML document. Now. While it is perfectly reasonable XML. To be called a document. it is considered to be a "fragment" of XML rather than a "document".Storing XML Data in SQL Server 2008 R2 17-7 Fragments vs. Documents with multiple top-level elements are considered fragments. Documents vs.

17-8 Implementing a Microsoft® SQL Server® 2008 R2 Database </order> </orders> Question: How could the XML fragment shown in the slide be converted to an XML document? .

this alias is called a "prefix" because of the way it is used within the remainder of the XML. In XML terminology. Any reference to the "id" element could easily be ambiguous. Many URIs used in namespaces only link to an address where a human-readable description of the namespace is found. Many other URIs do not lead to any real resources at all. Prefixes When declaring a namespace. The URI is simply used as a unique identifier for the namespace to reduce the possibility of duplicate entries. Both of these elements could have a child element called "id". The prefix is then used later to identify which namespace any element name is part of as shown below: .com/sqlserver/profiles/gml" Note that specifying an address in a namespace does not necessarily suggest that the URI provided could be used to retrieve the details in any particular format. an XML namespace attribute could be: xmlns="http://schemas. XML Namespaces An XML namespace is defined using the special attribute "xmlns" and the value of the attribute must be a valid Universal Resource Identifier (URI).microsoft. Imagine an XML instance that contains references to both a product and an order. As an example.Storing XML Data in SQL Server 2008 R2 17-9 XML Namespaces Key Points An XML namespace is a collection of names that can be used as element or attribute names. Namespaces are used to remove that ambiguity. an alias for the namespace is assigned. It is used to avoid conflicts with other names. You can see this in the snippet below from the example shown in the slide: xmlns="urn:AW_NS" xmlns:o="urn:AW_OrderNS" Two namespaces have been declared. The second namespace has been assigned the prefix "o".

Question: Why do you imagine that aliases are typically used with namespaces? .17-10 Implementing a Microsoft® SQL Server® 2008 R2 Database <o:Order SalesOrderID="43860" Status="5" OrderDate="2001-08-01T00:00:00"> <o:OrderDetail ProductID="761" Quantity="2"/> <o:OrderDetail ProductID="770" Quantity="1"/> </o:Order> In this snippet. the Order and OrderDetail elements are identified as being part of the "urn:AW_OrderNS" namespace by being prefixed by "o".

XSD is also the default file extension used by most products when storing XML schemas in operating system files. . XML Schemas The Worldwide Web Consortium (W3C) defined XML schemas as a more capable replacement for earlier objects called Document Type Definitions (DTDs). and layout that should be permitted within an XML document. attributes. An XML schema defines: • • • • • • • • elements that can appear in a document attributes that can appear in a document which elements are child elements the order of child elements the number of child elements whether an element is empty or can include text data types for elements and attributes default and fixed values for elements and attributes XML schemas are often also referred to as XML Schema Definitions (XSDs).Storing XML Data in SQL Server 2008 R2 17-11 XML Schemas Key Points XML schemas are used to provide rules that determine the specific elements.

Objects Higher level programming languages that are used for constructing application programs often represent entities such as customers and orders as objects. It is important to understand that there is no generic right and wrong answer for where in this range of options that a table should be designed. all in a single table. etc. Compare this to how tables have been traditionally designed in relational databases.Object ( ObjectID uniqueidentifier PRIMARY KEY. XML vs. While there is no suggestion that this would make for a good database design. Consider the following table definition: CREATE TABLE dbo. there is a tendency towards the overuse of XML within the database. an object-persistence layer. that is. PersistedData xml ). orders. payments. note that this table design could be used to store all objects from an application: customers. Appropriate Use Cases There are a number of reasons for storing XML data within SQL Server. It is important to consider when it is and when it is not appropriate to use XML within SQL Server. .17-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Appropriate Usage of XML Data Storage in SQL Server Key Points Given how widely XML has come to be used in application development in higher application tiers. Many developers see SQL Server as a simple repository for objects. Question: What is the basic problem with using this table design as your entire database design? SQL Server provides the developer with a wide range of choices with a simple XML design at one end of the spectrum and fully normalized relational tables at the other end.

You may wish to create indexes on your XML data to make it faster to query. You may have very sparse data. It is common to have a mixture of structured and semi-structured data. You may need to have order within your data. Imagine a table with thousands of columns where only a few columns or a few rows ever tend to have any data in them. You may need to achieve a level of interoperability between your relational and XML data. A table might hold some standard relational columns but also hold some less structured data in XML columns. (Sparse column support in SQL Server provides another mechanism for dealing with this situation but it also uses XML in the form of XML column sets. query and modify the XML data in an efficient and transacted way. . Other systems that you are communicating with may be based on entirely different technologies and not represent data in the same way as your server. Imagine the need to join a customer table with a list of customer IDs that are being sent to you as XML. You may wish to share. Sparse columns are an advanced topic beyond the scope of this current course). XML documents can exhibit a predictable order. For example. Relational tables and views have no implicit order. You may need to use XML formats to achieve cross-domain applications and need to have maximum portability for your data. You may wish to have SQL Server validate that your XML data meets a particular XML schema before processing it. You may not know the structure of your data in advance. order detail lines might need to be retained in a specific order. such as an order being received electronically from a customer.Storing XML Data in SQL Server 2008 R2 17-13 • • • • • • • • You may be dealing with data that is already in XML.

Open the 11 – Demonstration 1A. click Start. Follow the instructions contained within the comments of the script file. 4. From the File menu. 2. 5. type Proseware in the Server name text box and click Connect. In the Connect to Server window. navigate to D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ. 3. click Microsoft SQL Server 2008 R2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.ssmssln and click Open.sql script file.17-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Introduction to XML and XML Schemas Key Points In this demonstration you will see how: • • • XML is structured Documents differ from fragments XML schemas are structured Demonstration Steps 1.sql script file from within Solution Explorer. click Project/Solution. Question: What would the likely problem be if NULL elements are simply omitted? . In the virtual machine. click All Programs. click Open. click SQL Server Management Studio. Open and execute the 00 – Setup.

This is the first step in learning how to process XML effectively within SQL Server. you will be able to: • • • • Use the XML data type Create XML schema collections Declare variables and database columns as either typed or untyped XML Choose whether XML fragments can be stored rather than entire XML documents . how to define schema collections that contain XML schemas. Objectives After completing this lesson. how to declare both typed and untyped variables and database columns and how to specify how well-formed the XML data needs to be before it can be stored. schemas and the surrounding terminology.Storing XML Data in SQL Server 2008 R2 17-15 Lesson 2 Storing XML Data and Schemas in SQL Server After coming to an understanding of XML. You need to see how the XML data type is used. you can now turn your attention to how XML data and schemas can be stored within SQL Server.

The first assignment would be successful and the second assignment would fail as the value being assigned is not well-formed XML. look at the following code block: DECLARE @Settings xml. parameters and database columns can be declared as xml data type. SQL Server also exposes a number of methods that can be used for querying or modifying the XML data. It does not store the XML in the same format (including whitespace) as the data was received in. SET @Settings = '<Customer Name="Terry"><Customer>'. It is an intrinsic data type. xml Data Type xml is a built-in data type for SQL Server. Variables.17-16 Implementing a Microsoft® SQL Server® 2008 R2 Database XML Data Type Key Points SQL Server 2005 introduced a native data type for storing XML data in SQL Server. It can be used for variables. which means that it is not implemented separately via managed code. by default any well-formed XML can be stored in it. For example. . Look at the assignments in the following code block: SET @Settings = '<Customer Name="Terry"></Customer>". parameters and columns in databases. Canonical Form It is important to realize that SQL Server stores XML data in an internal format that makes it easier for it to process the XML data when required. You can see a variable declared using xml data type in the following code declaration: DECLARE @Settings xml. Once you have declared a variable of xml data type.

Storing XML Data in SQL Server 2008 R2 17-17 SET @Settings = N'<Customer Name="Terry"></Customer>'. SELECT @Settings. It is referred to as having been returned in a "canonical" or logically-equivalent form. the result returned is as follows: Note that the output returned is logically equivalent to the input but the output is not in exactly the same format as the input. When executed. .

com/ sqlserver/2004/sqltypes/sqltypes.xsd" /> .microsoft. it has an XML SCHEMA COLLECTION object which is an object that holds a collection of XML schemas. XML Schemas While they are somewhat legible to humans. you do not need to be able to read (or worse write!) such schemas.com/sqlserver/2004/sqltypes" elementFormDefault="qualified"> <xsd:import namespace= "http://schemas. An example of an XML schema is shown on the following page: <xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:schema="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:xsd="http://www. or database column. SQL Server can also create XML schemas. then the XML to be stored in that location needs to conform to at least one of the schemas that is contained in the schema collection. Even simple schemas tend to have quite a level of complexity.microsoft. XML Schema Collections In the first lesson.17-18 Implementing a Microsoft® SQL Server® 2008 R2 Database XML Schema Collections Key Points While the xml data type will only store well-formed XML.com/sqlserver/2004/sqltypes" schemaLocation="http://schemas.microsoft. When you associate an XML SCHEMA COLLECTION with an XML variable. SQL Server does not have an XML schema as a database object. it is possible to further constrain the stored values by associating the data type with an XML schema collection. XML schemas are designed to be processed by computer systems. Fortunately. They are generally created by tools and utilities.w3.org/2001/XMLSchema" xmlns:sqltypes= "http://schemas. you learned how XML schemas can be used to constrain what can be stored in an XML document. You will see an example of this in a later lesson. parameter.

The data being validated must match at least one of the schemas within the collection.Storing XML Data in SQL Server 2008 R2 17-19 <xsd:element name="Production. . The details of the namespaces that are referenced by XML schema collections can be seen by querying the sys.Product"> <xsd:complexType> <xsd:attribute name="ProductID" type="sqltypes:int" use="required" /> <xsd:attribute name="Name" use="required"> <xsd:simpleType sqltypes:sqlTypeAlias= "[AdventureWorks2008R2].[dbo]..[Name]"> <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions= "IgnoreCase IgnoreKanaType IgnoreWidth"> <xsd:maxLength value="50" /> </xsd:restriction> </xsd:simpleType> </xsd:attribute> <xsd:attribute name="Size"> <xsd:simpleType> <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions= "IgnoreCase IgnoreKanaType IgnoreWidth"> <xsd:maxLength value="5" /> </xsd:restriction> </xsd:simpleType> </xsd:attribute> <xsd:attribute name="Color"> <xsd:simpleType> <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions= "IgnoreCase IgnoreKanaType IgnoreWidth"> <xsd:maxLength value="15" /> </xsd:restriction> </xsd:simpleType> </xsd:attribute> </xsd:complexType> </xsd:element> </xsd:schema> Creating an XML Schema Collection An XML schema collection holds one or more schemas.xml_schema_namespaces system view.0" ?> <xsd:schema . </xsd:schema>'. You create an XML schema collection with the CREATE XML SCHEMA COLLECTION syntax shown in the following code snippet: CREATE XML SCHEMA COLLECTION SettingsSchemaCollection AS N'<?xml version="1..xml_schema_collections system view. System Views The details of the existing XML schema collections can be seen by querying the sys.

xml_collection_id WHERE c. You can get an idea of how they are stored by querying the sys.17-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Like XML. XML schema collections are not stored in the format that you enter them.name = 'SettingsSchemaCollection'.xml_schema_components system view as shown in the following code: SELECT cp.* FROM sys.xml_schema_components cp JOIN sys.xml_collection_id = c. .xml_schema_collections c ON cp. They are stripped into an internal format.

validating the XML can involve substantial work. One reason is that you might not have a schema for the XML data. you can choose to allow any XML to be stored or you can choose to constrain the available values by associating the XML location with an XML schema collection. Any well-formed XML could be stored in the WindowSettings column up to the maximum size of a SQL Server XML object which is currently 2GB. For complex schemas. Untyped XML You may choose to allow any well-formed XML to be stored. Typed XML Key Points When storing XML data.Settings ( SessionID int PRIMARY KEY. WindowSettings xml (SettingsSchemaCollection) . Typed XML You may wish to have SQL Server validate your data against a schema. WindowSettings xml ).Settings ( SessionID int PRIMARY KEY. The following example shows a table being created with an untyped XML column: CREATE TABLE App. Another reason is that you might want to avoid the processing overhead involved in validating the XML against the XML schema collection.Storing XML Data in SQL Server 2008 R2 17-21 Untyped vs. You might want to take advantage of storage and query optimizations based on the type information or want to take advantage of this type information during the compilation of your queries. The following example shows the same table being created with a typed XML column: CREATE TABLE App.

In this case. Question: What types of errors could occur if the XML data you were querying did not follow the schema you were expecting? .17-22 Implementing a Microsoft® SQL Server® 2008 R2 Database ). a schema collection called SettingsSchemaCollection has been defined and SQL Server will not allow data to be stored in the WindowSettings column if it does not meet the requirements of at least one of the XML schemas in the SettingsSchemaCollection.

Settings ( SessionID int PRIMARY KEY. Note the addition of the CONTENT keyword. WindowSettings xml (CONTENT SettingsSchemaCollection) ). This is equivalent to defining the table by the following code as the keyword CONTENT is the default value for typed XML declarations: CREATE TABLE App. DOCUMENT The alternative to the default value of CONTENT is to specify the keyword DOCUMENT as shown in the following code: CREATE TABLE App. When CONTENT is specified.Settings ( SessionID int PRIMARY KEY. XML fragments and entire well-formed XML documents can be stored in the typed XML location.Storing XML Data in SQL Server 2008 R2 17-23 CONTENT vs. DOCUMENT Key Points While specifying typed XML. you can also specify whether entire XML documents must be provided or if XML fragments can be stored.Settings ( SessionID int PRIMARY KEY. CONTENT In the example used in the last topic. a table was defined by this code: CREATE TABLE App. WindowSettings xml (DOCUMENT SettingsSchemaCollection) . WindowSettings xml (SettingsSchemaCollection) ).

In this case. a column that is intended to store a customer order can then be presumed to actually hold a customer order and not some other type of XML document. . XML fragments would not be able to be stored in the WindowSettings column.17-24 Implementing a Microsoft® SQL Server® 2008 R2 Database ). Only wellformed XML documents could be stored. For example.

Question: What is the difference between an XML SCHEMA COLLECTION and an XML schema? . click Open. click Project/Solution. Differentiate between CONTENT and DOCUMENT. navigate to D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ. 3. In the Connect to Server window. click SQL Server Management Studio. In the virtual machine. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Microsoft SQL Server 2008 R2. Open the 21 – Demonstration 2A. click All Programs. type Proseware in the Server name text box and click Connect. Open and execute the 00 – Setup.ssmssln and click Open.Storing XML Data in SQL Server 2008 R2 17-25 Demonstration 2A: Typed vs. Untyped XML Key Points In this demonstration you will see how to: • • • Create an XML SCHEMA COLLECTION.sql script file. • 2. click Start. From the File menu. Use typed XML in a column of a table.sql script file from within Solution Explorer. Follow the instructions contained within the comments of the script file. Demonstration Steps 1.

There are four types of XML index: a primary index and three types of secondary index. These are critical for achieving high performance of XML based queries. It is important to know how each can be used to achieve the maximum performance gain for your queries. Objectives After completing this lesson.17-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Implementing XML Indexes The final core aspect related to storing XML data in SQL Server is the creation of indexes on the XML columns. you will be able to: • • Describe the need for XML indexes Explain how each of the four types of XML index can be used .

It is important to note that XML indexes can be quite large compared to the underlying XML data. You saw earlier how XML data is not directly stored in a text format in SQL Server. it is broken into a form of object tree that makes it easier to navigate in memory. it is not uncommon to see XML indexes that are larger than the underlying data. particularly if the XML data is large. XML indexes are used to improve the performance of XQuery-based queries. . A XML index is somewhat like a copy of an XML object tree that is saved into the database for rapid reuse. Rather than having to create these object trees as required for queries. This can be very slow. which is also a relatively slow process. (XQuery will be discussed in the next module) XML Indexes Many systems query XML data directly as text.Storing XML Data in SQL Server 2008 R2 17-27 What are XML Indexes? Key Points Indexes are used in SQL Server to improve the performance of queries. XML indexes can be defined. For ease of querying. While relational indexes are often much smaller than the tables they are built on.

Settings (WindowSettings).17-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of XML Indexes Key Points SQL Server supports four types of XML index: a primary XML index and up to three secondary XML types. These secondary indexes are each designed to speed up a particular type of query. Secondary XML Indexes Most of the querying benefit comes from primary XML indexes. the table must have a clustered primary key. you could create a primary XML index by executing the following code: CREATE PRIMARY XML INDEX PXML_Settings_WindowSettings ON App. There are three forms of query that they help with: PATH. VALUE and PROPERTY. It is typically used with the exist() XQuery method. When creating the secondary XML index. (XQuery is discussed in the next module). A secondary XML index can only be created once a primary XML index has been established. you need to reference the primary XML index: . Before a primary XML index can be created on a table. You will see the use of these queries in the next module. A PROPERTY index is used when retrieving multiple values via PATH expressions. SQL Server also allows for the creation of three types of secondary XML index. The tree has been formed from the structure of the XML. Primary XML Index The primary XML index basically provides a persisted object tree in an internal format. A PATH index helps decide if a particular path to an element or attribute is valid. is used to speed up access to elements and attributes within the XML and avoids the need to read the entire XML document for each and every query. however.Settings table that was used as an example earlier. Based on the App. A VALUE index helps obtaining the value of an element or attribute. Secondary XML indexes are used to speed up particular types of queries.

Storing XML Data in SQL Server 2008 R2 17-29 CREATE XML INDEX IXML_Settings_WindowSettings_Path ON App. secondary XML indexes can only be created using T-SQL commands. XML Tooling Support Note that primary XML indexes can be created in SQL Server Management Studio or via T-SQL commands. In SQL Server 2008 R2.Settings (WindowSettings) USING XML INDEX PXML_Settings_WindowSettings FOR PATH. Question: Why does SQL Server support multiple types of secondary XML index? .

3. From the File menu. • 2. click Open.17-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Implementing XML Indexes Key Points In this demonstration you will see how to: • • • • Create a primary XML index Create a secondary XML index Query the sys. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Start. In the Connect to Server window. navigate to D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ. click Microsoft SQL Server 2008 R2. Follow the instructions contained within the comments of the script file. click Project/Solution. Open and execute the 00 – Setup. In the virtual machine.sql script file from within Solution Explorer. Question: How does SQL Server enforce the requirement that a primary XML index must be created before a secondary XML index can be created? .xml_indexes system view Identify the requirement of a clustered primary key on the table by XML indexes Demonstration Steps 1.ssmssln and click Open. type Proseware in the Server name text box and click Connect. Open the 31 – Demonstration 3A.sql script file. click SQL Server Management Studio. click All Programs.

and then click Hyper-V Manager.Storing XML Data in SQL Server 2008 R2 17-31 Lab 17: Storing XML Data in SQL Server Lab Setup For this lab. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machines list. In Virtual Machine Connection window. and then close the Virtual Machine Connection window. 3. Click Switch User. 2. wait until the Press CTRL+ALT+DELETE to log on message appears. click on the Revert toolbar icon. you will use the available virtual machine environment. wait until the Press CTRL+ALT+DELETE to log on message appears. click the Ctrl-Alt-Delete menu item. In the Virtual Machine Connection window. and then click Other User. If you are prompted to confirm that you want to revert. click Revert. 5. In the Virtual Machine Connection window. click Start. Before you begin the lab. 7. Maximize the Hyper-V Manager window. point to Administrative Tools. In the Virtual Machine Connection window. you must complete the following steps: 1. 6. On the host computer. Right-click 623XB-MIA-DC and click Start. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. . if the virtual machine 623XB-MIA-DC is not started: • • • 4. Right-click 623XB-MIA-SQL and click Connect. Wait for the revert action to complete. if the user is not already logged on: • • On the Action menu. In the Virtual Machines list.

you will decide on appropriate usage of XML within the documented application. In the Authentication drop-down list box. open the project D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ. In Solution Explorer. click Open.ssmssln. type Proseware in the Server name text box. He is keen to use this mechanism extensively. 13. and click Project/Solution. 15. 10. Lab Scenario A new developer in your organization has discovered that SQL Server can store XML directly. II. 11. In the Open Project window. and click SQL Server Management Studio. In the virtual machine. In the File menu.17-32 Implementing a Microsoft® SQL Server® 2008 R2 Database • Log on using the following credentials: I. check the Do not show me this console at logon check box and close the Server Manager window. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. in the Virtual Machine Connection window. click Full Screen Mode. No members of your current team have experience working with XML data in SQL Server.sql. double-click the query 00-Setup. When the query window opens. click Execute on the toolbar. In Connect to Server window. 14. You need to learn how to process XML data within SQL Server and you have been provided with some sample queries to assist with this learning. Supporting Documentation Use Cases Use Cases Requirements Existing XML data that is stored but not processed Storing attributes for a customer Relational data that is being passed through a system but not processed within it Storing attributes that are nested (that is attributes stored within attributes) . click Start. From the View menu. 12. click All Programs. 9. You also have an upcoming project that will require the use of XML data within SQL Server. In this lab. select Windows Authentication and click Connect. click Microsoft SQL Server 2008 R2. If the Server Manager window appears.

Review the list of Use Cases Determine whether each is appropriate for XML storage  Task 1: Review the list of Use Cases • Review the list of use cases in the supporting documentation  Task 2: Determine whether each is appropriate for XML • Determine whether the use cases are suitable for XML storage Results: After this exercise. you have seen how to analyze requirements and determine on appropriate use cases for XML storage. . The main tasks for this exercise are as follows: 1.Storing XML Data in SQL Server 2008 R2 17-33 Exercise 1: Appropriate Usage of XML Data Storage in SQL Server Scenario In this exercise. 2. you will need to assess the list of use cases provided by your new developer and determine which are appropriate for XML storage in SQL Server and which are not.

and review the results  Task 1: Review and execute the queries. The main tasks for this exercise are as follows: 1. You have been provided with a set of sample XML queries to assist with this. . you have seen how XML data is stored in variables.17-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 2: Investigate the Storage of XML Data in Variables Scenario Before you can begin to work with XML data in your organization. you need to explore how XML data is stored in variables. Do this one query at a time for scripts 17.1 to 17. Review and execute the queries. Results: After this exercise. execute the queries and determine how the output results relate to the queries.9. and review the results • Review the queries. In this exercise. you will review the effect of executing these queries.

Results: After this exercise. execute the queries and note the output. you have seen how to create XML schema collections. You need to investigate how these schemas are used.Storing XML Data in SQL Server 2008 R2 17-35 Exercise 3: Investigate the use of XML Schema Collections Scenario For some of the XML processing that you will need to perform in your upcoming project. In this exercise. and review the results • Review the queries.10 and 17. XML schemas are stored in XML schema collections. The main tasks for this exercise are as follows: 1. you will need to validate XML data using XML schemas. Do this one query at a time for scripts 17. In SQL Server.11. Review and execute the queries. you will review the effect of executing these queries. You have been provided with a set of sample queries to assist with this. and review the results  Task 1: Review and execute the queries. .

execute the queries and note the results of the queries. Results: After this exercise. and review the results  Task 1: Review and execute the queries.20. You need to investigate how columns of XML data type are used. Review and execute the queries. you have seen how to create database columns based on the XML data type. you will review the effect of executing these queries.12 to 17. In this exercise. You have been provided with a set of sample queries to assist with this.17-36 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 4: Investigate the Creation of Database Columns Based on XML (Only if time permits) Scenario The final aspect of XML data storage in SQL Server that you will need to understand for your upcoming project is how XML data is stored in tables. . Do this one query at a time for scripts 17. The main tasks for this exercise are as follows: 1. and review the results • Review the queries.

Use XML schemas only when required. Use the appropriate type of index for the types of queries expected. Use appropriate data types for your database columns. Index XML data stored in database columns. 4. 3.Storing XML Data in SQL Server 2008 R2 17-37 Module Review and Takeaways Review Questions 1. 2. 3. 2. What is XML? How are NULL elements represented in an XML document? What is the difference between an element and an attribute? Best Practices 1. Ensure you have at least basic XML proficiency when working with SQL Server. . Validating data against schemas incurs substantial processing overhead. even if you will be working primarily in database administration. Do not store all your data in XML columns.

17-38 Implementing a Microsoft® SQL Server® 2008 R2 Database .

Querying XML Data in SQL Server 18-1 Module 18 Querying XML Data in SQL Server Contents: Lesson 1: Using the T-SQL FOR XML Statement Lesson 2: Getting Started with XQuery Lesson 3: Shredding XML Lab 18: Querying XML Data in SQL Server 18-3 18-15 18-25 18-34 .

18-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview In the previous module. You now need to see how to query the XML data. and shredding XML data into a relational format. querying data that is already XML. To effectively process XML. you will be able to: • • • Use the T-SQL FOR XML Statement Work with basic XQuery queries Shred XML to a relational form . it is important to be able to query XML data in several ways: returning existing relational data as XML. you saw how SQL Server can be used to store XML based data and how you can index XML database columns to increase the performance of queries. The ability to query XML data directly avoids the need to shred it to a relational format before executing SQL queries. Objectives After completing this module.

Querying XML Data in SQL Server

18-3

Lesson 1

Using the T-SQL FOR XML Statement

There is a common requirement to return data that is stored in relational database columns as XML documents. Typically this requirement relates to the need to exchange data with other systems, including those from other organizations. When the FOR XML clause is added to a T-SQL SELECT statement, it causes the output to be returned as XML instead of as a relational recordset. SQL Server provides a number of modes for the FOR XML clause to allow the production of many styles of XML document.

Objectives
After completing this lesson, you will be able to: • • • • • • Explain the role of the FOR XML clause Use RAW Mode Queries Use Auto Mode Queries Use Explicit Mode Queries Use Path Mode Queries Retrieve Nested XML

18-4

Implementing a Microsoft® SQL Server® 2008 R2 Database

Introducing the FOR XML clause

Key Points
The FOR XML clause is used to extend the T-SQL SELECT statement syntax and causes the statement to return XML instead of rows and columns. It can be configured to return the attributes, elements, and/or schema that are required for client applications.

FOR XML
The FOR XML clause works in one of four modes: • • RAW mode generates a single <row> element per row in the rowset that is returned by the SELECT statement. AUTO mode generates nesting in the resulting XML based on the way the SELECT statement is specified. You have minimal control over the shape of the XML generated. If you need to produce nested XML, AUTO mode is a better choice than RAW mode. EXPLICIT mode allows more control over the shape of the XML. It can be used when other modes do not provide enough flexibility but does so at the cost of greater complexity. You can mix attributes and elements at will in deciding the shape of the XML. PATH mode together with the nested FOR XML query capability provides much of the flexibility of the EXPLICIT mode in a simpler manner.

Question: Why would sending XML data to a supplier be more useful than sending text files with fixed width columns?

Querying XML Data in SQL Server

18-5

Using RAW Mode Queries

Key Points
RAW mode is the simplest mode to work with in the FOR XML clause. It returns a simple XML representation of the rowset and can optionally specify a row element name and a root element.

FOR XML RAW
Look at the following simple T-SQL query:
SELECT FirstName, LastName, PersonType FROM Person.Person ORDER BY FirstName, LastName;

When executed, it returns the following results:

Now, look at the modified statement after adding the FOR XML clause:
SELECT FirstName, LastName, PersonType FROM Person.Person ORDER BY FirstName, LastName FOR XML RAW;

18-6

Implementing a Microsoft® SQL Server® 2008 R2 Database

When executed, this returns the following:

Note that one XML element is returned for each row from the rowset, the element has a generic name of "row" and all columns are returned as attributes. In the example on the slide, you can see how to override the generic element name. In that example, the elements have been named "Order" instead. In addition, notice that the results have been returned as an XML fragment rather than an XML document. This is because there is no root element. Also, in the example on the slide, you can see how to automatically add a root element called "Orders".

Element-centric XML
You will notice that in the previous examples that the columns from the rowset have been returned as attributes. This is referred to as "attribute-centric" XML. You can modify this behavior to produce "element-centric" XML by adding the keyword ELEMENTS to the FOR XML clause. You can see this in the following query:
SELECT FirstName, LastName, PersonType FROM Person.Person ORDER BY FirstName, LastName FOR XML RAW, ELEMENTS;

When executed, this query returns the following output:

Note that each column has been returned as a sub-element of the row element.

Querying XML Data in SQL Server

18-7

Using Auto Mode Queries

Key Points
With AUTO mode, by default, each row in the result set is represented as an XML element named after the table (or alias) it was selected from. AUTO mode generates nesting in the resulting XML based on the way the SELECT statement is specified. You have minimal control over the shape of the XML generated. AUTO mode queries are more capable of dealing with nested XML.

FOR XML AUTO
AUTO mode queries are useful if you want to generate simple hierarchies but they provide limited control of the resultant XML. If you need more control over the resultant XML than is provided by AUTO mode queries, you will need to consider using PATH or EXPLICIT modes instead. Look at the following query (which is a modified version of the query that you saw in the last topic):
SELECT FirstName, LastName, PersonType FROM Person.Person ORDER BY FirstName, LastName FOR XML AUTO;

Each table in the FROM clause, from which at least one column is listed in the SELECT clause, is represented as an XML element. The columns listed in the SELECT clause are mapped to attributes or subelements, if the optional ELEMENTS option is specified in the FOR XML clause. You can see the output of this query below:

18-8

Implementing a Microsoft® SQL Server® 2008 R2 Database

Note how the name of the table is directly used as the element name. For this reason, it is common to provide an alias for the table as shown in the following code:
SELECT FirstName, LastName, PersonType FROM Person.Person AS Person ORDER BY FirstName, LastName FOR XML AUTO;

When executed, it provides the following output:

NULL Columns
Look at the following query:
SELECT ProductID, Name, Color FROM Production.Product AS Product ORDER BY ProductID FOR XML AUTO;

When executed, it produces the following output:

Note that a number of products do not have any color. In the resultant XML, NULL values are not returned as zero length strings, by default they are omitted from the results. While in general this is appropriate, it can cause a specific problem when an XML schema is being derived from an XML document. For example, if someone sent you an XML document with product details, if none of the products happened to have a color, you would assume that there was no color column.

XSINIL
To assist in situations where a schema needs to be derived from a document that contains nullable columns, SQL Server provides an additional option XSINIL that adds an element to the output to indicate that an element exists but that it is currently NULL. Look at the following code:
SELECT ProductID, Name, Color FROM Production.Product AS Product ORDER BY ProductID FOR XML AUTO, ELEMENTS XSINIL;

When executed, it returns the following results:

Querying XML Data in SQL Server

18-9

Note the difference between the rows that have no color and the rows that do have a color.

18-10

Implementing a Microsoft® SQL Server® 2008 R2 Database

Using Explicit Mode Queries

Key Points
EXPLICIT mode gives you the greatest control over the resulting XML but at the price of query complexity. Many common queries that required EXPLICIT mode in SQL Server 2000 can be implemented using PATH mode (which was introduced in SQL Server 2005 and will be explained later).

FOR XML EXPLICIT
EXPLICIT mode queries define XML fragments as a universal table, which consists of a column for each piece of data that you require, and two additional columns. The additional columns are used to define the metadata for the XML fragment. 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. Each row of data in the universal table represents an element in the resulting XML document. The power of EXPLICIT mode is to mix attributes and elements at will, create wrappers and nested complex properties, create space-separated values (for example, OrderID attribute may have a list of order ID values), and mixed contents. PATH mode, together with the nesting of FOR XML queries and the TYPE clause, gives enough power to replace most of the EXPLICIT mode queries in a simpler, more maintainable way. EXPLICIT mode is rarely needed now and is complicated to write queries for.

You can use FOR XML EXPLICIT mode queries to construct such XML from a rowset. Values starting with an @ symbol in XPath refer to attributes. and scalar value. The slide provides an example of an XML PATH query. These expressions indicate how the values are being mapped to XML. PATH mode.BusinessEntityID value has been returned as the EmpID attribute of the row element. more maintainable way. The next two columns listed in the example on the slide detail the path to the values. column names or column aliases are treated as XML Path Language (XPath) expressions. together with the ability to write nested FOR XML queries and the TYPE directive to return xml data type instances. This indicates that the p. such as the attribute. which is itself returned as a sub-element of the row element. FOR XML PATH PATH mode is a simpler way to introduce additional nesting for representing complex properties. (More detail on XPath will be provided later in this module). In PATH mode. but PATH mode provides a simpler alternative to the potentially time consuming EXPLICIT mode queries. You can see in the output that the e. and the name and hierarchy of the node that will be generated relative to the row element. Question: What does an @ symbol relate to in an XQuery? .BusinessEntityID is shown as "@EmpID". allows you to write queries with less complexity and gives enough power to replace most of the EXPLICIT mode queries in a simpler.FirstName path is shown as "EmpName/First". Each XPath expression is a relative XPath that provides the item type. Note that the path to e.Querying XML Data in SQL Server 18-11 Using Path Mode Queries Key Points PATH mode provides a simpler way to mix elements and attributes. the p. For example. element. It can be used in many situations as an easier way to write query than those using EXPLICIT mode.FirstName value should be output as an element named "First" that is a sub-element of an element named "EmpName".

18-12

Implementing a Microsoft® SQL Server® 2008 R2 Database

Retrieving Nested XML

Key Points
The TYPE keyword can be used to return FOR XML sub-queries as xml data type rather than as nvarchar data type.

TYPE Keyword
In the previous topics in this lesson, you have seen how FOR XML AUTO queries can return attribute or element centric XML. If this data is returned from a subquery, it needs to be returned as a specific data type. The FOR XML clause was introduced in SQL Server 2000. That version of SQL Server did not have an xml data type. For that reason, sub-queries with FOR XML clauses had no way to return xml. FOR XML subqueries in SQL Server 2000 returned nvarchar data type instead. SQL Server 2005 introduced the xml data type but for backward compatibility, the data type for return values from FOR XML subqueries was not changed to xml. However, a new keyword TYPE was introduced that changes the return data type of FOR XML sub-queries to xml. For example, look at the following query:
SELECT Customer.CustomerID, Customer.TerritoryID, (SELECT SalesOrderID, [Status] FROM Sales.SalesOrderHeader AS soh WHERE Customer.CustomerID = soh.CustomerID FOR XML AUTO) as Orders FROM Sales.Customer as Customer WHERE EXISTS(SELECT 1 FROM Sales.SalesOrderHeader AS soh WHERE soh.CustomerID = Customer.CustomerID) ORDER BY Customer.CustomerID;

When executed in SQL Server Management Studio, this query returns:

Querying XML Data in SQL Server

18-13

Note that the Orders column is not hyperlinked. XML data type columns are hyperlinked in SQL Server Management Studio. Now look at the following modified query:
SELECT Customer.CustomerID, Customer.TerritoryID, (SELECT SalesOrderID, [Status] FROM Sales.SalesOrderHeader AS soh WHERE Customer.CustomerID = soh.CustomerID FOR XML AUTO, TYPE) as Orders FROM Sales.Customer as Customer WHERE EXISTS(SELECT 1 FROM Sales.SalesOrderHeader AS soh WHERE soh.CustomerID = Customer.CustomerID) ORDER BY Customer.CustomerID;

When executed in SQL Server Management Studio, this returns the following results:

Note that the Orders column now is hyperlinked like other xml data type columns. The example on the slide is a common use case where elements and attributes are mixed to define hierarchies in FOR XML. Question: Why is hyperlinking of XML columns in SSMS useful?

18-14

Implementing a Microsoft® SQL Server® 2008 R2 Database

Demonstration 1A: FOR XML Queries

Key Points
In this demonstration you will see: • • • • • How to retrieve XML in RAW mode How to retrieve XML in AUTO mode How to retrieve XML in EXPLICIT mode How to retrieve XML in PATH mode How to use TYPE

Demonstration Steps
1. 2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_18_PRJ\6232B_18_PRJ.ssmssln and click Open. Open and execute the 00 – Setup.sql script file from within Solution Explorer. Open the 11 – Demonstration 1A.sql script file. Follow the instructions contained within the comments of the script file.

3. 4. 5.

Question: When should you use EXPLICIT mode in an XQuery?

Querying XML Data in SQL Server

18-15

Lesson 2

Getting Started with XQuery

In Lesson 1, you learned how to query relational data and return it as XML. Sometimes, however, the data is already in XML and you may need to query it directly. You might want to extract part of the XML into another XML document; you might want to retrieve the value of an element or attribute; you might want to check if an element or attribute exists and finally you might want to directly modify the XML. These tasks are provided for by XQuery methods.

Objectives
After completing this lesson, you will be able to: • • • • • Explain the role of XQuery? Use the Query Method Use the Value Method Use the Exist Method Use the Modify Method

18-16

Implementing a Microsoft® SQL Server® 2008 R2 Database

What is XQuery?

Key Points
XQuery is a query language that is designed to query XML documents. It also includes elements of other programming languages such as looping constructs.

XQuery
XQuery was developed by a working group within the Worldwide Web Consortium (W3C). It was developed in conjunction with other work in the W3C, in particular the definition of Extensible Style Sheets (XSLT). XSLT makes use of a subset of XQuery known as XPath. XPath is the syntax used to provide an address for specific attributes and elements within an XML document. You saw basic examples of this when looking at FOR XML PATH mode queries in the last lesson. Look at the following XPath expression:
/InvoiceList/Invoice[@InvoiceNo=1000]

This specifies a need to traverse the InvoiceList node (that is the root element as the expression starts with a slash /), then to the Invoice sub-elements (note that there may be more than one of these) and then to access the InvoiceNo attribute. All invoices with invoice number 1000 are then returned. Note that while you may realize that there is unlikely to be more than one invoice with the number 1000, nothing about XML syntax (without a schema) enforces this. One thing that can be hard to get used to with the XPath syntax is that you constantly need to specify that you want the first entry of a particular type, even though logically you may think that it should be obvious that there would only be one. You indicate the first entry in a set by the expression [1]. In XPath, attributes are indicated by the @ prefix. The content of the element itself is referred to by the token text().

Querying XML Data in SQL Server

18-17

FLWOR Expressions
As well as basic path traversal, XPath supports an iterative expression language known as FLWOR and commonly pronounced as though it was spelled "flower". FLWOR stands for "for, let, where, order, and return" which are the basic operations in a FLWOR query. An example of a FLWOR expression is shown in the following XQuery query() method:
SELECT @xmlDoc.query('<OrderedItems> { for $i in /InvoiceList/Invoice/Items/Item return $i } </OrderedItems>');

This query outputs OrderedItems as an element and then within that element, it locates all items on all invoices contained in the XML document and outputs them as sub-elements of the OrderedItems element. Note that becoming proficient at XQuery is an advanced topic beyond the scope of this course. The aim of this lesson is to make you basically aware of what is possible when using XQuery methods. The available XQuery methods are shown in the following table: Method query() value() exist() modify() nodes() Function Returns selected XML data Retrieves a specific value from an element or attribute Checks for the existence of an element or attribute Performs insert, replace or delete operations Shreds XML data to relational format

The nodes() method will be covered in the next lesson that discusses shredding XML to relational data. Question: Why do you think it is important to learn XPath query language?

18-18

Implementing a Microsoft® SQL Server® 2008 R2 Database

query() Method

Key Points
The query() method is used to extract XML from an existing XML document. The output XML can be a subset of the original XML document or entirely new XML can be generated based on the values contained in the original XML document.

query() Method
The query() method is used to return untyped XML. It takes an XQuery expression that evaluates to a list of XML nodes and allows the users to create output XML based in some way on the fragments it extracts from the input XML. An XQuery expression in SQL Server consists of two sections – a prolog and a body. The prolog can contain a namespace declaration. You will see how to do this later in this module. The body of an XQuery expression contains query expressions that define the result of the query. It is important to understand that both the input and output of a query() method are XML. Note that if NULL is passed to a query() method, the result returned by the method is also NULL.

Example of query() Method
Look at the query shown in the slide:
SELECT XmlEvent.query( '<EventSPIDs> { for $e in /EVENT_INSTANCE return <SPID> {number($e/SPID[1])} </SPID> } </EventSPIDs>') FROM dbo.DatabaseLog;

Querying XML Data in SQL Server

18-19

This query tells SQL Server to return one xml value for each row in the dbo.DatabaseLog table. The xml value returned for each row will have a root element called EventSPIDs. For each EVENT_INSTANCE node that is contained in the XmlEvent column within each row, a sub-element named SPID should be returned. The contents of that node will be the value of the first SPID sub-element of the EVENT_INSTANCE node returned as a number. You will see how this works in the following demonstration.

. It is only specified as the example is working with typed XML. The value of the XML node is returned cast to the specified SQL type. You will see more about namespaces later in this module. Do not be too concerned with the namespace declaration in the example shown in the slide. NULL will be returned. Note the use of the expression [1] to specify that the first of these is retrieved and returned as an integer with the alias Result. value() Method The purpose of the value() method shown in the slide example is to navigate to the ProductModelID attributes of the ProductDescription element. Example Output You can see the output from this query below: Note again that if NULL is passed to the value() method.18-20 Implementing a Microsoft® SQL Server® 2008 R2 Database value() Method Key Points The value() method is useful for extracting scalar values from XML documents as a relational value. This method takes an XQuery expression that identifies a single node and the desired SQL type to be returned.

The exist() method is most helpful when used in a SQL WHERE clause and utilizes XML indexes more effectively than the value() method. exist() Method 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. A database log has been used to hold details of all schema changes made to a database. Example Output The output from the example code in the slide is shown below: This is a good example of the power of XML methods when used by database administrators. Question: Why would the exist() method outperform the value() method? . The result of this method is: • • • 1 if the XQuery expression returns a nonempty result 0 if the result is empty. use the exist() method on the XML data type. The example query asks SQL Server to return the rows where the type of object affected was a table. You will notice in the output that all events listed are table-related. and NULL if the XML instance itself is NULL For better performance.Querying XML Data in SQL Server 18-21 exist() Method Key Points Use the exist() method to check for the existence of a specified value. instead of the value() method. whenever possible.

and updated using the "insert". . The modify() method modifies the contents of an XML document. and "replace value of" keywords. Note that unlike the previous methods. or delete nodes from the XML data. respectively. update. an error is returned if NULL is passed to the modify() method. a new SalesPerson node with the text() of Bill is inserted into the first position of the first invoice in the list of invoices. modify() Method You can use the modify() method to alter the content of an xml type variable or column.18-22 Implementing a Microsoft® SQL Server® 2008 R2 Database modify() Method Key Points Data manipulation operations can be performed on an XML instance using the modify() method. This method takes an XML data manipulation language (DML) statement to insert. The modify() method of the xml data type can only be used in the SET clause of an UPDATE statement. Supported Actions The modify() method supports these keywords: • • • Insert adds child nodes to an XML document Replace updates a node in an XML document Delete removes a node from the XML document Slide Example In the insert example shown in the slide. One or more nodes can be inserted. deleted. "delete".

the SalesPerson's name is replaced by Ted. In the delete example shown in the slide. . the SalesPerson sub-element would be removed from the InvoiceList/Invoice path.Querying XML Data in SQL Server 18-23 In the replace example shown in the slide.

Demonstration Steps 1. 3. Open and execute the 00 – Setup.ssmssln and click Open.18-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: XQuery Methods in a DDL Trigger Key Points In this demonstration you will see how to use XQuery in DDL triggers. click SQL Server Management Studio. From the File menu. click All Programs. click Start. click Microsoft SQL Server 2008 R2. . click Project/Solution. Open the 21 – Demonstration 2A. navigate to D:\6232B_Labs\6232B_18_PRJ\6232B_18_PRJ.sql script file. Question: Suggest an example of where the ability to create triggers on DDL statements would be useful. In the Connect to Server window. click Open. In the virtual machine. Follow the instructions contained within the comments of the script file. type Proseware in the Server name text box and click Connect. • 2. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.sql script file from within Solution Explorer.

The extraction of relational data from within XML documents is referred to as "shredding" the XML documents. For example. you might receive a purchase order from a customer in XML format. While that is still supported. Besides covering these in this module. you will be able to: • • • • • Describe how to shred XML data Use system stored procedures for creating and managing in-memory node trees extracted from XML documents Use the OPENXML function Work with XML namespaces Use the nodes() method . SQL Server 2000 supported the creation of an in-memory tree that could then be queried with an OPENXML function.Querying XML Data in SQL Server 18-25 Lesson 3 Shredding XML Another common need that can arise when working with XML data in SQL Server is to be able to extract relational data from within an XML document. There are two basic ways to do this. Objectives After completing this lesson. You need to parse the XML to retrieve the details of the items that you need to supply. you will also see how T-SQL provides a way of simplifying how namespaces are referred to in queries. SQL Server 2005 introduced the XQuery nodes() method which in many cases will be an easier way to shred XML data.

based on the input XML. This allows you to obtain relational data from within the XML document. The steps in this process will be explored in the following topics. An XML document is received from a client application. 3. 2. The system stored procedure sp_xml_preparedocument can be used to create an in-memory node tree from an XML document that will make querying the XML data faster. The relational data that has been extracted is normally combined with other relational data as part of standard T-SQL queries. Shredding XML The process for shredding XML is: 1. . 5. 4. an in-memory node tree gets created. By calling sp_xml_preparedocument.18-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Overview of Shredding XML data Key Points The first of the methods for shredding XML data that was mentioned was to query an in-memory tree that represents the XML. Calling sp_xml_removedocument removes the node tree from memory. The OPENXML table-valued function is then used to query the in-memory node tree and extra relational data.

parses the text by using the Microsoft XML Core Services (MSXML) parser (Msxmlsql. sp_xml_preparedocument reads the XML text provided as input. This means that on 32 bit systems. the node tree will not be able to be stored in AWE memory. This is done via the sp_xml_preparedocument system stored procedure. When the call returns. the node tree remained in memory until the session ended or until sp_xml_removedocument was called. In SQL Server 2000. sp_xml_preparedocument created a node tree that was session-scoped. creates an in-memory node tree from the XML (to make it easier to navigate). Before calling sp_xml_preparedocument. and provides the parsed document in a state ready for consumption. A common coding error was to forget to call sp_xml_removedocument. comments. and so on. sp_xml_removedocument sp_xml_removedocument is a system stored procedure that frees the memory occupied by a node tree and invalidates the handle. sp_xml_preparedocument sp_xml_preparedocument is a system stored procedure that takes XML either as the xml data type or as xml stored in the nvarchar data type. text. This parsed document is a tree representation of the various nodes in the XML document: elements. It is important to realize that the node tree must stay available and unmoved in visible memory because the handle is basically a pointer that needs to remain valid. Allowing too many node trees to . you need to declare an integer variable to be passed as an output parameter to the procedure call.Querying XML Data in SQL Server 18-27 Stored Procedures for Managing In-Memory Node Trees Key Points Before you can use the OPENXML functionality to navigate over XML documents. the variable will then be holding a handle to the node-tree. and returns a handle to that node tree. you need to create an in-memory node tree.dll). that is. attributes.

a change was made in SQL Server 2005 that made the node trees created by sp_xml_preparedocument to become batch-scoped rather than session-scoped. Even though the tree will be removed at the end of the batch. Because of this. it is considered good practice to explicitly call sp_xml_removedocument to minimize the use of low-address memory as much as possible.18-28 Implementing a Microsoft® SQL Server® 2008 R2 Database remain in memory was known to cause severe lack of available low-address memory on 32-bit systems. . Note that 64-bit systems generally do not have the same memory limitations anyway.

a rowpattern. The ColPattern shown is an optional. For example. OPENXML provides a rowset view of the document. you might need to extract a list of products that you need to supply to a customer from an XML-based order that the customer sent to you. OPENXML allows access to the XML data as though it is a relational rowset. which is similar to a table or a view. . It does this by providing a rowset view of the internal representation of an XML document. If ColPattern is not specified. generic XPath pattern that describes how the XML nodes should be mapped to the columns. you can use OPENXML to write queries against the document.Querying XML Data in SQL Server 18-29 OPENXML Key Points OPENXML provides a rowset over in-memory XML documents. and an indication of whether or not to use attributes by default rather than elements. The parameters passed to OPENXML are the XML document handle. Associated with the OPENXML clause is a WITH clause that provides a mapping between the rowset columns and the XML nodes. which is an XPath expression that maps the nodes of XML data to rows. OPENXML After you have created an in-memory node tree of an XML document using sp_xml_preparedocument. the default mapping (attribute-centric or elementcentric mapping as specified by flags) takes place. based on the parameters passed to it.

In the example on the slide. you saw how an XML namespace is a collection of names that can be used as element or attribute names in an XML document. you can specify an optional parameter that specifies the namespaces used. You can then use the namespace prefixes in the XPath expressions used within OPENXML.18-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Working with XML Namespaces Key Points In the previous module. note how the alias "o" has been assigned to the XML namespace "urn:AW_OrderNS". The namespace qualifies names uniquely to avoid naming conflicts with other elements with the same name. if you are working with XML that contains embedded namespaces. That alias is then used throughout the document when an element that is defined in that namespace is used. Working with XML Namespaces When calling sp_xml_preparedocument. .

It is important to be careful about the query plans generated when using the nodes() method. For the XML instance stored in a column or a variable. This enables subsequent queries to navigate relative to these context nodes. This has the potential to lead to poor query plans. In these logical copies. nodes() Method The nodes() method is an XQuery method and is useful when you want to shred an xml data type instance into relational data. It is a table-valued function that allows you to identify nodes that will be mapped into a new row. The result of the nodes() method is a rowset that contains logical copies of the original XML instances.Querying XML Data in SQL Server 18-31 nodes() Method Key Points The nodes() method provides a much easier way to shred XML into relational data than OPENXML and its associated system stored procedures. the context node of every row instance is set to one of the nodes identified with the query expression. the cardinality is simply estimated to be a fixed value of 10. CROSS APPLY and Table-valued Function The nodes() method is a table-valued function that is normally called via the CROSS APPLY or OUTER APPLY operations.000 rows. APPLY operations cause table-valued functions to be called for each row in the left-hand table of the query. In some cases. no cardinality estimates are available when using this method. This might cause an inappropriate query plan to be generated if your XML document contained only a handful of nodes. In particular. The document node is the implicit node at the top of every xml data type instance. this is the document node. Every xml data type instance has an implicitly provided context node. Look at the query from the example in the slide: .

'sysname') AS ObjectName FROM dbo. 'int') AS SPID.'sysname') AS ObjectType. In this case.value('ObjectName[1]'. EventDetail. EventDetail.nodes('/EVENT_INSTANCE') AS EventInfo(EventDetail) ORDER BY PostTime.DatabaseLog table. In this query.value('ObjectType[1]'. a series of columns is generated by calling the value() method. When table-valued functions are used in queries like this. an alias must be provided for both the derived table and the columns it contains. When executed. the above query returns the following output: Question: When would it make sense to use OPENXML rather than the nodes() method for shredding XML data to relational format? .DatabaseLog table.XmlEvent.value('PostTime[1]'. Note that it is called four times for each output row in this example. the alias provided to the derived table is EventInfo and the alias provided to the extracted column is EventDetail.value('SPID[1]'. EventDetail.DatabaseLog AS dl CROSS APPLY dl. From the returned XML column (EventDetail). One output row is being returned for each node at the level of the XPath expression "/EVENT_INSTANCE".18-32 Implementing a Microsoft® SQL Server® 2008 R2 Database SELECT EventDetail. for every row in the dbo.'datetime2') AS PostTime. the nodes() method is called on the XmlEvent column from the dbo. Also note that the path to the value to be returned and the data type of that value are being specified along with output column aliases.

sql script file from within Solution Explorer. Open the 31 – Demonstration 3A. Follow the instructions contained within the comments of the script file. click All Programs. Open and execute the 00 – Setup. click Microsoft SQL Server 2008 R2.ssmssln and click Open. click SQL Server Management Studio. type Proseware in the Server name text box and click Connect. • 2. Demonstration Steps 1.sql script file. click Project/Solution.Querying XML Data in SQL Server 18-33 Demonstration 3A: Shredding XML Key Points In this demonstration you will see how to shred XML data using the nodes() method. In the virtual machine. navigate to D:\6232B_Labs\6232B_18_PRJ\6232B_18_PRJ. In the Connect to Server window. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. 3. From the File menu. click Start. click Open. .

Right-click 623XB-MIA-SQL and click Connect. wait until the Press CTRL+ALT+DELETE to log on message appears. In Virtual Machine Connection window. if the user is not already logged on: • • On the Action menu. Wait for the revert action to complete. wait until the Press CTRL+ALT+DELETE to log on message appears. click on the Revert toolbar icon. 3. If you are prompted to confirm that you want to revert. click Revert. On the host computer. In the Virtual Machine Connection window.18-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 18: Querying XML Data in SQL Server Lab Setup For this lab. Before you begin the lab. Right-click 623XB-MIA-DC and click Connect. and then click Other User. In the Virtual Machines list. 7. you must complete the following steps: 1. click Start. Right-click 623XB-MIA-DC and click Start. you will use the available virtual machine environment. click the Ctrl-Alt-Delete menu item. In the Virtual Machine Connection window. and then click Hyper-V Manager. Click Switch User. and then close the Virtual Machine Connection window. point to Administrative Tools. 6. In the Virtual Machines list. 2. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. . if the virtual machine 623XB-MIA-DC is not started: • • • 4. 5.

In the Authentication drop-down list box. your manager has an additional task for you. That is.sql.ssmssln. When the query window opens. 13. click Start. click Open. ListPrice. In Connect to Server window. Lab Scenario In this lab. you will investigate several ways in which XML data can be used in SQL Server. In the File menu. 10. If you have time. 12. Root element is AvailableModels. double-click the query 00-Setup. You will query relational data and return it as XML and also process existing XML data using T-SQL.ProductModel) for rows where there is a SellStartDate but not yet a SellEndDate. You need to create a stored procedure that will query data from a table and return it as an XML value. Rows within the XML should be in order of SellStartDate ascending and then ProductName ascending. 15. 14.Product) and ProductModelID and ProductModel (from Marketing. 11. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. From the View menu. Row element is AvailableModel. Color and SellStartDate (from Marketing. click All Programs. check the Do not show me this console at logon check box and close the Server Manager window. In Solution Explorer. ii. click Execute on the toolbar. In the Open Project window. in the Virtual Machine Connection window. and click Project/Solution. click Full Screen Mode. sort by SellStartDate first and then ProductName within SellStartDate. A new web service is being added to the marketing system. In the virtual machine. If the Server Manager window appears. and click SQL Server Management Studio. Output Order: . select Windows Authentication and click Connect. Supporting Documentation Stored Procedure Specifications Stored Procedure Input Parameters: Output Parameters: Returned Rows: WebStock.Querying XML Data in SQL Server 18-35 • Log on using the following credentials: i. Row contains ProductID. open the project D:\6232B_Labs\6232B_18_PRJ\6232B_18_PRJ.GetAvailableModelsAsXML None None One XML document with attribute-centric XML. type Proseware in the Server name text box. click Microsoft SQL Server 2008 R2. 9. ProductName.

Incoming XML object format: <SalespersonMods> <SalespersonMod SalespersonID="274"> <Mods> <Mod SalesTerritoryID="3"/> </Mods> </SalespersonMod> <SalespersonMod SalespersonID="278"> <Mods> <Mod SalesTerritoryID="4"/> </Mods> </SalespersonMod> </SalespersonMods> .UpdateSalesTerritoriesByXML @SalespersonMods xml None None Update the SalesTerritoryID column in the Marketing.Salesperson table based upon the SalesTerritoryID values extracted from the input parameter.18-36 Implementing a Microsoft® SQL Server® 2008 R2 Database Stored Procedure: Marketing.UpdateSalesTerritoriesByXML Stored Procedure Input Parameters: Output Parameters: Returned Rows: Actions: Marketing.

you have executed queries that return SQL Server relational data as XML. you have decided to learn to query SQL Server data to return XML. The main tasks for this exercise are as follows: 1.1 to 18. . execute the query and review the results for scripts 18.9 Results: After this exercise.Querying XML Data in SQL Server 18-37 Exercise 1: Learn to query SQL Server data as XML Scenario In this exercise. You will review and execute scripts that demonstrate the most important FOR XML querying techniques. Review and execute the query and review the results  Task 1: Review and execute the query and review the results • Review the query.

GetAvailableModelsAsXML  Task 2: Create the stored procedure • Create and implement the stored procedure based on the specifications provided  Task 3: Test the stored procedure • Test the stored procedure by executing the following code: EXEC WebStock. 2. You need to create a stored procedure that will query data from a table and return it as an XML value. The main tasks for this exercise are as follows: 1. you should have created and tested the required stored procedure that returns XML.18-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 2: Write a stored procedure returning XML Scenario In this exercise. 3. Review the requirements Create the stored procedure Test the stored procedure  Task 1: Review the requirements • Review the supporting documentation for details of the required stored procedure WebStock. .GetAvailableModelsAsXML. Results: After this exercise. a new web service is being added to the marketing system.

Salesperson. You need to construct a stored procedure Marketing.Salesperson table.UpdateSalesTerritoriesByXML  Task 2: Create the stored procedure • Create and implement the stored procedure based on the specifications given in the supporting documentation for the lab  Task 3: Test the stored procedure • Test the stored procedure by executing the following code: DECLARE @SalespersonMods xml. EXEC Marketing. 2.UpdateSalesTerritoriesByXML that can process this XML and use it to update the SalesTerritoryID column in the Marketing.UpdateSalesTerritoriesByXML @SalespersonMods. it sends an XML document containing the changes. 3. SET @SalespersonMods = '<SalespersonMods> <SalespersonMod SalespersonID="274"> <Mods> <Mod SalesTerritoryID="3"/> </Mods> </SalespersonMod> <SalespersonMod SalespersonID="278"> <Mods> <Mod SalesTerritoryID="4"/> </Mods> </SalespersonMod> </SalespersonMods>'. . The main tasks for this exercise are as follows: 1. you should have created and tested the required stored procedure that updates XML. Review the requirements Create the stored procedure Test the stored procedure and ensure the updates have been applied  Task 1: Review the requirements • Review the supporting documentation for details of the required stored procedure Marketing. the reassignment of salesperson territories is done by an external management system. When it completes reassignments. GO SELECT * FROM Marketing. GO Results: After this exercise.Querying XML Data in SQL Server 18-39 Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits) Scenario In this exercise.

2. Check the query plans for queries using the nodes() method to ensure that the lack of cardinality estimates is not producing a poor execution plan.18-40 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. 3. 2. Convert existing code that uses the nvarchar data type for XML parameters to use the XML data type. Provide meaningful row names when using RAW mode by using the optional name parameter to the RAW clause. What are AUTO mode queries? What are PATH mode queries? What does the nodes() method do? What are RAW mode queries? Best Practices 1. 4. . 3.

Working with SQL Server® 2008 R2 Spatial Data 19-1 Module 19 Working with SQL Server® 2008 R2 Spatial Data Contents: Lesson 1: Introduction to Spatial Data Lesson 2: Working with SQL Server Spatial Data Types Lesson 3: Using Spatial Data in Applications Lab 19: Working with SQL Server Spatial Data 19-3 19-13 19-27 19-38 .

which often makes results easier to interpret. This capability can help business make better decisions and can also be used to help visualize results. you will be able to: • • • Describe the importance of spatial data and the industry standards related to it Explain how to store spatial data in SQL Server Perform calculations on and query SQL Server spatial data . yet they rarely provide effective ways to process distances and proximity. Objectives After completing this module. and shapes.19-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Business applications routinely deal with addresses and locations. addresses. Spatial data in SQL Server allows for effective storage and processing of locations.

Working with SQL Server® 2008 R2 Spatial Data 19-3 Lesson 1 Introduction to Spatial Data Before starting to work with spatial data. it is important to gain an understanding of where it is typically used in applications. It is important to understand the difference between these two types of data as well as how the SQL Server data types relate to the relevant industry standards and measurement systems. Most business applications need to work with addresses or locations. along with an understanding of the different types of spatial data. you will be able to: • • • • • Explain how spatial data is useful in a wide variety of business applications Describe the different types of spatial data Describe the difference between planar and geodetic data types Explain the relationship between the SQL Server spatial data support and the industry standards Work with spatial reference identifiers to provide measurement systems . Objectives After completing this lesson. SQL Server can process both planar and geodetic data.

It could be true that customers really do purchase from their local store. They know where their stores are and they know where their customers live. If so. It could also be true that customers don't purchase from their local stores. Consider how many business applications you have seen that do not involve storing addresses or locations. The same is true for stores. Business Intelligence Applications A particularly strong use of spatial data comes when it is combined with Business Intelligence applications. and delivery addresses. Common Business Questions Consider a pet accessories supply company. Customers or clients have street addresses. The owner may have just come across a small sample of data and been misled by it. mailing addresses. The owner has a feeling though that the company's customers are not buying from their nearest store but the owner also has no firm facts to base this feeling on. and many other business-related entities. Business Applications While mapping provides an interesting visualization in some cases.19-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Target Applications Key Points There is a perception that spatial data is not useful in mainstream applications. Perhaps the local store doesn't hold a wide . Spatial capabilities make it possible to provide very rich forms of visualization. it might be interesting to know what they purchase when they travel to another store. offices. They have stores all over the country. This is an invalid perception as almost every business application can benefit from the use of spatial data. These applications often deal with results that are best visualized rather than being presented as tables of numbers. business applications can make good use of spatial data for much more routine tasks. suppliers.

Working with SQL Server® 2008 R2 Spatial Data 19-5 enough variety of stock. the customers purchase everything they need from a more remote store as they don't like the staff at the local store. This is the sort of problem you can solve quite easily if you are able to process spatial data in a database. Perhaps instead. not specialized mapping questions. It is important to realize though that these sorts of questions are normal business questions. .

This is because it would effectively be redrawn at each level of magnification. Vector storage is the method that SQL Server spatial data is based upon. if you then zoom in into an image of the line. several types of spatial data are used. 3D. A third dimension would represent the elevation of a point on the map. the line would still look complete. 2D. This is how raster-based storage works. This is how vector-based storage works. SQL Server spatial data is currently based on the 2D technology. You could divide the line into a series of dots that make up the line. In some of the objects and properties it provides. if the line was stored as the coordinates of the start and end points of the line. 4D You are likely familiar with seeing drawings or maps on paper that are two dimensional in nature. no matter how much you zoom in or out. SQL Server spatial data supports storing and retrieving of 3D values but it is important to realize that the third dimension is ignored during calculations. Alternately. along with the gaps between the dots. This means that if you calculate the distance between say a point and a building. 4D systems usually incorporate changes in a shape over time. the calculated distance is the same regardless of which floor or level in the building the point is located. Vector vs Raster Data Spatial data could be stored as either a series of line segments that together form an overall shape (vector storage) or as a series of dots or pixels that are formed by dividing a shape into smaller pieces (raster storage).19-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of Spatial Data Key Points In the spatial data community. . Imagine storing the details of a line. SQL Server works with vector-based 2D data but has some storage options for 3D values. However. the individual dots would then become visible. One key advantage of vector-based storage is the way that it can scale.

Working with SQL Server® 2008 R2 Spatial Data 19-7 Question: Which existing SQL Server data type could be used to store (but not directly process) raster data? .

particularly as you move from the center of the map. SQL Server spatial data offers a number of systems for representing the shape of the Earth. however. Most systems model the Earth as an ellipsoid rather than as a sphere. Geodetic Systems Geodetic systems represent the Earth in a round shape. As soon as larger distances are involved. mapping tended to be two dimensional in nature. they also were oriented around where the people drawing them lived. Geodetic systems represent the Earth more like its actual shape. That way. compare Antarctica’s size on the map and note that it is really only about 13 million square kilometers in size. it isn’t obvious how Africa’s area (about 30 million square kilometers) compares to North America’s area (about 24 million square kilometers). Most people are familiar with traditional flat maps of the world. the least distortion occurred where the people that were using the maps were based. For convenience. in the flat map shown. When most of the standard maps from atlases were first drawn. it was very difficult to perform calculations on round models of the Earth. Some systems use simple spheres but it is important to realize that the Earth is not actually spherical. Geodetic Key Points Planar systems represent the Earth as a flat surface. Also.19-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Planar vs. As an example. Planar Systems Prior to the advent of computer systems. Question: What is the difference between an ellipsoid and a sphere? . flat maps provide a significant distortion.

SQL Specification One of the two data types that SQL Server provides is the geometry data type. Extensions SQL Server also extends the standards in a number of ways. In the chart shown in the slide. It is likely that future versions of SQL Server will expand this coverage of OGC objects. along with a number of additional useful properties and methods.0 and is used for planar spatial data. . Methods and properties that are related to the OGC standard have been defined with an ST prefix (such as STDistance) and those without an ST prefix are Microsoft extensions to the standard (such as MakeValid). Other objects in the OGC Geometry hierarchy are shown in yellow (or the lighter color). the objects that are supported and can be created in SQL Server spatial data are shown in blue (or the darker color).Working with SQL Server® 2008 R2 Spatial Data 19-9 OGC Object Hierarchy Key Points The Open Geospatial Consortium (OGC) is the industry body that provides specifications for how spatial data processing should occur in SQL-based systems. The OGC defines a series of data types that form an object tree. It conforms to the OGC Simple Features for SQL Specification 1. A round-Earth data type called geography has also been provided. the specification details common properties and methods to be applied to the data. Besides defining how the data should be stored.

a starting point for measurement) at Greenwich. the entry for SRID 4326 has the following name (formally called the Well-known Text or WKT that is associated with the ID): GEOGCS["WGS 84". SQL Server supports many of these measurement systems directly. the unit of measure used. PRIMEM["Greenwich". UNIT["Degree". you also specify the measurement system to be used. 0]. GPS is often used in navigation systems and uses WGS 84 as its coordinate system. The latest standard is WGS 84 and is best known to most people via the Global Positioning System (GPS).19-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Spatial Reference Identifiers Key Points Many systems of measurement have existed over time. ELLIPSOID["WGS 84". 298. geodetics. and navigation. and a . a flattening of 1 / 298. SRID 4326 The World Geodetic System (WGS) is commonly used in cartography. You specify this by associating a spatial reference ID with the data. This is commonly used where there is no need for a specific measurement system. A spatial reference ID of zero indicates the lack of a measurement system. When you specify a spatial data type in SQL Server. with its major radius of 6378137 meters at the equator. the authority responsible for maintaining it. Each SRID defines the shape of the Earth model. WGS 84 support is provided by SRID 4326 in SQL Server spatial data.0174532925199433]] This specifies how WGS 84 models the Earth as an ellipsoid (you can imagine it as a squashed ellipsoid).257223563 (or about 21 kilometers) at the poles. Spatial Reference Systems Any model of the Earth is an approximation. SQL Server supports many different Earth models via a series of Spatial Reference Identifiers (SRIDs). a prime meridian (that is. DATUM["World Geodetic System 1984". some models closer to reality than others.257223563]]. 6378137. 0. and a multiplier that determines how the unit of measure could be converted to meters. If you query the list of SRIDs in SQL Server.

Most geographic data today would be represented by SRID 4326. The units are shown as degrees and the size of a degree is specified in the final value in the definition.Working with SQL Server® 2008 R2 Spatial Data 19-11 measurement based on degrees. Question: Do you currently use GPS data in any existing applications within your organization? . The starting point at Greenwich is specifically based at the Royal Observatory.

type Proseware in the Server name text box and click Connect.sql script file.sql script file from within Solution Explorer. click Project/Solution. In the Connect to Server window. click Microsoft SQL Server 2008 R2. 4. Open and execute the 00 – Setup. In the virtual machine.ssmssln and click Open.19-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Spatial Reference Systems Key Points In this demonstration you will see: • • The available spatial reference identifiers The available units of measurement Demonstration Steps 1. 5. click Open. Open the 11 – Demonstration 1A. navigate to D:\6232B_Labs\6232B_19_PRJ\6232B_19_PRJ. click All Programs. . 3. click Start. click SQL Server Management Studio. 2. Follow the instructions contained within the comments of the script file. From the File menu. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.

you will be able to: • • • • • • Describe the support provided by SQL Server spatial data Explain how system CLR types differ from user CLR types Use the geometry data type Use the geography data type Work with standard spatial data formats Use OGC methods and properties on spatial data Use Microsoft extensions to the OGC standard when working with spatial data • . which have been created as system CLR data types. It is important to know how to use each of these data types and how to interchange data using industry standard formats.Working with SQL Server® 2008 R2 Spatial Data 19-13 Lesson 2 Working with SQL Server Spatial Data Types SQL Server supports two spatial data types. Objectives After completing this lesson. geometry and geography.

The geometry data type is suited to flat Earth (planar) models. The map control is available for reports built using BIDS and for reports built using Report Builder. The geometry type is used when modeling flat Earth models such as two dimensional diagrams. It provides two data types. the geographical community uses the terminology in the reverse order. and the geography data type is suited for round Earth (geodetic) models. It supports the majority of the methods and properties of the OGC type plus extensions to the OGC type. the longitude value precedes the latitude value. Additional Support The Bing Maps software development kit (SDK) has been updated to work closely with SQL Server spatial data. The geography data type works with a Long and Lat (longitude and latitude) coordinate system.and Y-based coordinate system.19-14 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Spatial Data Key Points SQL Server supplies rich support for spatial data. geography Data Type The geography data type is a Microsoft extension to the OGC standards that is suitable when working with round Earth models such as GPS data. . SQL Server Reporting Services 2008 R2 includes a map control that can be used to render spatial data and a wizard to help to configure the map control. Note that although "latitude and longitude" is a commonly-used phrase in the general community. The geometry data type offers an X. When specifying inputs for geographic data in SQL Server. geometry Data Type The geometry data type is the SQL Server implementation of the OGC Geometry data type.

no prefix has been added to the name of the methods or properties. ST Prefix For the properties and methods that are implementations of the OGC standards. As an example. Question: You may have used a web service to calculate the coordinates of an address. For Microsoft extensions to the OGC standards. even on servers that are configured for case insensitivity.Working with SQL Server® 2008 R2 Spatial Data 19-15 An application that stores or retrieves spatial data from a SQL Server database needs to be able to work with that data as a spatial data type. For example. there is a MakeValid method. the X and Y coordinates of a geometry object are provided by STX and STY properties and the Distance calculation is provided by the STDistance method.NET managed code. This file is installed on client systems and allows an application on the client to "rehydrate" a geography object that has been read from a SQL Server database into a SqlGeography object within . a separate installer file (MSI) has been provided as part of the SQL Server 2008 R2 Feature Pack to allow client applications to also make use of the SQL Server spatial data types. To make this possible. The installer is called the "Microsoft® System CLR Types for SQL Server® 2008 R2". Care must also be taken when referring to properties and methods as they are case sensitive. What is this process commonly called? . an ST prefix has been added to the names of the properties and methods.

System CLR Types SQL Server 2005 introduced the concept of a CLR user-defined data type. Unlike user-defined CLR data types.assemblies. and hierarchyid. permission_set_desc. separate from the user-defined data types but also implemented in managed code. User SQL CLR Types Key Points The geometry and geography data types have been implemented as CLR types using managed code. This increased limit makes it possible to create complex data types using managed code. They are defined as system CLR types and work even when CLR integration is not enabled at the SQL Server instance level. for data types implemented in managed code. . geography. They needed to be capable of being serialized into 8 KB of storage (they needed to fit in one SQL Server data page). In SQL Server 2008 R2. SQL Server 2008 also replaced the 8 KB limit on serialization with a 2 GB limit. You can see the currently installed assemblies and whether or not they are user-defined by executing the following query: SELECT name.19-16 Implementing a Microsoft® SQL Server® 2008 R2 Database System vs. assembly_id. SQL Server 2008 introduced the concept of a system CLR data type. is_user_defined FROM sys. there are three system CLR data types that take advantage of this large data type support: geometry. these system data types operate even when the 'clr enabled' setting for the server instance is disabled. CLR data types in SQL Server 2005 were limited in size.

0).MakeValid(). In . look at the following code that is accessing the STX property of a variable called @Location: SELECT @Location. this would be referred to as calling a public static method on the geometry class. Note also that the methods and properties of the spatial data types are case-sensitive.Method(). .NET terminology. It is also possible to call methods that are defined on the data types (geometry and geography) rather than on instances (that is. This is an important distinction. You can access a method of an instance of a spatial data type by referring to it as Instance.Working with SQL Server® 2008 R2 Spatial Data 19-17 Accessing Properties and Methods You can access a property of an instance of a spatial data type by referring to it as Instance. As an example of this. As an example of this. columns or variables) of those types. even on servers configured with case-insensitive default collations. look at the following code that is calling the MakeValid method of a variable called @InputLocation: SELECT @Location = @InputLocation. look at the following code that is calling the GeomFromText method of the geometry data type: SELECT @Location = geometry::STGeomFromText('POINT (12 15)'. Note that you are not calling the method on a column or variable of type geometry but on the geometry type itself.Property.STX. As an example of this.

The geometry data type allows the Z and M values to be entered and retrieved but it ignores these values when performing calculations. SELECT @Location = geometry::STGeomFromText('POINT (12 15 2 9)'.19-18 Implementing a Microsoft® SQL Server® 2008 R2 Database geometry Data Type Key Points The geometry data type is used for flat Earth (that is. It is a 2D data type.STAsText(). It provides comprehensive coverage of the OGC standard. there is provision for Z (elevation) and M (measure) as well as the X and Y coordinates. The X and Y coordinates are represented by STX and STY properties. Y. Z.AsTextZM(). You can see input and output of X. the above code returns the following results: Comprehensive coverage of the OGC Geometry data type is provided by the SQL Server geometry data type. geometry Data Type The geometry data type is based on an X and Y coordinate system. SELECT @Location. When executed. In the definition of the type. planar) data storage and calculations. and M in the following code: DECLARE @Location geometry. .0). SELECT @Location.

For example. When inputting data. the SRID value is typically left as zero. there is no need to specify an SRID when working with geometric data. to allow you to visualize the spatial results. the area of a shape which is 3 x 2 is still 6 regardless of whether 3 and 2 are in meters or in inches. Spatial Results Viewer Whenever a SQL Server result set is being displayed in SQL Server Management Studio and the results include columns of geometry or geography data type. the measurement system is not directly relevant. . a special spatial results viewer tab will also be provided. For this reason.Working with SQL Server® 2008 R2 Spatial Data 19-19 SRID and geometry When working with geometric data.

The points on the line are also included. Result Size Limitations In the SQL Server 2008 implementation of the geography data type. The same set of points actually defines two regions: all the points inside the postal code region and all the points outside the postal code region. The geography data type can also store but not process Z and M values. To enclose points. Imagine the set of points that define a postal code region. the order in which the points are provided matters. any resulting geography value must be contained within a single hemisphere. Point Order in Polygons When defining the shape of a polygon via a series of points. . It is an extension to the OGC standard. 4326 (or WGS 84) is the most commonly used spatial reference system when working with the geography data type. The latitude and longitude values are represented by the Lat and Long properties. As you draw a shape. the Lat and Long properties must relate to valid latitudes and longitudes for the selected spatial reference system. they are listed in anti-clockwise order. typically involving actual positions or locations on the Earth.19-20 Implementing a Microsoft® SQL Server® 2008 R2 Database geography Data Type Key Points The geography data type is used for round Earth values. all the points to the left of the line that you draw will be enclosed by the shape. Unlike the geometry data type where the X and Y coordinates can be any valid number. geography Data Type The geography data type is based on a latitude and longitude coordinate system. This does not mean any specific hemisphere such as the northern or southern hemispheres but just that no two points can be more than half the Earth apart if they are contained in the same instance of the geography data type.

the viewer is quite configurable. The spatial results viewer in SQL Server Management Studio in SQL Server 2008 R2 is limited to displaying the first 5000 objects from the result set. Mercator. the geographic projection to use for display (for example. For geography. Bonne.Working with SQL Server® 2008 R2 Spatial Data 19-21 If you draw a postal code region in a clockwise direction. and you can choose to display another column as a label over the relevant displayed region. an error would then be returned. You can set which column to display.). a spatial results viewer will be provided whenever a result set is displayed in SQL Server Management Studio and the results include either geometry or geography data. etc. Spatial Results Viewer As discussed in the previous topic. Because results are not permitted to span more than a single hemisphere. . you are defining all points outside the region.

Both methods are implemented in the spatial types and you will see how they are implemented shortly. Geography Markup Language (GML) is the XML-based representation for spatial data. All CLR data types must implement two string-related methods. String-based representations of the data need to be accommodated. As an example. Well-known Binary (WKB) is a more compact binary representation that is useful for computer to computer interchange. Spatial Data Formats The OGC and other organizations that work with spatial data define a number of formats that can be used for interchanging spatial data. There are a number of variations of these methods used for input and output.19-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Spatial Data Formats Key Points The internal binary format of any CLR data type is not directly used for input and output of the data type in most cases. CLR Data Type Representation CLR data types (including the geometry and geography system CLR data types) are stored in a binary format determined by the designer of the data type. this is not typically very helpful as you would need to have a detailed understanding of the internal binary format. Some of the formats that SQL Server supports are: • • • Well-known Text (WKT) is the most common string format and is quite human-readable. The ToString method is also implemented and also assumes the WKT format. the STAsText method provides a specific WKT format as output and the AsTextZM method is a Microsoft extension that provides the Z and M values as well as the 2D coordinates. The Parse method is used to convert a string to the data type and the ToString method is used to convert the data type back to a string. . While it is possible to both input and output instances of the data type using a binary string. Note that the Parse method is implemented and assumes that the input is in WKT format.

Working with SQL Server® 2008 R2 Spatial Data 19-23 Question: Why is there a need to represent spatial data types as strings within SQL Server? .

Common Methods The STDistance method returns the distance between two spatial objects. The distance between two polygons can also be calculated. It is returned as the minimum distance between any two points on the polygons. The STLength method returns the total length of the objects in a geometry instance. The STIntersects method returns 1 when two objects intersect and 0 otherwise. Several of the common methods and properties are described here but many more exist. The STArea method returns the total surface area of a geometry instance. STLength returns the total length of all line segments that make up the polygon. For example. Properties such as STNumGeometries and STGeometryN provide access to the members of these collections. Common Collection Properties Support has also been provided in SQL Server for a number of collections defined in the OGC specifications. along with a number of OGC defined collections. The STBuffer method returns an object whose points are within a certain distance of an instance of a geometry object. Note that this does not only apply to points. A GeometryCollection can be held in a geometry object and can contain a number of other nested geometry objects. The STUnion method returns a new object that is formed by uniting all points from two objects.19-24 Implementing a Microsoft® SQL Server® 2008 R2 Database OGC Methods and Properties Key Points A wide variety of OGC methods and properties has been provided in SQL Server spatial data. . with a polygon.

Working with SQL Server® 2008 R2 Spatial Data 19-25 Microsoft Extensions Key Points Besides the OGC properties and methods. An example of GML is shown here: <Point xmlns="http://www.net/gml"> <pos>12 15</pos> </Point> GML is excellent for information interchange but you can see that the representation of objects in XML can quickly become very large. but allows for the storage and retrieval of invalid instances. A valid instance representing the same point set of any invalid instance can then be retrieved using the MakeValid method. SQL Server produces only valid geometry instances. Several of these extensions are described in this topic but many more exist. . The IsNull method returns 1 if an instance of a spatial type is NULL. Microsoft has enhanced the data types by adding properties and methods that extend the standards. The AsGML method returns the object encoded as Geographic Markup Language (GML). The BufferWithTolerance method returns a buffer around an object but uses a tolerance value to allow for minor rounding errors. Note that the extended methods and properties do not have the ST prefix. Microsoft has provided a number of useful extensions to the standards. Common Extensions While the coverage provided by the OGC specifications is good. The Reduce method is used to reduce the complexity of an object while attempting to maintain the overall shape of the object.opengis. otherwise it returns 0. The MakeValid method takes an arbitrary shape and returns another shape that is valid for storage in a geometry data type.

click All Programs.sql script file. click Microsoft SQL Server 2008 R2. Open the 21 – Demonstration 2A. Demonstration Steps 1. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. In the virtual machine. • 2.sql script file from within Solution Explorer. click SQL Server Management Studio. 3.ssmssln and click Open. Follow the instructions contained within the comments of the script file. . From the File menu.19-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: Spatial Data Types Key Points In this demonstration you will see how to work with SQL Server spatial data types. In the Connect to Server window. type Proseware in the Server name text box and click Connect. click Open. click Start. navigate to D:\6232B_Labs\6232B_19_PRJ\6232B_19_PRJ. click Project/Solution. Open and execute the 00 – Setup.

Working with SQL Server® 2008 R2 Spatial Data 19-27 Lesson 3 Using Spatial Data in Applications Once you have gained an understanding of how spatial data is stored and accessed in SQL Server. spatial indexes can be created to improve the performance of the applications and an understanding of how spatial indexes work and which methods they are useful for is necessary for building performant applications. you will be able to: • • • • • • • Describe the need for spatial indexes Explain the basic tessellation process used within SQL Server spatial indexes Describe the different types of spatial indexes Implement spatial indexes Explain which geometry methods can benefit from spatial indexes Explain which geography methods can benefit from spatial indexes Describe options for extending SQL Server spatial data support . Objectives After completing this lesson. it is important to gain an understanding of implementation issues that need to be addressed when building applications that use SQL Server spatial data. In particular.

19-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Performance Issues in Spatial Queries Key Points Spatial queries can often involve a very large number of data points. Spatial indexes help avoid unnecessary calculations. Executing methods like STIntersect for a large number of points is slow. Question: What is the challenge in locating the intersecting streets? Question: Which streets would you need to check? Question: How could you minimize this problem? . Discussion Imagine trying to locate the streets that intersect your suburb or region.

The basic idea is that if your suburb is located within a region of cells.Working with SQL Server® 2008 R2 Spatial Data 19-29 Tessellation Process Key Points Spatial indexes help avoid unnecessary calculations by breaking larger problems down into problems that need to be solved and those that don't need to be solved. would take a very long time. Moreover. To avoid making unnecessary calculations. Grid levels are used to quickly isolate large areas that do not need to be checked. you do not need to check for streets that are contained entirely within Paris. the biggest problem is that checking every street in the state or worse. you do not need to check any street that is contained entirely within France. The irony of this is that almost all of these calculations would return an outcome that showed no intersection. any streets that do not extend into those cells do not need to be checked at all. . Each grid level is made up of a number of cells. As a real-world human-based example. SQL Server breaks the problem-space into relevant areas by using a four-level grid. if you are checking for streets that are part of Vienna. You can quickly eliminate those as not being of interest to you. in the country. Tessellation In the example from the discussion where you were considering finding streets that intersect your suburb or region.

19-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Spatial Indexes Key Points Spatial indexes are unlike standard relational indexes. possible candidates are found. SQL Server provides a Filter method that only applies to the primary filter. However. After applying the predicate. To allow a check on the effectiveness of the primary filter. In the street-based example that was mentioned previously. if Vienna was contained inside a grid cell and a street entered that cell. Instead of precisely locating the specific rows. as it is possible that it might. queries that use spatial indexes operate in a two-phase manner. This greatly reduces the number of calculations that SQL Server needs to make as long as the spatial index has been effective. Primary and Secondary Filters Spatial indexes are used as a primary filter on the data. you still do not know if the street actually intersects the boundaries of Vienna. spatial indexes are used to locate rows that could potentially be of interest. you know that you need to check whether or not it does. you are left with precisely the rows you require. In the first phase. It executes the methods in the WHERE clause of the query on the filtered set of candidate rows. Spatial Indexes When you traverse a clustered or non-clustered index on a SQL Server table. You saw in the last topic how tessellation can be applied to minimize the number of calculations that need to be performed. Spatial indexes use this tessellation process to quickly reduce the overall number of rows to a list of candidate rows that might potentially be of interest. All possible candidate rows are returned by the filter. the returned list of candidates is individually checked. Spatial indexes work differently than this. The number of rows returned by that method can then be compared to the . There may still be false positives after the filter is applied. The secondary filter is used to locate the precise rows of interest. Instead of locating specific rows to be returned. you apply the predicates in the WHERE clause to filter the specific rows. In the second phase.

.Working with SQL Server® 2008 R2 Spatial Data 19-31 total number of rows to see how effective the spatial index has been. This will be shown in an upcoming demonstration.

a spatial index is most useful when it knows the overall area that is covered by the spatial data. The geometry data type has no natural boundaries and specifying a bounding box allows SQL Server to produce a more useful index. Indexes on geometry data type should specify a BOUNDING_BOX. Spatial indexes created on the geography data type do not need to specify a bounding box as the data type is naturally limited by the Earth itself. Spatial indexes on the geometry data type specify a BOUNDING_BOX. and the spatial data column that needs to be indexed. providing a name for the index. the rows they are contained in would need to be returned by the primary filter. .19-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Implementing Spatial Indexes Key Points Spatial indexes are created using the CREATE SPATIAL INDEX statement. You specify a value for the number of cells per grid for each grid level in the index. If values arise outside the bounding box coordinates. Index Bounds Unlike more traditional types of index. the table that the index is to be created on. • • • A value of LOW indicates 16 cells per grid or a 4 x 4 cell grid. CREATE SPATIAL INDEX Spatial indexes are created in a similar way as non-clustered indexes. Grid Density SQL Server also allows you to specify grid densities when creating spatial indexes. You execute the CREATE SPATIAL INDEX statement. A value of MEDIUM indicates 64 cells per grid or a 8 x 8 cell grid. A value of HIGH indicates 256 cells per grid or a 16 x 16 cell grid. This provides the coordinates of a rectangle that would contain all possible points or shapes of interest to the index. The table must have a clustered primary key before a spatial index can be built on it.

Indexes with one set of grid densities might be more useful than a similar index with a different set of grid densities for locating data in a specific query. Limitations Spatial indexes do not support the use of ONLINE build operations. as are available for other types of index in the Enterprise Edition of SQL Server.Working with SQL Server® 2008 R2 Spatial Data 19-33 Spatial indexes are also different from other types of index as it might makes sense to create multiple spatial indexes on the same table and column. .

The table in the slide shows the specific predicates that can potentially make use of a spatial index as a primary filter. Unless the predicate in your query is in one of these forms. .19-34 Implementing a Microsoft® SQL Server® 2008 R2 Database geometry Methods Supported by Spatial Indexes Key Points Not all geometry methods and not all predicate forms can benefit from the presence of spatial indexes. spatial indexes that you create will be ignored.

. not all geography methods and not all predicate forms can benefit from the presence of spatial indexes. The table in the slide shows the specific predicates that can potentially make use of a spatial index as a primary filter. Unless the predicate in your query is in one of these forms.Working with SQL Server® 2008 R2 Spatial Data 19-35 geography Methods Supported by Spatial Indexes Key Points Similarly to the geometry type. spatial indexes that you create will be ignored.

You may be able to use some of these extensions directly. types. and aggregates that were present in the sqlspatial. .19-36 Implementing a Microsoft® SQL Server® 2008 R2 Database Extending SQL Server Spatial Key Points A very active community that contributes user-created extensions to SQL Server spatial data exists on the CodePlex site. the functions. They may also be useful as starting points when creating your own extensions to the SQL Server spatial data. the capabilities provided in the project will change.codeplex.com project at the time of writing these notes are listed. In the slide. As the project continues to evolve.

From the File menu. In the Connect to Server window. Follow the instructions contained within the comments of the script file. Open and execute the 00 – Setup.sql script file from within Solution Explorer.ssmssln and click Open. 3. Open the 31 – Demonstration 3A. In the virtual machine. navigate to D:\6232B_Labs\6232B_19_PRJ\6232B_19_PRJ. • 2.sql script file. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Open. Demonstration Steps 1. click All Programs. click Project/Solution. click Start. type Proseware in the Server name text box and click Connect. click SQL Server Management Studio. click Microsoft SQL Server 2008 R2.Working with SQL Server® 2008 R2 Spatial Data 19-37 Demonstration 3A: Spatial Data in Applications Key Points In this demonstration you will see how to use SQL Server spatial data to solve some business questions. .

Click Switch User. . you must complete the following steps: 1. and then click Hyper-V Manager. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. If you are prompted to confirm that you want to revert. 7. click on the Revert toolbar icon. and then click Other User. In Virtual Machine Connection window. and then close the Virtual Machine Connection window. Before you begin the lab. On the host computer. 6. wait until the Press CTRL+ALT+DELETE to log on message appears. Wait for the revert action to complete. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. 5. you will use the available virtual machine environment. point to Administrative Tools.19-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 19: Working with SQL Server Spatial Data Lab Setup For this lab. wait until the Press CTRL+ALT+DELETE to log on message appears. Right-click 623XB-MIA-DC and click Connect. Right-click 623XB-MIA-DC and click Start. if the user is not already logged on: • • On the Action menu. In the Virtual Machine Connection window. if the virtual machine 623XB-MIA-DC is not started: • • • 4. In the Virtual Machines list. 2. click the Ctrl-Alt-Delete menu item. 3. In the Virtual Machines list. In the Virtual Machine Connection window. click Start. click Revert.

If the Server Manager window appears. When the query window opens. You will make some changes to the system to help support the need for spatial data. One of the developers has provided a table of the locations where prospects live. 15. 13. click Full Screen Mode. In the Authentication drop-down list box. click Execute on the toolbar. type Proseware in the Server name text box. In the File menu.ssmssln.GetNearbyProspects @ProspectID int @DistanceInKms int None Distance (in Kms) ProspectID LastName FirstName WorkPhoneNumber CellPhoneNumber AddressLine1 AddressLine2 City Longitude Latitude Distance Output Parameters Output Rowset Columns Output Order . The new Marketing database was initially designed prior to the company beginning to implement spatial data. click All Programs. In Connect to Server window. click Microsoft SQL Server 2008 R2. click Open. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. From the View menu. double-click the query 00-Setup.ProspectLocation. check the Do not show me this console at logon check box and close the Server Manager window. open the project D:\6232B_Labs\6232B_19_PRJ\6232B_19_PRJ. In the virtual machine.sql. ii. 12. In Solution Explorer. It is called Marketing. 10. 11. 9. In the Open Project window. 14. A second developer has added columns to it for Latitude and Longitude and geocoded the addresses. click Start. and click Project/Solution. select Windows Authentication and click Connect. Lab Scenario Your organization has only recently begun to acquire spatial data within its databases. and click SQL Server Management Studio.Working with SQL Server® 2008 R2 Spatial Data 19-39 • Log on using the following credentials: i. in the Virtual Machine Connection window. Supporting Documentation Stored Procedure Specifications Stored Procedure Name Input Parameters Marketing.

Review and execute the sample script  Task 1: Review and execute the sample script • Review the query. you should have seen how to work with the geometry data type.9. The main tasks for this exercise are as follows: 1. . Results: After this exercise.1 to 19. you have decided to learn to write queries using the geometry data type in SQL Server. execute the query. and review the results for scripts 19. You will review and execute scripts that demonstrate querying techniques.19-40 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Familiarity With Geometry Data Type Scenario In this lab.

3.ProspectLocation table.  Task 3: Drop the existing Latitude and Longitude columns • Once you are sure the new column has correct data.Working with SQL Server® 2008 R2 Spatial Data 19-41 Exercise 2: Adding Spatial Data to an Existing Table Scenario In this lab. drop the existing Latitude and Longitude columns. Results: After this exercise. Add a Location column Write code to assign values to this column Drop the existing Latitude and Longitude columns  Task 1: Add a Location column • Add a Location column to the Marketing. 2. you should have replaced the existing Longitude and Latitude columns with a new Location column. . The main tasks for this exercise are as follows: 1.ProspectLocation to replace the existing Latitude and Longitude columns with a new Location column of type geography.  Task 2: Write code to assign values to this column • Write code to assign values to this column based on the existing Latitude and Longitude columns. You need to migrate the data to the new Location column before you delete the existing Latitude and Longitude columns. you need to modify an existing table Marketing.

ProspectLocation table  Task 3: Design and implement the Stored Procedure • Design and implement the stored procedure based on the specifications given in the supporting documentation for the lab  Task 4: Test the procedure • Test the stored procedure by executing the following code: EXEC Marketing. To minimize effort.50. . you will create a spatial index on the table. rather than just on the phone.GetNearbyProspects 2. 2. To ensure it performs quickly. 3.19-42 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 3: Business Application of Spatial Data (Only if time permits) Scenario Salespeople are keen to visit with prospects at their own locations. 4. The main tasks for this exercise are as follows: 1. you should have created and tested the required stored procedure. they are keen when visiting a prospect to also see other prospects in the same area. Review the requirements Create a spatial index Design and implement the Stored Procedure Test the procedure  Task 1: Review the requirements • Review the supporting documentation for details of the required stored procedure  Task 2: Create a spatial index • Create a spatial index on the Marketing. You will write a stored procedure that provides details of other prospects in the area. Results: After this exercise.

2. Set the SRID for geometry objects to 0 to ensure that operations on multiple geometry objects can always be performed. Before creating spatial indexes. . 2. 3. What is the main difference between the geometry and geography data types? Why does the order of points matter when defining a polygon? Best Practices 1. Use a CHECK CONSTRAINT to ensure that the SRID values for a column are consistent across all rows.Working with SQL Server® 2008 R2 Spatial Data 19-43 Module Review and Takeaways Review Questions 1. make sure that the queries that need to be executed against the data use predicate forms that are supported by the types of index you are creating.

19-44 Implementing a Microsoft® SQL Server® 2008 R2 Database .

Working with Full-Text Indexes and Queries 20-1 Module 20 Working with Full-Text Indexes and Queries Contents: Lesson 1: Introduction to Full-Text Indexing Lesson 2: Implementing Full-Text Indexes in SQL Server Lesson 3: Working with Full-Text Queries Lab 20: Working with Full-Text Indexes and Queries 20-3 20-10 20-21 20-33 .

much more powerful than what is possible with traditional T-SQL language statements alone. you will be able to: • • • Describe why user interfaces in existing applications are not sufficient for end user search needs Implement full-text indexes in SQL Server Query SQL Server using full-text queries . Objectives After completing this module. Full-text indexing in SQL Server allows you to create very flexible searching options.20-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Existing business applications and the database applications that are associated with them tend to offer very limited options when users need to search for information.

while powerful. . you will be able to: • • • Explain why applications need to offer much more flexible user-interaction options Explain why the T-SQL LIKE statement. This is usually not the case. Objectives After completing this lesson. does not offer the level of flexibility that users really want Execute queries that use SQL Server full-text predicates or table-valued functions. There is a substantial mismatch between what is being provided to end users and what they really want to use. You will also investigate the types of queries that users really wish to execute.Working with Full-Text Indexes and Queries 20-3 Lesson 1 Introduction to Full-Text Indexing Most developers feel that their applications provide sufficiently usable search options for end users. In this lesson. you will explore this mismatch and see how traditional searching approaches using T-SQL statements such as LIKE are not capable of providing appropriate levels of search capability.

They prefer much more flexible and “fuzzy” interfaces. Most online mapping engines today have a single input box where you type what you are looking for. Consider the early online mapping engines. Why do you think so? IT Professionals tend to like everything they deal with to be exact. in contrast to the current online mapping engines. you needed to enter values into multiple input locations for street number. When you interacted with those online mapping engines. country. The system then works out what’s needed. Ask yourself which of these screens you would prefer to interact with. Question: Which type of interface would you prefer? Most people prefer the first search page shown. precise. Ironically. this is the exact opposite of what most end users prefer.20-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Discussion: The Need for More Flexible User Interaction Key Points Spend some time looking at the two simple search screens on the slide. etc. suburb. Question: Why aren't interfaces to business systems built like that? . and well-structured. street name.

Keylee. and so on. The search also returns rows where the name is Ashlee. Performance Another consideration is performance. pendulum. you would need to have an understanding of 'words'. you would need to have an understanding of punctuation.Working with Full-Text Indexes and Queries 20-5 Why LIKE Isn’t Enough Key Points The LIKE operator in T-SQL is a very powerful operator that works by finding string values within strings. This looks for rows where the FirstName column contains the string 'Lee'. open. This is not the same as searching for the word Lee. Kathleen. you would get values such as pencil. T-SQL LIKE Operator The most common use for the LIKE operator in T-SQL is to search for substrings within strings. and Wathalee. . In the example shown on the slide. This means that you would also need to have an understanding of the target languages. Shirleen. the search term '%Lee%' is being used. Waleed. if a search was made using the term '%Pen%'. Carolee. Question: What would you need to know to be able to find words rather than substrings? Finding words involves much more than searching for strings within other strings. It applies a pattern-based search. Colleen. yet the rules for punctuation differ by language. Similarly. as well as values containing the word Pen. Question: What is needed to really find the word Pen? To be able to find the word Pen. there is a big difference between searching for substrings and searching for words. To start with. An index on a column is ignored when you are searching for values using a pattern with a leading % wildcard. penitentiary. While this can be useful.

20-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Question: Is LIKE case sensitive? .

They prefer interfaces that are much more flexible and "fuzzy". end users want something quite different. such as sentence and paragraph breaks. effective search needs much more capability than that. Ideally. One person might say "Client" while another says "Customer". . the more relevant the result is. Query Fuzziness IT professionals tend to like to work in an exact and precise way with highly defined structure. Near Most users have had the experience of searching for two words and the returned results include documents that contained both words but they were so far apart in the document that the fact that they were both contained in the document was almost meaningless. you need a concept of nearness. Often the nearer together two words are. Full-text search in SQL Server is capable of being taught that these terms are equivalent. Ironically. But how do you measure how far apart words are? Full-text indexes in SQL Server understand nearness and also understand more subtle concepts. This can be particularly important with companies that are involved in mergers. Thesaurus It is common for different people in an organization to call the same object by different names.Working with Full-Text Indexes and Queries 20-7 Fuzziness in Queries Key Points While being able to find words within columns that you search is useful. They often don't know exactly what they are looking for but they know something about it. SQL Server knows that two words that are side-by-side in a single sentence are logically closer than two words with a sentence break between them. such as what it was about or some of the key words related to it. End users are looking for much more "fuzzy" concepts when searching.

the words "drive". "drove". if the user wants to find data related to "Attempts to Improve Solar Energy Efficiency". Consider how popular existing Internet-based search engines such as Bing are.20-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Inflections To a human. SQL Server understands inflectional forms of words. how would you search for that using T-SQL? Full-text indexing and querying in SQL Server allows you to search for results based on semantics (or meaning). Users really like this form of search yet very few business applications today provide them with the ability to do searches like this. This is much harder for computer systems. For example. and "driving" are really just the same word. they would expect the system to return results containing any of them. If a human was searching for one of these words. This is extremely powerful and directly appeals to end users. FreeText End users often do not know what they are looking for but know some information about what the result is related to. .

click Open. In the Connect to Server window. click Start. From the File menu.sql script file. 4. navigate to D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ. In the virtual machine. Open the 11 – Demonstration 1A. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. . click Project/Solution.sql script file from within Solution Explorer. 2. 5. 3. Open and execute the 00 – Setup. click Microsoft SQL Server 2008 R2.ssmssln and click Open. click All Programs. type Proseware in the Server name text box and click Connect. click SQL Server Management Studio.Working with Full-Text Indexes and Queries 20-9 Demonstration 1A: Using Full-Text Queries Key Points In this demonstration you will see why full-text indexing is important for creating advanced and flexible user interfaces Demonstration Steps 1. Follow the instructions contained within the comments of the script file.

Objectives After completing this lesson. you saw how traditional search options based on T-SQL operators such as LIKE provided only limited searching ability. you will also need to gain an understanding of the components of a full-text searching system. you will learn about the advanced search capabilities and how to implement full-text indexes. Before learning the details of how full-text indexes are implemented. In this lesson. you will be able to: • • • • • Describe existing search-related options and their features Discuss specific capabilities of full-text indexes implemented in SQL Server Describe the core components that make up a full-text search system Detail the available languages supported by SQL Server full-text indexing Implement a full-text index in SQL Server .20-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Implementing Full-Text Indexes in SQL Server In the previous lesson.

. SQL Server interfaced with the search capabilities at the operating system level. Question: Which forms of search are you already familiar with? Question: Describe your experiences (both good and bad) with any form of search. Full-text search in SQL Server was completely redesigned in SQL Server 2008. This has brought significant benefits in terms of both management and performance. In prior versions.Working with Full-Text Indexes and Queries 20-11 Discussion: Search-related Options Key Points There are many existing forms of search available on the Windows operating system platform. This separation is maintained to ensure stability and security of the SQL Server engine. The only components that now live outside the SQL Server engine are the components that can be created or customized by end users and developers. Starting with SQL Server 2008. This led to both management and performance-related challenges. full-text search has been implemented directly inside the SQL Server engine. Include your experience with earlier versions of full-text search in SQL Server if you have used it.

If possible. ntext. build indexes on those data types. and image columns as follows: Old Data Type text ntext image Next. are supported as well as their double-byte character equivalents. it is not recommended as these data types have been deprecated and will be removed in a later version of SQL Server. XML data can also be indexed via full-text indexes. Full-text indexes on XML allow indexing all the text within the XML. While creating full-text indexes on text. XML indexes allow fast access for certain types of XQuery based queries.20-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Full-Text Search in SQL Server Key Points Full-text indexing in SQL Server allows for the creation of word-based indexes built on character-based data stored in SQL Server tables. first convert any text. A wide variety of character data types is supported. Data Types Full-text indexes in SQL Server are created on character-based data. another column in the table must New Data Type varchar(max) nvarchar(max) varbinary(max) . SQL Server knows how to extract character data from a large number of document types that can be stored in varbinary(max) columns. nchar and nvarchar. ntext. Single-byte character columns. To be able to index these columns. and image data types is possible. char and varchar.

where appropriate. to provide a measure of how relevant the returned results are. Once full-text indexes are created.Working with Full-Text Indexes and Queries 20-13 hold the file extension (for example. . Full-Text Indexes Full-text indexes are stored in the database. as other indexes are. The predicates that are supported by full-text indexes allow users to query using simple words and phrases that are much more familiar to the users. special query predicates and table-valued functions can be used to provide powerful querying abilities. A significant number of languages are supported by default and it is possible to extend the product by the construction of code to support additional languages. Each index is associated with a table that contains the character data being indexed and full-text indexing supports multiple concurrent languages in different columns.TXT) of the document that is being held in the varbinary(max) column. Full-text indexes can be created on textual data in a variety of languages. The table-valued functions are also able to rank results. .

SQL Server also supports the concept of adding additional iFilters. If the data is being held in a character-based column in a table. iFilter The first step in indexing character data is to obtain a stream of characters. iFilters. .20-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Core Components of Full-Text Search Key Points The full-text indexing system is made up of a number of components that are described using specific terminology. The output is then a stream of words. Stemmer When a stream of words has been obtained. A common example of this would be to install an iFilter to work with PDF documents. drove. Inflectional forms of the words need to be resolved and verbs conjugated (that is. You can create user-created iFilters for special types of documents or you can obtain iFilters from companies that create special document types. SQL Server needs to know how to extract a stream of characters from that type of document. word breaking and stemming are often called tokenizing. It is important to understand the role of each component and to understand the terminology used. driving). Together. if the data is being held in a document stored in a varbinary(max) column. The filters that perform this action are called iFilters. drive. A significant number of iFilters are provided with SQL Server. processing needs to be done to standardize the format of the words. This involves an understanding of the punctuation and whitespace rules in each language. rather than a stream of characters. this is straightforward. the next step is to break that stream into a series of words. Word Breaker Once a stream of characters has been obtained. Word Breakers and Stemmers operate sequentially to extract the words that need to be placed in the index. However.

to assist with keeping terms that are related within the same sentence in the output. Question: Which among the core components of full-text search are likely to be language-specific? Indexing. and Stopword Example As a high-level example of the actions performed by the iFilter. consider the following document: <Document> <Author>Proseware. unlike a standard clustered or nonclustered index.driving us broke and driving us crazy. the term "noise word" has been replaced by the term "stop word". Stemmer and Stopword components. After a Word Breaker has been applied. After a Stopword list is applied. Word Breaker. Stemmer. SQL Server also allows you to create stoplists that contain your own stopwords that you do not want to index. Every language has a series of words such as "and" or "the" that do not add value to the index. Querying involves using the full-text predicates and table-valued functions to return results.fulltext_system_stopwords WHERE language_id = 1033. you then have a list of words to be indexed.</Author> <Address>19 Proseware Drive. It is important to understand that. The exact text that is output will depend upon the design of the iFilter but the following output could be obtained: author . title driving us broke and driving us crazy..proseware. . full-text indexes are not updated during data modification statements. A good example of this would be your company name. The iFilter will output a stream of text. Note that in recent versions of SQL Server. contoso. address proseware drive contoso. CONTOSO</Address> <Title>Driving Us Broke And Driving Us Crazy</Title> </Document> An iFilter could be created to extract text from this type of document. the full-text indexes are updated shortly after the data modification has been performed.title . Scoring (also known as ranking) involves providing a measure of relevance of each row in the result set. iFilter. Word Breaker. Scoring Finally. Note that this particular iFilter replaces XML element tags with the name of the tag and a dash separator.address . the following output could be obtained: author proseware inc. However. You can see the list of standard noise words for the English language (which has Windows locale identifier 1033) by executing the query: SELECT * FROM sys. It is likely that it appears in every document so it would likely add little value to the index.19 proseware drive. title driving broke driving crazy. inc. SQL Server uses them to construct the full-text index. the following output could be obtained: author proseware inc. address 19 proseware drive contoso. Inc.Working with Full-Text Indexes and Queries 20-15 Noise Word Removal It is not always desirable to index all the words in a document. if auto-population is enabled. It also adds a period at the end of each tag. Querying.

. address proseware drive contoso. the words are ready to be inserted into a full-text index. title drive broke driving crazy. The list of words is different to the original text but is sufficient for indexing the text.20-16 Implementing a Microsoft® SQL Server® 2008 R2 Database After a Stemmer has been applied. At this point. the following output could be obtained: author proseware inc.

. Question: Which of the languages in the list do you need to support in your applications or databases? Note that the three languages shown in red (or in lighter color in monochrome printing) are included with the product but disabled by default. They must be manually registered before they can be used. A full list of the supported languages can be seen by executing the following query: SELECT * FROM sys.Working with Full-Text Indexes and Queries 20-17 Language Support and Supported Word Breakers Key Points A large number of languages are supported by the built-in functionality in SQL Server full-text indexing. Language Support You can see from the list of languages presented in the slide how many languages are directly supported by full-text indexing in SQL Server. These language files were provided by third party organizations and were not included in the detailed testing of the SQL Server product so they are shipped in a disabled state.fulltext_languages. The query returns the Windows locale identifier in a column called lcid and the name of the language.

. this column could hold values such as '. Full-Text Catalog Full-text indexes are created within full-text catalogs. Table with Character-based Data Full-text indexes are created on tables in a way that is similar to how non-clustered indexes are created. If the character data is contained within a document in a column of type varbinary(max). One full-text catalog can be identified as the DEFAULT catalog and will be used for all full-text indexes that are created without specifying a catalog. you also need to specify the name of another column that will hold the name of the type of document. While the CREATE FULLTEXT CATALOG statement includes an option to specify a filegroup. While some maintenance operations can still be carried out at the catalog level but in general. the table that it is based upon.DOC'. most databases do not need more than one full-text catalog.TXT' and '. You need to specify a name for the index. The table must contain some character-based data from the list of supported data types mentioned earlier. This concept is mainly retained for backward compatibility with the earlier versions of SQL Server. For example. and the name of the column that contains the character data. Full-Text Index The full-text index is created using the CREATE FULLTEXT INDEX command.20-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Implementing Full-Text Indexes Key Points Creating and querying full-text indexes is not difficult but involves a number of steps. when the full-text indexes were created in the operating system rather than directly in the database. this setting is now ignored.

Populate the Index Once the index is created. . In the next lesson. Auto-population is the most common option used. This will almost always be the primary key of the table.Working with Full-Text Indexes and Queries 20-19 You also need to specify which index can be used to uniquely identify rows within the table. you will see how to use full-text querying capability to return results from the full-text indexes. One full-text index is allowed per table or indexed view. you can manually request SQL Server to start populating it. and each full-text index applies to a single table or indexed view. based on the existing data or you can set the index to be auto-populated. SQL Server tracks the rows that have been changed and updates the index as close to the end of the data modification as possible. Query the Index Querying the full-text indexes relates to using the full-text predicates or the full-text table-valued functions in T-SQL queries.

3.sql script file from within Solution Explorer. click Project/Solution. Open the 21 – Demonstration 2A. In the virtual machine. Follow the instructions contained within the comments of the script file. • 2. click SQL Server Management Studio.20-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: Implementing Full-Text Indexes Key Points In this demonstration you will see: • • • How to create a full-text catalog How to create a full-text index How to check when a full-text index is fully populated Demonstration Steps 1. click Start. navigate to D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ. click Open.ssmssln and click Open. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.sql script file. In the Connect to Server window. Open and execute the 00 – Setup. . From the File menu. type Proseware in the Server name text box and click Connect. click Microsoft SQL Server 2008 R2. click All Programs.

you will be able to: • • • • • • Write queries using the CONTAINS predicate Write queries using the FREETEXT predicate Return CONTAINS and FREETEXT results as tables along with ranking of relevance Create stopwords and stoplists Add details of synonyms and replacements to a full-text thesaurus Manage and debug full-text indexes .Working with Full-Text Indexes and Queries 20-21 Lesson 3 Working with Full-Text Queries The real power of using full-text indexes comes after the index has been built and populated and you begin to execute queries that make use of the index. Full-text predicates can be added to WHERE clauses. tables of full-text results can be returned and queried or joined to other tables. There are two basic ways to execute queries using full-text indexes. Objectives After completing this lesson. Alternately. It is also important to be able to exercise control over which words are included in the index and to use the thesaurus to provide synonyms or replacements for common search terms.

'drive NEAR car') This predicate will filter rows where the Description column contains the word "drive" somewhere "near" the word "car". The permitted Boolean operators are: • • • AND AND NOT OR Proximity The CONTAINS predicate can also search for combinations of words using the NEAR operator. Results are often more or . It is important to realize however. that NEAR is a relative term.20-22 Implementing a Microsoft® SQL Server® 2008 R2 Database CONTAINS Queries Key Points Queries using the CONTAINS predicate search for words or combinations of words. Boolean Logic Boolean logic can also be applied to search for combinations of words. the query is changed so that only rows where the Description column contains the word 'file' but does not also contain the word 'boundary' are returned. The most basic form of usage is shown in the first example on the slide. CONTAINS The CONTAINS predicate is used to search for words. The query returns the MessageID and Description columns from the dbo. In the second example shown in the slide. This is shown in the following WHERE clause: WHERE CONTAINS(Description. They can also perform proximity searches and advanced searches using inflectional forms of words or synonyms and replacements from a thesaurus.Messages table for each row where the Description column contains the word 'filing'.

The more important a search term is. the word 'symmetric' is ranked as 0. the heigher the weight that should be assigned to it.2.8). and driving as being different versions of the same word.client)') This predicate will filter rows where the Description column contains words that have been configured as synonyms for the word "client". 'FORMSOF(INFLECTIONAL.8.2) )') In this WHERE clause. This is shown in the following WHERE clause: WHERE CONTAINS(Description. you will see how to configure a thesaurus to make these queries possible. symmetric weight (. This is shown in the following WHERE clause: WHERE CONTAINS(Description. The ISABOUT function will be discussed later in the lesson. you learned how end users think of words like drive. Weights are values between 0 and 1. drove. you can include a search for these by using the FORMSOF function.4). the word 'certificate' is ranked as 0. Inflectional Earlier in the module. the developer is telling SQL Server how important each search term is by assigning a weight to each term. In this example. such as "driving" or "drove".4 and the word 'key' is ranked as 0. Thesaurus It is also useful to be able to search for words that are treated as having the same meaning within the organization. you will see how ranking the results of a proximity query usually provide more useful outcomes. Specified Relevance The CONTAINS predicate can also search for terms based upon the weighting that you assign to each term.0. This is shown in the following WHERE clause: WHERE CONTAINS(Description. 'ISABOUT (certificate weight (. Later in this lesson. The ISABOUT function is another example where it is important to rank the relevance of the results returned. 'FORMSOF(THESAURUS. drive)') This predicate will filter rows where the Description column contains a word that is an inflectional form of the word "drive". key weight (. .Working with Full-Text Indexes and Queries 20-23 less relevant depending upon how near the search words are in the column. In a CONTAINS query. Later in the lesson.

In the example shown in the slide. Users can enter the details of the meaning of what they are looking for and SQL Server finds matches that are relevant.Messages table are being returned for any rows where the Description column contains a value that is relevant to the phrase 'statement was terminated'.20-24 Implementing a Microsoft® SQL Server® 2008 R2 Database FREETEXT Queries Key Points FREETEXT queries are the most powerful form of full-text query. They depend upon SQL Server understanding the meaning of the term or phrase being searched for. This is very similar to the way the ISABOUT option works in the CONTAINS predicate but with FREETEXT. the MessageID and Description columns from the dbo. FREETEXT The FREETEXT predicate allows for the creation of the most powerful forms of full-text query. SQL Server automatically assigns the search term weightings based on an internal algorithm. This provides a result that makes it appear that SQL Server has "understood" the meaning of the search phrase. . Weighting SQL Server determines the relevance of the column data by internally assigning a weight to each of the search terms and then matching using the weights.

Note. it would be used to find entries in the dbo.Messages table for rows where the Description column is relevant to the search phrase 'statement was terminated'. It also provides a KEY column that determines the unique identity of the returned row so that it can be joined to the underlying table if necessary. SQL Server can also provide a ranking on the relevance of the results when table-valued functions are used instead of WHERE clause predicates. CONTAINSTABLE and FREETEXTTABLE also return a measure of relevance of each returned row called RANK. . In this example. CONTAINSTABLE CONTAINSTABLE is a table-valued function that returns the same rows that would have been filtered by a CONTAINS predicate but additionally provides a measure of relevance of each returned result via a RANK column that is returned in the table. Some will be more relevant than others. however. In the example shown in the slide.Messages table based upon the value in the MessageID column. FREETEXTTABLE FREETEXTTABLE is the table-valued function equivalent of the FREETEXT predicate. the MessageID and Description columns are being returned from the dbo. that the rows that are filtered have been returned as a table which has then been joined back to the source dbo.Messages table. The table returned by the FREETEXTTABLE function includes a column named KEY that is then used to locate the row in the original table.Working with Full-Text Indexes and Queries 20-25 Table Functions and Ranking Results Key Points Many of the CONTAINS and FREETEXT predicate options will return a large number of returned rows. RANK Besides returning the relevant rows. It also returns the same rows that would have been filtered by a FREETEXT predicate along with RANK and KEY columns.

This will return the most relevant rows first. the query returns an output where the resultant rows are arranged by the RANK descending. The value cannot be used to compare with other CONTAINSTABLE or FREETEXTTABLE function return values. Question: Would a search engine be more likely to use the table forms of these or the predicate forms? . You will see an example of this in the next demonstration.20-26 Implementing a Microsoft® SQL Server® 2008 R2 Database In the example shown in the slide. Note that the value returned by the RANK column is only meaningful within the table of results that are returned during that particular execution of the query.

breves. a search is automatically performed for all three of the words. If a search is performed for any of these three words. A replacement is used to provide alternate search terms. Replacement A replacement has also been created in the example shown in the slide. These are uncommon in the English language today apart from when words have been adopted from another language. There is one XML file per language per SQL Server instance. In the example shown. .Working with Full-Text Indexes and Queries 20-27 Thesaurus Key Points The full-text thesaurus allows specifying synonyms or replacements for search terms. It is set up in a language-specific XML file for each SQL Server instance. Only the replacement term would be searched for. an expansion has been set up. Thesaurus The full-text thesaurus does not live within the database. Diacritics are marks that are used as indicators in certain languages. 'operator'. Diacritic Sensitivity You may have noticed another option in the example thesaurus file in the slide. then a search for the word 'Windows 2000' would be carried out instead. Many other languages use accents. SQL Server has been told that the words 'user'. It is an instance-level XML file that contains details of synonyms and replacement searches. and 'developer' can be used interchangeably. if the user searches for either the word 'NT5' or the word 'W2K'. It is stored in the FTDATA folder that is located within the default database file folder for the instance. Note that no search for 'NT5' or 'W2K' would actually be carried out. In this example. Expansions are used for synonyms. Expansion In the example shown in the slide.

and virama. stress and iota subscripts. the search becomes sensitive to diacritics. etc. the Greek language includes diacritics for breathings. With the default value of zero for diacritics_sensitive. nukta. When the value is set to one. these are ignored. . chandrabindu. Indic diacritics include the anusvara.20-28 Implementing a Microsoft® SQL Server® 2008 R2 Database diaeresis. cedillas. For example.

The word 'Microsoft' would then no longer be indexed in full-text indexes within this database. a full-text stoplist called CompanyNames is being created and then the word 'Microsoft' is being added for language_id 1033 (English). Similarly. You can also configure other words to be ignored by full-text indexing. These are referred to as stopwords. . You can see the list of system-supplied stopwords for all languages by executing the following query: SELECT * FROM sys. Noise Words (Stopwords) Using English as an example. therefore. has a set of words that should be ignored when creating an index. in Simplified Chinese (language_id 2052). In the slide. Stoplists and Stopwords In addition to the system-supplied stopwords. SQL Server allows you to define your own sets of stopwords. Each language. words such as '我' (which means 'I') or '不' (which means 'not') are not useful in an index. SQL Server automatically excludes common noise words from full-text indexes.Working with Full-Text Indexes and Queries 20-29 Stopwords and Stoplists Key Points Not all words in any language are useful in a word index.fulltext_stoplists. Stopwords are created within stoplists.fulltext_system_stopwords. You can see the list of stoplists that have been created by executing the following query: SELECT * FROM sys. These are grouped together in stoplists. You can see the user-defined stopwords by executing the following query: SELECT * FROM sys.fulltext_stopwords. words such as 'and' or 'the' are not useful in an index.

This can cause a loss of performance.dm_fts* prefix. . the ALTER FULLTEXT CATALOG REORGANIZE command can be used. Fragmentation Full-text indexes can become fragmented like other types of index. To perform a master merge or all full-text indexes in a fulltext catalog. Dynamic Management Views and Functions Several dynamic management objects have been added to SQL Server to make it easier to troubleshoot full-text indexing. they can benefit from periodic reorganization to remove fragmentation. Like other indexes. The views and functions are all prefixed with a sys.dm_fts_parser.20-30 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Management of Full-Text Key Points Full-text indexes live within the database that holds the tables they are based on. You can pass a string. A fully merged index will have higher performance. a language id. You can see the list of supported document types by executing the query: SELECT * FROM sys. and optionally a stoplist to this function. It will then display how it parses the string into words and how it categorizes those words into useful words or noise words. Changes to full-text indexes are not merged into the main index files immediately. Changes are first written to separate locations within the index. Several useful DMVs have been provided for working with full-text indexing. This can be very helpful when trying to work out how a character value is being indexed. One particularly useful function is sys.fulltext_document_types. The ALTER INDEX REORGANIZE command can be used to reorganize a full-text index to reduce fragmentation and increase performance. Full-text indexing supports many document types without the need to install additional components.

Working with Full-Text Indexes and Queries 20-31 This query returns a row for each supported document type. .

type Proseware in the Server name text box and click Connect.sql script file from within Solution Explorer. In the Connect to Server window.20-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Working with Full-Text Queries Key Points In this demonstration you will see how to: • • • • Query a full-text index. click All Programs. Open and execute the 00 – Setup. click Start. • 2. From the File menu. click SQL Server Management Studio. Check the parsing of text by the full-text engine. 3. Locate the built-in stopwords.sql script file. click Open. . Follow the instructions contained within the comments of the script file. In the virtual machine.ssmssln and click Open. click Microsoft SQL Server 2008 R2. If Demonstration 1A was not performed: • • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Demonstration Steps 1. navigate to D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ. Create a stoplist and add a value to it. click Project/Solution. Open the 31 – Demonstration 3A.

5. 6. point to Administrative Tools. If you are prompted to confirm that you want to revert. In Virtual Machine Connection window. and then close the Virtual Machine Connection window. if the user is not already logged on: • • On the Action menu.Working with Full-Text Indexes and Queries 20-33 Lab 20: Working with Full-Text Indexes and Queries Lab Setup For this lab. In the Virtual Machines list. In the Virtual Machines list. In the Virtual Machine Connection window. 7. In the Virtual Machine Connection window. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. you will use the available virtual machine environment. 2. wait until the Press CTRL+ALT+DELETE to log on message appears. On the host computer. Right-click 623XB-MIA-DC and click Connect. Right-click 623XB-MIA-DC and click Start. click on the Revert toolbar icon. if the virtual machine 623XB-MIA-DC is not started: • • • 4. click Revert. In the Virtual Machine Connection window. 3. you must complete the following steps: 1. Before you begin the lab. Right-click 623XB-MIA-SQL and click Connect. Maximize the Hyper-V Manager window. wait until the Press CTRL+ALT+DELETE to log on message appears. and then click Other User. click the Ctrl-Alt-Delete menu item. and then click Hyper-V Manager. Click Switch User. Wait for the revert action to complete. click Start. .

GetRelevantDescriptions @PhraseToSearch nvarchar(1000) Nil ProductDescriptionID. 9. Lab Scenario Users have been complaining about the limited querying ability provided in the marketing system. .sql. 10. click Start.ssmssln. ii. You will implement a stoplist to avoid excessive unnecessary index size. click Microsoft SQL Server 2008 R2. in the Virtual Machine Connection window. Ranking Provide relevant results by using the FREETEXTTABLE function and limit your results to rows with LanguageID = 'en' (for English). and click SQL Server Management Studio. 13. your manager would like you to help provide a more natural interface for your users. click Open. In Solution Explorer. This will involve creating a new stored procedure. In the virtual machine. click All Programs. Supporting Documentation Stored Procedure Specifications Name Input Parameters Output Parameters Columns Returned Marketing. 15. type Proseware in the Server name text box. select Windows Authentication and click Connect. If the Server Manager window appears. click Execute on the toolbar. 11. In the Open Project window. open the project D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ. You are intending to use full-text indexing to address these complaints. 12. In Connect to Server window. and click Project/Solution. In the File menu. double-click the query 00-Setup.20-34 Implementing a Microsoft® SQL Server® 2008 R2 Database • Log on using the following credentials: i. click Full Screen Mode.ProductDescription table to improve this situation. From the View menu. If you have time. You will implement a full-text index on the Marketing. Description. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. check the Do not show me this console at logon check box and close the Server Manager window. When the query window opens. In the Authentication drop-down list box. 14.

 Task 5: Write a simple CONTAINS query • Write a query to search for ProductDescriptionID and Description where the Description column contains the word “bottle”. Look in particular at the has_crawl_completed column.ProductDescription table. Check to see that the population of the index is complete.  Task 6: Write a CONTAINS query that searches for two words • Write a query to search for ProductDescriptionID and Description where the Description column contains the words. Ensure that the catalog is set as the default full-text catalog. Enable automatic change tracking for the index. “elastic” and “lycra”.ProductDescription table • • • Execute T-SQL statements to create a full-text index on the Description column of the Marketing.ProductDescription table. Results: After this exercise. Write a CONTAINS query that uses INFLECTIONAL forms. Write a CONTAINS query that searches for two words. you should have created and tested a full-text index.  Task 2: Create a full-text index on the Description column of the Marketing. . Create a full-text catalog. 3. Create a full-text index on the Description column of the Marketing. Write a simple CONTAINS query.ProductDescription table to improve the searching abilities. Specify the primary key of the table as the key index.  Task 4: Check to see that the population of the index is complete • • Query the sys.Working with Full-Text Indexes and Queries 20-35 Exercise 1: Implement a full-text index Scenario In this exercise. 6. 2. 7. you will implement a full-text index on the Marketing.  Task 3: Enable automatic change tracking for the index • Execute T-SQL statements to enable automatic change tracking for the table.  Task 7: Write a CONTAINS query that uses INFLECTIONAL forms • Write a query to search for ProductDescriptionID and Description where the Description column contains inflectional forms of the word “wash”. 4.fulltext_indexes system view to determine if the population is complete. The main tasks for this exercise are as follows: 1. 5.  Task 1: Create a full-text catalog • • Execute T-SQL statements to create a new full-text catalog called DefaultFullTextCatalog. Initially configure change tracking and population off.

 Task 1: Review the existing system stopwords • Review the existing system stopwords by querying the view sys.fulltext_stoplists and sys.  Task 3: Add words to the stoplist • Add the words.20-36 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 2: Implement a stoplist Scenario In this exercise. you should have created a new stoplist that will help avoid excessive index size growth. View the stoplist. 4. The main tasks for this exercise are as follows: 1. Review the existing system stopwords.  Task 4: View the stoplist • View the new stoplist by querying the sys. 3. 2. (English)  Task 2: Create a full-text stoplist • Create a full-text stoplist called “CommonWords”. Results: After this exercise. “Bike” and “AdventureWorks” to the stoplist for the English language. Create a full-text stoplist. you will implement a stoplist to avoid excessive unnecessary index size. .fulltext_system_stopwords for language_id 1033. Add words to the stoplist.fulltext_stopwords views.

ProductDescription table.Working with Full-Text Indexes and Queries 20-37 Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits) Scenario In this exercise. Rows are returned where they are considered relevant. The procedure Marketing. Design. implement. In this exercise. you want to provide a more natural interface for your users. • Results: After this exercise. implement.GetRelevantDescriptions takes an input search term and returns the specified columns from the Marketing. and test the stored procedure. you should have created a new stored procedure and tested its behavior.  Task 1: Review the supporting documentation • The supporting documentation includes specifications for the design of a new stored procedure.  Task 2: Design. based on the FREETEXTTABLE function and the English language. 2. Review the supporting documentation. you will create a stored procedure that implements a more advanced type of search. and test the stored procedure • Design and implement the stored procedure. . Test the stored procedure using the search phrases 'strong frame' and 'serious competition'. The main tasks for this exercise are as follows: 1.

2. 4. any words that are used in almost all your company documents. . based on full-text indexes in SQL Server. Use auto-population of indexes except in rare cases with specific issues. 3. Create a stoplist for your company. 2. (These situations would typically involve data that is updated at a high rate and where the index does not need to be kept completely up to date). What is the function of a stopword? What are iFilters used for? What is the difference between FREETEXT and FREETEXTTABLE? How do you configure a thesaurus for use with full-text indexing? Best Practices 1. Try to encourage developers in your organization to offer much more flexible user interfaces to your end users.20-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. Add to the stoplist. 3.

Working with Full-Text Indexes and Queries 20-39 Course Review and Evaluation .

20-40 Implementing a Microsoft® SQL Server® 2008 R2 Database .

click the Ctrl-Alt-Delete menu item. In the Virtual Machine Connection window. if the user is not already logged on: • • • On the Action menu. In the Virtual Machines list. and then close the Virtual Machine Connection window. you must complete the following steps: 1. point to Administrative Tools. Click Switch User. click All Programs. ensure that the following services are listed for the MKTG instance: • • • • SQL Server (MKTG) SQL Full-text Filter Daemon Launcher (MKTG) SQL Server Reporting Services (MKTG) SQL Server Agent (MKTG) . On the host computer. Before you begin the lab. In the left-hand pane of the SQL Server Configuration Manager window. In the Virtual Machine Connection window. in the Virtual Machine Connection window. click Configuration Tools. 2. 3. 9. and then click Other User. wait until the Press CTRL+ALT+DELETE to log on message appears. if the virtual machine 623XB-MIA-SQL1 is not started: • • • Right-click 623XB-MIA-SQL1 and click Start. 6. click Revert. 3. From the View menu. Log on using the following credentials: • • User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. wait until the Press CTRL+ALT+DELETE to log on message appears. Right-click 623XB-MIA-DC and click Start. 5. In the Virtual Machines list. In the right-hand pane.Lab: Introduction to SQL Server and its Toolset L1-1 Module 1: Introduction to SQL Server 2008 R2 and its Toolset Lab: Introduction to SQL Server and its Toolset Lab Setup For this lab. If the Server Manager window appears. 2. In the Virtual Machine Connection window. Right-click 623XB-MIA-DC and click Connect. Wait for the revert action to complete. Right-click 623XB-MIA-SQL1 and click Connect. 7. click Full Screen Mode. Click Start. check the Do not show me this console at logon check box and close the Server Manager window. If you are prompted to confirm that you want to revert. click SQL Server Services. click Start. if the virtual machine 623XB-MIA-DC is not started: • • • 4. click Microsoft SQL Server 2008 R2. and then click Hyper-V Manager. click on the Revert toolbar icon. In Virtual Machine Connection window. Exercise 1: Verify SQL Server Component Installation f Task 1: Check that Database Engine and Reporting Services have been installed for the MKTG instance 1. you will use the available virtual machine environment. and then click SQL Server Configuration Manager. Maximize the Hyper-V Manager window.

Check that the SQL Server Agent (MSSQLSERVER) service has Start Mode set to Automatic. ensure that the following services are listed for the default instance: • • • • 3. note that SQL Server Integration Services 10. Check that all the services for the default instance have a Start Mode of Automatic. In the Log On tab. Ignore the SQL Full-text Filter Daemon Launcher service at this time. 5. In the right-hand pane. click Start and the SQL Server Agent service should start. . Check that all the services for the MKTG instance have a Start Mode of Automatic. 6. SQL Server (MSSQLSERVER) SQL Full-text Filter Daemon Launcher (MSSQLSERVER) SQL Server Analysis Services (MSSQLSERVER) SQL Server Agent (MSSQLSERVER) In the right-hand pane.0 is not installed as a perinstance basis as there is no instance name shown. Note: The SQL Server Agent (MSSQLSERVER) service is not set to autostart. In the Log On tab. In the left-hand pane of the SQL Server Configuration Manager window. f Task 2: Note the services that are installed for the default instance and that Integration Services is not installed on a per instance basis 1. 4. 2. 3. 2. and then click OK. Note: The SQL Server Agent (MKTG) service is not set to autostart. click Start and the SQL Server Agent service should start. 8. Right-click the SQL Server Agent (MKTG) service and click Properties.L1-2 Lab: Introduction to SQL Server and its Toolset Note: The SQL Full-text Filter Daemon Launcher is present and it is part of the Database Engine. set the value for the Start Mode to Automatic. f Task 3: Ensure that all required services including SQL Server Agent are started and set to autostart for both instances 1. click SQL Server Services. 7. Ignore the SQL Full-text Filter Daemon Launcher service at this time. In the Service tab. Right-click the SQL Server Agent (MSSQLSERVER) service and click Properties.

6. Right-click SQL Server Agent (MTKG) and select Start to restart the service. type Pa$$w0rd. right-click Named Pipes and select Enable. expand SQL Server Network Configuration and then click Protocols for MSSQLSERVER. type Pa$$w0rd and click OK. In the Account Name text box. type Pa$$w0rd and click OK. set the value for the Start Mode to Automatic. 5. The SQL Server Services need to be configured as the screenshot below: Exercise 2: Alter Service Accounts for New Instance f Task 1: Change the service account for the MKTG database engine 1. In the left-hand pane of the SQL Server Configuration Manager window. f Task 2: Enable the named pipes protocol for the MKTG instance 1. 3. In the Password text box. . In the Confirm Password text box. right-click SQL Server Agent (MTKG). and then click OK. In the left-hand pane of the SQL Server Configuration Manager window. click SQL Server Services. In the Password text box. 5. In the right-hand pane. 2. 2. right-click SQL Server (MTKG). click OK.Lab: Introduction to SQL Server and its Toolset L1-3 9. f Task 2: Change the service account for the MKTG SQL Server Agent 1. In the Service tab. type Pa$$w0rd. 4. In the Warning window. click Yes. In the left-hand pane of the SQL Server Configuration Manager window. type AdventureWorks\PWService. In the right-hand pane. In the left-hand pane of the SQL Server Configuration Manager window. In the right-hand pane. In the Confirm Password text box. click Protocols for MKTG. 2. 3. and select Properties. click SQL Server Services. 6. In the Confirm Account Change window. and select Properties. Exercise 3: Enable Named Pipes Protocol for Both Instances f Task 1: Enable the named pipes protocol for the default instance 1. In the Account Name text box. 10. 3. type AdventureWorks\PWService. 4.

f Task 3: Restart both database engine services 1. expand SQL Native Client 10. In the left-hand pane of the SQL Server Configuration Manager window. click SQL Server Services. right-click Aliases and select New Alias. In the Warning window. . 4. 4. click OK. f Task 2: Create a 32-bit alias (Proseware) for the MKTG instance 1.0 Configuration (32bit) and click Client Protocols. Right-click SQL Server (MSSQLSERVER) and select Restart. f Task 3: Create a 64-bit alias (AdventureWorks) for the default instance 1. in the Alias Name text box. 5. select Named Pipes. In the left-hand pane of the SQL Server Configuration Manager window.L1-4 Lab: Introduction to SQL Server and its Toolset 2. 4. 3. Confirm that the Named Pipes protocol is Enabled. In the left-hand pane.\MKTG and click OK. In the Server text box. type . 3. Right-click SQL Server (MKTG) and select Restart. In the Server text box. 5. 5. in the Alias Name text box. 6. 3. select Named Pipes. right-click Named Pipes and select Enable. type . 3. In the Alias – New window. right-click Aliases and select New Alias. click the Refresh icon. 4. 6. In the right-hand pane. In the left-hand pane of the SQL Server Configuration Manager window. expand SQL Native Client 10. expand SQL Native Client 10. type AdventureWorks. Confirm that the Named Pipes protocol is Enabled. Confirm that the Named Pipes protocol is Enabled. In the toolbar. right-click Aliases and select New Alias. type Proseware. and click OK. In the left-hand pane of the SQL Server Configuration Manager window. and click OK. in the Alias Name text box. In the Protocol drop-down list box. In the left-hand pane. In the left-hand pane of the SQL Server Configuration Manager window. In the Alias – New window. In the Protocol drop-down list box.0 Configuration and click Client Protocols. type .0 Configuration (32bit) and click Client Protocols. 5. In the left-hand pane of the SQL Server Configuration Manager window. type AdventureWorks. In the left-hand pane. 2. expand SQL Native Client 10. In the Server text box. Exercise 4: Create Aliases for AdventureWorks and Proseware f Task 1: Create a 32-bit alias (AdventureWorks) for the default instance 1. f Task 4: Create a 64-bit alias (Proseware) for the MKTG instance 1. 3. click SQL Server Services. select Named Pipes. 6.0 Configuration and click Client Protocols. In the Alias – New window. 2. In the Protocol drop-down list box. 2. 2.

and AdventureWorksDW2008R2. select Named Pipes. and then click SQL Server Configuration Manager. In the Protocol drop-down list box. and click Connect. In the Virtual Machine window. 2.Lab: Introduction to SQL Server and its Toolset L1-5 2. type AdventureWorks. type Proseware. In the TCP/IP Properties window. 5. Right-click the TCP/IP protocol and select Properties. 2. Close SQL Server Configuration Manager. Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits) f Task 1: Configure the TCP port for the MKTG database engine instance to 51550 1. select Windows Authentication. 3. Scroll to the bottom of the screen. In the Server name text box. 5. 5. Database Snapshots. 4. and ReportServer$MKTGTempDB. 6. 8. 9. ensure that Server Type is set to Database Engine. and then click SQL Server Management Studio. click Start. In the Authentication drop-down list. type . click All Programs.\MKTG and click OK. Note: The databases that are present include at least the following: System Databases. click All Programs. 10. under AdventureWorks expand Databases. In the Authentication drop-down list. 4. click Database Engine. In the Server name text box. click Microsoft SQL Server 2008 R2. In the left-hand pane of the SQL Server Configuration Manager window. 6. 3. In Object Explorer. Close SQL Server Management Studio. under the IPAll section. Confirm that the Named Pipes protocol is Enabled. In the Server text box. 12. Database Snapshots. right-click Aliases and select New Alias. AdventureWorks2008R2. clear the value for TCP Dynamic Ports. In the Connect to Server window. select Windows Authentication. In the Connect to Server window. From the Start menu. click Microsoft SQL Server 2008 R2. . Click Start. expand SQL Server Network Configuration and then click Protocols for MKTG. ReportServer$MKTG. in the Alias Name text box. type Proseware. 11. 6. 4. In Object Explorer. under Proseware expand Databases. In Object Explorer. In the left-hand pane. f Task 5: Use SQL Server Management Studio to connect to both aliases to ensure they work as expected 1. 7. Note: The databases that are present include at least the following: System Databases. and click Connect. ensure that Server Type is set to Database Engine. click IP Addresses tab. In the Alias – New window. click Configuration Tools. click Connect. 3.

L1-6 Lab: Introduction to SQL Server and its Toolset 7. 9. right-click SQL Server Browser and click Stop. f Task 2: Disable the SQLBrowser service 1. In the Warning window. 11. . click OK. click SQL Server Services. click SQL Server Services. In the left-hand pane of the SQL Server Configuration Manager window. Right-click the SQL Server Browser and click Properties. click SQL Server Services. In the right-hand pane. In the SQL Server Browser Properties window. 4. type 51550. in the Service tab. 2. In the left-hand pane of the SQL Server Configuration Manager window. 12. 8. 10. click the Refresh icon and make sure the service starts. Right-click SQL Server (MKTG) and select Restart. set the Start Mode to Disabled and click OK. In the left-hand pane. In the toolbar. 3. For TCP Port. and click OK.

In the Virtual Machines list. In the File menu. Exercise 1: Choosing Appropriate Data Types f Task 1: Determine column names and data types 1. click Full Screen Mode. When the query window opens. click the Ctrl-Alt-Delete menu item. • In the Virtual Machine Connection window. type Proseware in the Server name text box. If you are prompted to confirm that you want to revert. From the View menu. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. Before you begin the lab. in the Virtual Machine Connection window. 10. Opportunity and SpecialOrder tables and determine column names. Password: Pa$$w0rd 8. and click Project/Solution. • Right-click 623XB-MIA-SQL and click Connect. click on the Revert toolbar icon. double-click the query 00-Setup. data types. Maximize the Hyper-V Manager window. Review the supporting documentation for details of the PhoneCampaign. . and then close the Virtual Machine Connection window.Lab: Working with Data Types L2-1 Module 2: Working with Data Types Lab: Working with Data Types Lab Setup For this lab. 4. 2. point to Administrative Tools. 15. select Windows Authentication and click Connect.sql. 12. 13. and then click Other User. 14. wait until the Press CTRL+ALT+DELETE to log on message appears. and click SQL Server Management Studio. In Virtual Machine Connection window. and then click Hyper-V Manager. • Click Switch User. click Open. In Solution Explorer. In the virtual machine. if the user is not already logged on: • On the Action menu. User name: AdventureWorks\Administrator ii. • In the Virtual Machine Connection window. click All Programs. If the Server Manager window appears. you will use the available virtual machine environment. In the Virtual Machine Connection window. click Start. wait until the Press CTRL+ALT+DELETE to log on message appears. check the Do not show me this console at logon check box and close the Server Manager window. 6. 5. Wait for the revert action to complete. In the Virtual Machines list. click Start. you must complete the following steps: On the host computer. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. In Connect to Server window. 7. 3. 9. In the Authentication drop-down list box. 11. and nullability for each data item in the design. click Microsoft SQL Server 2008 R2. • Right-click 623XB-MIA-DC and click Connect. click Execute on the toolbar. open the project D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ. 1.ssmssln. click Revert. • Log on using the following credentials: i. In the Open Project window.

Contract Negotiations.L2-2 Lab: Working with Data Types Note: With any design exercise. Hot Estimated closing date Estimated revenue Delivery address Table 3: SpecialOrder Description Which prospect this order is for Column Name and Data Type ProspectID INT NOT NULL Column Name and Data Type OpportunityID INT NOT NULL ProspectID INT NOT NULL SalesStageCode CHAR(2) NOT NULL InitialContact DATETIME NULL ContactOutcomeCode CHAR(1) NULL SalesValue DECIMAL(10. Table 1: PhoneCampaign Description Which campaign this relates to. Qualification. if it ContactComments NVARCHAR(MAX) NULL was made. Column Name and Data Type PhoneCampaignID INT NOT NULL ProspectID INT NOT NULL FirstAttemptedContact DATETIME NULL Comments related to the contact that was made.2) NULL DateRaised DATETIME NOT NULL Likelihood TINYINT NOT NULL Rating CHAR(1) NOT NULL EstimatedClosingDate DATE NOT NULL EstimatedRevenue DECIMAL(10. Complete. The prospect that was contacted. Outcome of the contact: sale. there is no one correct answer. later follow-up or no interest Value of any sale made (up to 2 decimal places) Table 2: Opportunity Description Name of the opportunity Which prospect this opportunity relates to Stage the sale is at: Lead.2) NOT NULL DeliveryAddress NVARCHAR(MAX) NOT NULL . When contact was first attempted with the prospect. Lost Date that the opportunity was raised Probability of success Rating: Cold. Proposal Development. When contact was actually made with the prospect. A sample solution has been provided below. Warm.

Right-click the MarketDev database and click New Query. 3. 2. f Task 3: Review the second query requirement and write a SELECT statement to meet the requirement 1. In Object Explorer. 2. In the toolbar. expand the Databases under Proseware. 6. expand the Databases under Proseware. Review the supporting documentation for details for the first query requirement. Review the supporting documentation for details for the second query requirement. 4. Right-click the MarketDev database and click New Query. click Execute. 2. In Object Explorer. . some are fractional with up to 3 decimal places) Date of order Promised delivery date Actual delivery date Column Name and Data Type SupplierID INT NOT NULL ItemDescription NVARCHAR(100) NOT NULL QuantityRequired DECIMAL(10. In Object Explorer. Ensure that the results from the query match the required output as shown in the supporting documentation.3) NOT NULL OrderDate DATETIME NOT NULL PromisedDeliveryDate DATE NOT NULL ActualDeliveryDate DATE NULL Special requirements (any comments related to the SpecialRequirements NVARCHAR(MAX) NULL special order) Quoted price per unit (up to 2 decimal places) QuotedPricePerUnit DECIMAL(10.Product. expand the Databases under Proseware.112) AS SellEndDate FROM Marketing.2) NOT NULL Exercise 2: Writing Queries With Data Type Conversions f Task 1: Connect to the MarketDev Database 1. GO 5. Type the query below in the query pane: SELECT ProductID.Lab: Working with Data Types L2-3 Description External supplier of the item Description of the item Quantity Required (some quantities are whole numbers. ProductName. f Task 2: Review the first query requirement and write a SELECT statement to meet the requirement 1. CONVERT(varchar(8).SellEndDate.

6. and expand MarketDev. Ensure that the results from the query match the required output as shown in the supporting documentation. and expand Tables. click Execute. . 2.Prospect Marketing. In Object Explorer.Prospect Marketing. click Execute. In the Object Explorer. Right-click the MarketDev database and click New Query. The following columns should be identified: Table Marketing. 3.Prospect Marketing. expand the Databases under Proseware. GO 4. expand Columns. f Task 3: Create a data type that stores email addresses 1. Type the query below in the query pane: SELECT ProspectID. expand the Databases under Proseware. GO 5. In each table. noting any columns that are holding details of Phone Numbers or Email Addresses. Right-click the MarketDev database and click New Query. expand Databases. CAST(Demographics AS nvarchar(1000)) AS Demographics FROM Marketing. 4. Type the query below in the query pane: CREATE TYPE PhoneNumber FROM nvarchar(25).Prospect.L2-4 Lab: Working with Data Types 3.Prospect Phone Number Columns CellPhoneNumber HomePhoneNumber WorkPhoneNumber Definition NVARCHAR(20) NVARCHAR(25) VARCHAR(22) Table Marketing. Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits) f Task 1: Investigate the storage of phone numbers and email addresses 1. In the toolbar. 2. In the toolbar. 2. Right-click the MarketDev database and click New Query.SalesPerson Email Address Columns EmailAddress EmailAlias Definition NVARCHAR(100) NVARCHAR(256) f Task 2: Create a data type that stores phone numbers 1. In Object Explorer.

Type the query below in the query pane: CREATE TYPE EmailAddress FROM nvarchar(256). click Execute . In the toolbar. GO 4.Lab: Working with Data Types L2-5 3.

L2-6 Lab: Working with Data Types .

In Connect to Server window. click Microsoft SQL Server 2008 R2. if the user is not already logged on: • On the Action menu. click All Programs. • In the Virtual Machine Connection window. and then click Hyper-V Manager. • Right-click 623XB-MIA-DC and click Connect. and click SQL Server Management Studio. In the Authentication drop-down list box. A sample solution has been provided below. 7. If the Server Manager window appears. 2. double-click the query 00-Setup. click Open. and click Project/Solution. In the virtual machine. 4. f Task 2: Suggest an improved design Note: With any design exercise. click Start. In the File menu. and then close the Virtual Machine Connection window. click Execute on the toolbar. In the Virtual Machines list.sql. 12. • In the Virtual Machine Connection window. 14. Review the supplied design in the supporting documentation for the exercise. 6. . User name: AdventureWorks\Administrator ii. • Log on using the following credentials: i. Wait for the revert action to complete. click Revert. open the project D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ. wait until the Press CTRL+ALT+DELETE to log on message appears. From the View menu. Password: Pa$$w0rd 8. 15. 3. click on the Revert toolbar icon. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. 1. 11. 10. click Start. point to Administrative Tools. and then click Other User. wait until the Press CTRL+ALT+DELETE to log on message appears. If you are prompted to confirm that you want to revert. 5.Lab: Designing and Implementing Tables L3-1 Module 3: Designing and Implementing Tables Lab: Designing and Implementing Tables Lab Setup For this lab.ssmssln. In the Virtual Machine Connection window. In Virtual Machine Connection window. click Full Screen Mode. 13. you will use the available virtual machine environment. click the Ctrl-Alt-Delete menu item. In Solution Explorer. In the Open Project window. type Proseware in the Server name text box. • Right-click 623XB-MIA-SQL and click Connect. • Click Switch User. 9. Maximize the Hyper-V Manager window. check the Do not show me this console at logon check box and close the Server Manager window. In the Virtual Machines list. When the query window opens. Before you begin the lab. Exercise 1: Improve the Design of Tables f Task 1: Review the supplied design 1. in the Virtual Machine Connection window. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. there is no one correct answer. select Windows Authentication and click Connect. you must complete the following steps: On the host computer.

L3-2 Lab: Designing and Implementing Tables Table1: Competitor (Table name change to singular to match existing singular table names in the database) Name CompetitorID Data Type INT NOT NULL CompetitorName NVARCHAR(30) NOT NULL NVARCHAR(max) NOT NULL DATE NOT NULL The column name “Name” is too generic Unicode data type for flexibility Common to have multiple addresses Unicode data type for flexibility Removed underscore for consistency Chose appropriate data type Renamed for consistency Note: Suspect this should be a code or a number but would require more information from Business Analyst Unicode data type for flexibility Comments NVARCHAR(max) NULL Unicode data type for flexibility NULL because there may be no comments Table2A: City (Duplicated City details extracted from the original table called TVAdvertisements) Name CityID Data Type INT NOT NULL CityName NVARCHAR(25) NOT NULL Renamed original column Retained data type where no further information is available Design Rationale Added a surrogate key Design Rationale Prefer numeric code for surrogate keys StreetAddress DateEntered StrengthOfCompetitio NVARCHAR(8) n NOT NULL Table2B: TVStation (Duplicated TV Station details extracted from the original table called TVAdvertisements) Name TVStationID Data Type INT NOT NULL NVARCHAR(15) NOT NULL Design Rationale Added a surrogate key TVStationName Renamed original column Retained data type where no further information is available .

Lab: Designing and Implementing Tables L3-3 Name CityID Data Type INT NOT NULL DECIMAL(12.2) NOT NULL Design Rationale City details extracted to a separate table CostPerAdvertisement Chose appropriate data type TotalCostOfAllAdvertisements removed as it should be calculated NumberOfAdvertisements removed as it should be calculated Table2C: TVAdvertisement (Extracted repeating groups from the original table called TVAdvertisements) Name TVAdvertisementID Data Type INT NOT NULL INT NOT NULL DATETIME NOT NULL Design Rationale Added a surrogate key TVStationID Reference to TV Station table ScreeningTime Single data type to hold both values Name to reflect combination of values Table3: CampaignResponse (Table name change to singular to match existing singular table names in the database and removed underscore for consistency) Name TVAdvertisementID ResponseReceived ProspectID Data Type INT NOT NULL DATETIME NOT NULL INT NOT NULL Design Rationale Added a surrogate key Improved column name Reference to existing Prospect table Changed to a straightforward code using first letter An alternative would be to extract the response method as another lookup table Chose appropriate data type Chose appropriate data type ResponseProfit should be removed as it should be calculated rather than stored in the table ResponseMethodCode CHAR(1) NOT NULL ChargeFromReferrer RevenueReceived DECIMAL(12.2) NOT NULL .2) NOT NULL DECIMAL(12.

Type the query below in the query pane: Note: The sample query below is based on the sample solution. Right-click the MarketDev database and click New Query. StrengthOfCompetition NVARCHAR(8) NOT NULL. TVStationID INT NOT NULL. StreetAddress NVARCHAR(MAX) NOT NULL. GO . GO CREATE TABLE DirectMarketing. The solution shown below is contained in the 71 – Lab Exercise 3. In the toolbar. Challenge Exercise 3: Create the Tables (Only if time permits) f Task 1: Create the tables 1. GO 2. CityID INT NOT NULL. f Task 2: Create a schema named DirectMarketing 1. 3.Competitor ( CompetitorID INT NOT NULL PRIMARY KEY. TVStationName NVARCHAR(15) NOT NULL.City ( CityID INT NOT NULL PRIMARY KEY. In Object Explorer.2) NOT NULL ). ScreeningTime DATETIME NOT NULL ). GO CREATE TABLE DirectMarketing. Type the query below in the query pane: CREATE SCHEMA DirectMarketing AUTHORIZATION dbo.TVAdvertisement ( TVAdvertisementID INT NOT NULL PRIMARY KEY. Right-click the MarketDev database and click New Query. CityName NVARCHAR(25) NOT NULL ). In Object Explorer. CompetitorName NVARCHAR(30) NOT NULL.L3-4 Lab: Designing and Implementing Tables Exercise 2: Create a Schema f Task 1: Connect to the MarketDev Database 1. 2. Your query should be based on your design.sql script file in Solution Explorer. click Execute. expand the Databases under Proseware. 2. GO CREATE TABLE DirectMarketing. CREATE TABLE DirectMarketing. CostPerAdvertisement DECIMAL(12. DateEntered DATE NOT NULL. expand the Databases under Proseware.TVStation ( TVStationID INT NOT NULL PRIMARY KEY. Comments NVARCHAR(MAX) NULL ).

RevenueReceived DECIMAL(12. click Execute. In the toolbar. ResponseMethodCode CHAR(1) NOT NULL.2) NOT NULL ).CampaignResponse ( CampaignResponseID INT NOT NULL PRIMARY KEY.Lab: Designing and Implementing Tables L3-5 CREATE TABLE DirectMarketing. ProspectID INT NOT NULL. ResponseReceived DATETIME NOT NULL.2) NOT NULL. . ChargeFromReferrer DECIMAL(12. GO 4.

L3-6 Lab: Designing and Implementing Tables .

Lab: Designing and Implementing Views L4-1 Module 4: Designing and Implementing Views Lab: Designing and Implementing Views Lab Setup For this lab. click Open. In the Authentication drop-down list box. click the Ctrl-Alt-Delete menu item. 5. 2. point to Administrative Tools. click on the Revert toolbar icon. click Start. 13. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. GO . click Full Screen Mode. • Click Switch User. wait until the Press CTRL+ALT+DELETE to log on message appears.sql. and then close the Virtual Machine Connection window. 9. click Execute on the toolbar. 12. When the query window opens. 1. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. and click SQL Server Management Studio. 6. Implement and Test the WebStock Views f Task 1: Create the WebStock schema 1. 11. In the Virtual Machines list. double-click the query 00-Setup. Before you begin the lab. In the Open Project window. In the File menu. Password: Pa$$w0rd 8. select Windows Authentication and click Connect. you will use the available virtual machine environment. In the virtual machine. • Right-click 623XB-MIA-DC and click Connect. Type the query below in the query pane: CREATE SCHEMA WebStock AUTHORIZATION dbo. wait until the Press CTRL+ALT+DELETE to log on message appears. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. • In the Virtual Machine Connection window. Wait for the revert action to complete. click Microsoft SQL Server 2008 R2. In Connect to Server window. Right-click the MarketDev database and click New Query. 14. if the user is not already logged on: • On the Action menu. 2. User name: AdventureWorks\Administrator ii. If the Server Manager window appears. open the project D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ. 3. and then click Hyper-V Manager. click Start. In the Virtual Machines list. click All Programs. In Solution Explorer. • Right-click 623XB-MIA-SQL and click Connect. • Log on using the following credentials: i. check the Do not show me this console at logon check box and close the Server Manager window. 7. 3. • In the Virtual Machine Connection window. and then click Other User. 15. type Proseware in the Server name text box. In Object Explorer. and click Project/Solution. 4. Exercise 1: Design. in the Virtual Machine Connection window. click Revert. If you are prompted to confirm that you want to revert. 10. In Virtual Machine Connection window. expand the Databases under Proseware.ssmssln. you must complete the following steps: On the host computer. From the View menu.

f Task 2: Review the design requirements 1.'N/A') AS Color.ProductModel FROM Marketing. Review the supplied design in the supporting documentation for the OnlineProducts and AvailableModels views.SellEndDate IS NULL AND p. pm. Right-click the MarketDev database and click New Query. f Task 3: Design and implement the views 1. click Execute.ProductModelID. Type the query below in the query pane: CREATE VIEW WebStock. COALESCE(p. In the toolbar.ProductModel AS pm ON p. p.L4-2 Lab: Designing and Implementing Views 4.ProductModelID WHERE p. GO 3. GO SELECT * FROM WebStock. GO 3. GO CREATE VIEW WebStock.ProductID.ProductModelID = pm. In the toolbar. p.ListPrice AS Price. p.AvailableModels AS SELECT p. pm. Type the query below in the query pane: SELECT * FROM WebStock.AvailableModels.OnlineProducts AS SELECT p. In the toolbar. CASE p.ProductID. f Task 4: Test the views 1.Product AS p WHERE p.SizeUnitMeasureCode AS UnitOfMeasure. p.SellStartDate IS NOT NULL. click Execute.ProductNumber.DaysToManufacture WHEN 0 THEN 'Instock' WHEN 1 THEN 'Overnight' WHEN 2 THEN 'Fast' ELSE 'Call' END AS Availability. p. .ProductName. p.Product AS p INNER JOIN Marketing.Size.OnlineProducts.SellStartDate IS NOT NULL. 2. Right-click the MarketDev database and click New Query. 2.ProductName.SellEndDate IS NULL AND p.Weight FROM Marketing.Color. p. click Execute.

sp.Lab: Designing and Implementing Views L4-3 Exercise 2: Design and Implement the Contacts View f Task 1: Create the Relationship schema 1.SalespersonID. Right-click the MarketDev database and click New Query. 2. f Task 2: Review the design requirements 1.Contacts AS SELECT p. Review the supplied design in the supporting documentation for the Contacts view.Contacts. p. 3. In Object Explorer. Right-click the MarketDev database and click New Query. Type the query below in the query pane: . sp.ProspectID AS ContactID. expand the Databases under Proseware. f Task 3: Design and implement the view 1. GO 3. GO 4.MiddleName.MiddleName.Salesperson AS sp. sp. 2.Prospect AS p UNION ALL SELECT sp. Challenge Exercise 3: Modify the AvailableModels View (Only if time permits) f Task 1: Alter the AvailableModels View 1. Type the query below in the query pane: CREATE SCHEMA Relationship AUTHORIZATION dbo.LastName. click Execute. Type the query below in the query pane: SELECT * FROM Relationship.FirstName. 2. f Task 4: Test the view 1.FirstName. Right-click the MarketDev database and click New Query. p. p. In the toolbar. In the toolbar. click Execute. GO 3. Type the query below in the query pane: CREATE VIEW Relationship. 2. In the toolbar. 'SALESPERSON' FROM Marketing. 'PROSPECT' AS ContactRole FROM Marketing. Right-click the MarketDev database and click New Query. click Execute.LastName.

In the toolbar.SellEndDate IS NULL AND p. This page intentionally left blank .LanguageID = '' WHERE p.ProductDescription AS ed ON pm.ProductModelID = id. p.Description) AS CatalogDescription FROM Marketing.LanguageID = 'en' LEFT OUTER JOIN Marketing.ProductModelID AND ed.ProductName. click Execute.id. 4. In the toolbar.AvailableModels AS SELECT p. f Task 2: Test the view 1.ProductModelID LEFT OUTER JOIN Marketing. GO 3. GO 3.ProductModelID = ed.ProductModelID AND id. 2.ProductModel AS pm ON p.SellStartDate IS NOT NULL. pm.AvailableModels.L4-4 Lab: Designing and Implementing Views ALTER VIEW WebStock.ProductModelID = pm.Description. Type the query below in the query pane: SELECT * FROM WebStock. Right-click the MarketDev database and click New Query. pm.ProductModel.Product AS p INNER JOIN Marketing. click Execute. COALESCE(ed.ProductModelID.ProductID.ProductDescription as id ON pm.

• Log on using the following credentials: i. In the Virtual Machine Connection window. expand the Databases under Proseware. 14. In the File menu. Before you begin the lab. double-click the query 00-Setup. If you are prompted to confirm that you want to revert. In Connect to Server window. In the Open Project window. you must complete the following steps: 1. select Windows Authentication and click Connect. In the virtual machine.  In the Virtual Machines list. point to Administrative Tools. 7. • Right-click 623XB-MIA-DC and click Connect. click All Programs. In Solution Explorer. • Right-click 623XB-MIA-SQL and click Connect. 10. 6. click Start. Exercise 1: Explore existing index statistics f Task 1: Execute SQL Command 1. open the project D:\6232B_Labs\6232B_05_PRJ\6232B_05_PRJ. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. When the query window opens. click Revert. In the Virtual Machine Connection window. 12. in the Virtual Machine Connection window. . 2. and then click Other User. 2. Right-click the MarketDev database and click New Query. 9. check the Do not show me this console at logon check box and close the Server Manager window. In Object Explorer.ssmssln. click the Ctrl-Alt-Delete menu item.sql. Maximize the Hyper-V Manager window. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. if the user is not already logged on: • On the Action menu. Password: Pa$$w0rd  From the View menu. Wait for the revert action to complete. 11. click Full Screen Mode. and then click Hyper-V Manager. and then close the Virtual Machine Connection window. click Open. In Virtual Machine Connection window. User name: AdventureWorks\Administrator • 4. you will use the available virtual machine environment. and click SQL Server Management Studio. click Microsoft SQL Server 2008 R2. wait until the Press CTRL+ALT+DELETE to log on message appears. 8. • In the Virtual Machine Connection window. In the Virtual Machines list. 13. wait until the Press CTRL+ALT+DELETE to log on message appears. type Proseware in the Server name text box. ii. 15. If the Server Manager window appears. • Click Switch User. click Execute on the toolbar. and click Project/Solution. 3. click on the Revert toolbar icon. On the host computer. In the Authentication drop-down list box.Lab: Planning for SQL Server Indexing L5-1 Module 5: Planning for SQL Server 2008 R2 Indexing Lab: Planning for SQL Server Indexing Lab Setup For this lab. 5. click Start.

Type the query below in the query pane: CREATE STATISTICS Product_Color_Stats ON Marketing.Product_Color_Stats). click Execute. Type the query below in the query pane: DBCC SHOW_STATISTICS('Marketing. Note: The results returned can vary. If any autostats have been created. f Task 2: Review the results 1. Complete the answer column in the table below. click Execute. f Task 5: Use DBCC SHOW_STATISTICS 1. In the toolbar. f Task 6: Answer questions 1. f Task 4: Re-execute the SQL command from task 1 1. GO 3.Product’ GO 3.L5-2 Lab: Planning for SQL Server Indexing 3. Right-click the MarketDev database and click New Query. they will appear in the results with an _WA prefix. In the toolbar. In the Query Analyzer Results pane. 2.Product’ GO 4. In the toolbar. Type the query below in the query pane: EXEC sp_helpstats ‘Marketing. 2. Type the query below in the query pane: EXEC sp_helpstats ‘Marketing. Right-click the MarketDev database and click New Query.Product (Color) WITH FULLSCAN. f Task 3: Create statistics 1. 2. In the toolbar. GO 3.Product'. Check to see if any autostats has been generated. review the results. click Execute. Right-click the MarketDev database and click New Query. click Execute. Sample results are shown in the following table . 2.

. GO 5. 2. Type the query below in the same query pane: -. FirstName. Note: A sample result would be 19955 4. Highlight only Query 1 and click Execute. click Execute. Type the query below in the query pane: SELECT COUNT(1) FROM Marketing. 2.Prospect WHERE FirstName LIKE 'Alejandro%'. LastName FROM Marketing.Lab: Planning for SQL Server Indexing L5-3 Question How many rows were sampled? How many steps were created? What was the average key length? How many Black products are there? Answer 504 10 5. f Task 8: Calculate Selectivity of each query 1. In the toolbar. Calculate the selectivity of the query.Product WHERE Color = 'Black'. GO 3. Right-click the MarketDev database and click New Query.Prospect WHERE FirstName LIKE 'A%'. Right-click the MarketDev database and click New Query.Calculate the total number of rows in the table SELECT COUNT(1) FROM Marketing.Prospect. In the toolbar.Query 1 SELECT ProspectID.178571 93 f Task 7: Execute SQL Command and check accuracy of statistics 1. Type the query below in the query pane: -. click Execute. Note: A sample result would be 2013 / 19955 or approximately 10. GO 3. FirstName.1% 7. 6.Query 2 SELECT ProspectID. Type the query below in the same query pane: -. LastName FROM Marketing.

Note: A sample result would be 1 / 19955 or approximately 0. Highlight only Query 2 and click Execute. Note: A sample result would be 48 / 19955 or approximately 0. Calculate the selectivity of the query.L5-4 Lab: Planning for SQL Server Indexing GO 8. the columns and column order is detailed in the table below: Columns ProspectID Column Order 1 Rationale: Selecting by ProspectID only and no output order f Task 2: Design an index 1.2% 10. LastName FROM Marketing. the columns and column order is detailed in the table below: Columns FirstName Column Order 1 Rationale: Selecting by FirstName only and no output order f Task 3: Design an index 1. Type the query below in the same query pane: -. Calculate the selectivity of the query.Query 3 SELECT ProspectID.0% Challenge Exercise 2: Design column orders for indexes (Only if time permits) f Task 1: Design an index 1. Review the supporting documentation for Query 3. FirstName. Review the supporting documentation for Query 1. Highlight only Query 3 and click Execute. GO 11. 12.Prospect WHERE FirstName LIKE 'Arif%'. 9. the columns and column order is detailed in the table below: . Review the supporting documentation for Query 2.

In this case. FirstName instead f Task 5: Design an index 1. the selectivity of the FirstName column is sufficient to warrant the index on the FirstName.Lab: Planning for SQL Server Indexing L5-5 Columns FirstName LastName Column Order 1 2 Rationale: Selecting only a single FirstName. the index would be better defined as LastName. Review the supporting documentation for Query 5. the columns and column order is detailed in the table below: Columns FirstName LastName Column Order 1 2 Rationale: Selecting a range of FirstNames could have varying selectivity. the columns and column order is detailed in the table below: Columns LanguageID Column Order 1 Rationale: Grouping by LanguageID. Adding LastName to the index will supply the correct output order f Task 4: Design an index 1. Review the supporting documentation for Query 4. Note that in this case an alternate output order would not change the recommendation . Note that if the constant was an ‘A’ rather than an ‘S’.

L5-6 Lab: Planning for SQL Server Indexing .

In Virtual Machine Connection window. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. Maximize the Hyper-V Manager window. Before you begin the lab. double-click the query 00-Setup. In the virtual machine. and then click Hyper-V Manager. click Full Screen Mode.  In the Virtual Machines list. Password: Pa$$w0rd  From the View menu. 10. Review the supporting documentation for Table 1 and 2. select Windows Authentication and click Connect. if the user is not already logged on: • On the Action menu. On the host computer. click the Ctrl-Alt-Delete menu item. you must complete the following steps: 1.Lab: Implementing Table Structures in SQL Server L6-1 Module 6: Implementing Table Structures in SQL Server 2008 R2 Lab: Implementing Table Structures in SQL Server Lab Setup For this lab. 2. click Microsoft SQL Server 2008 R2. and then click Other User.ssmssln. click Start. in the Virtual Machine Connection window. type Proseware in the Server name text box. User name: AdventureWorks\Administrator • 4. If the Server Manager window appears. 3. When the query window opens. 9. • In the Virtual Machine Connection window. If you are prompted to confirm that you want to revert. click Open. . point to Administrative Tools. In the Virtual Machines list. wait until the Press CTRL+ALT+DELETE to log on message appears.sql. click on the Revert toolbar icon. click Execute on the toolbar. and click Project/Solution. 12. 8. Exercise 1: Creating Tables as Heaps f Task 1: Review the Requirements 1. In the Authentication drop-down list box. 11. Wait for the revert action to complete. ii. open the project D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ. and click SQL Server Management Studio. • Log on using the following credentials: i. In the Virtual Machine Connection window. 13. In Connect to Server window. you will use the available virtual machine environment. and then close the Virtual Machine Connection window. In the Virtual Machine Connection window. In the File menu. 7. In Solution Explorer. click Revert. 6. In the Open Project window. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. check the Do not show me this console at logon check box and close the Server Manager window. 5. 15. 14. • Click Switch User. click Start. wait until the Press CTRL+ALT+DELETE to log on message appears. • Right-click 623XB-MIA-SQL and click Connect. • Right-click 623XB-MIA-DC and click Connect. click All Programs.

click Execute. PublicationDate datetime.ActivityLog ( ActivityTime datetimeoffset. ActivityType int ).MediaOutlet ( MediaOutletID int PRIMARY KEY CLUSTERED. CallDurationSeconds int ).PhoneLog ( PhoneLogID int PRIMARY KEY NONCLUSTERED. PlacementDate datetime. In Object Explorer. GO 4. Right-click the MarketDev database and click New Query. SalespersonID int. GO 4. Exercise 2: Creating Tables with Clustered Indexes f Task 1: Review the Requirements 1. 3. GO CREATE TABLE Relationship. 2. City nvarchar(50) ). Type the query below in the query pane: CREATE TABLE Relationship. SessionID int. RelatedProductID int. GO CREATE TABLE Relationship. In the toolbar. expand the Databases under Proseware. . Type the query below in the query pane: CREATE TABLE Relationship. In the toolbar. In Object Explorer. f Task 2: Create the Tables in the MarketDev database 1. Duration int. 2.L6-2 Lab: Implementing Table Structures in SQL Server f Task 2: Create the Tables in the MarketDev database 1. PrimaryContact nvarchar(50). 3. click Execute. Review the supporting documentation for Tables 3 and 4. MediaOutletName nvarchar(40). MediaOutletID int. CalledPhoneNumber nvarchar(16). Right-click the MarketDev database and click New Query. PlacementCost decimal(18.2) ). expand the Databases under Proseware.PrintMediaPlacement ( PrintMediaPlacementID int PRIMARY KEY CLUSTERED.

Right-click the MarketDev database and click New Query. expand the Databases under Proseware. f Task 4: Create the Relationship.1). EmailAddress nvarchar(100). expand the Databases under Proseware.1). Right-click the MarketDev database and click New Query. 2. Review the supporting documentation for Table 5. click Execute. expand the Databases under Proseware. ReferenceID uniqueidentifier.Table_Heap Table 1. 2. Heaps (Only if time permits) f Task 1: Review the Table Design 1. In the toolbar. 3. ApplicantName nvarchar(150). click Execute.Table_ApplicationID ( ApplicationID int IDENTITY(1. 3. f Task 3: Create the Relationship.Table_ApplicationID (ApplicationID). GO 4. 2.Lab: Implementing Table Structures in SQL Server L6-3 Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs. Comments nvarchar(500) ).1). f Task 2: Create the Relationship.Table_Heap ( ApplicationID int IDENTITY(1. In Object Explorer. Type the query below in the query pane: CREATE TABLE Relationship. Type the query below in the query pane: CREATE TABLE Relationship. In the toolbar. EmailAddress nvarchar(100). 3.Table_EmailAddress Table 1. . ApplicantName nvarchar(150). In Object Explorer. GO 4. GO CREATE CLUSTERED INDEX IX_ApplicantID ON Relationship. Type the query below in the query pane: CREATE TABLE Relationship. In Object Explorer.Table_EmailAddress ( ApplicationID int IDENTITY(1. Comments nvarchar(500) ). Right-click the MarketDev database and click New Query.Table_ApplicationID Table 1. ReferenceID uniqueidentifier.

GO 4. 2.Table_EmailAddress (EmailAddress).1). Comments nvarchar(500) ). EmailAddress nvarchar(100). click Execute. GO 4. click Execute. ApplicantName nvarchar(150). Right-click the MarketDev database and click New Query. click Execute. Note: this may take approximately five minutes to complete. GO CREATE CLUSTERED INDEX IX_ReferenceID ON Relationship. A message is printed as each of the four sections is completed. Compare the performance of each table structure as reported by the results of executing the Workload script. f Task 6: Load and Execute the Workload Script 1. depending on available hardware resources. EmailAddress nvarchar(100). ReferenceID uniqueidentifier. In Solution Explorer. In Object Explorer. Note: Results will vary substantially depending upon the hardware the Virtual Machine is running on. You can check where it is up to by periodically switching to the Messages tab. review the contents of the script and estimate the proportion of time difference you expect to see in the results. Comments nvarchar(500) ). ReferenceID uniqueidentifier.Table_ReferenceID (ReferenceID). expand the Databases under Proseware. While the script is running. In the toolbar.sql. double-click the file 72 – Lab Exercise 3 Workload Script. 2. 3. In the toolbar. Type the query below in the query pane: CREATE TABLE Relationship. f Task 7: Compare Table Performance 1. In the toolbar. GO CREATE CLUSTERED INDEX IX_EmailAddress ON Relationship. Sample results are shown below.Table_ReferenceID Table 1. f Task 5: Create the Relationship.Table_ReferenceID ( ApplicationID int IDENTITY(1.L6-4 Lab: Implementing Table Structures in SQL Server ApplicantName nvarchar(150). HeapTime 23 seconds ApplicationIDTime 21 seconds EmailAddressTime 91 seconds ReferenceIDTime 134 seconds .

click Microsoft SQL Server 2008 R2. In Solution Explorer. and then click Other User. • Click Switch User. type Proseware in the Server name text box. click Full Screen Mode. 10. Estimated Plans f Task 1: Load the test script 1. 5.Lab: Reading SQL Server Execution Plans L7-1 Module 7: Reading SQL Server 2008 R2 Execution Plans Lab: Reading SQL Server Execution Plans Lab Setup For this lab. On the host computer.sql. click All Programs. In the File menu. In Virtual Machine Connection window. 11. Right-click 623XB-MIA-DC and click Connect. select Windows Authentication and click Connect. • Log on using the following credentials: i. double-click the file . open the project D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ. 7.ssmssln. 3. When the query window opens. From the View menu. If the Server Manager window appears. In the Open Project window. In the Virtual Machine Connection window.  In the Virtual Machines list. In the Virtual Machine Connection window. Before you begin the lab. User name: AdventureWorks\Administrator • Password: Pa$$w0rd  8. double-click the query 00-Setup. you will use the available virtual machine environment. 15. 13. click Start. and click SQL Server Management Studio. In the Virtual Machines list. Maximize the Hyper-V Manager window. Exercise 1: Actual vs. click Revert. you must complete the following steps: 1. ii. 2. In Connect to Server window. In Solution Explorer. click Execute on the toolbar. 14. click the Ctrl-Alt-Delete menu item. click Open. If you are prompted to confirm that you want to revert. if the user is not already logged on: • On the Action menu. In the Authentication drop-down list box. wait until the Press CTRL+ALT+DELETE to log on message appears. • Right-click 623XB-MIA-SQL and click Connect. click Start. and then click Hyper-V Manager. check the Do not show me this console at logon check box and close the Server Manager window. 9. 6. and then close the Virtual Machine Connection window. if the virtual machine 623XB-MIA-DC is not started:  4. • In the Virtual Machine Connection window. Wait for the revert action to complete. wait until the Press CTRL+ALT+DELETE to log on message appears. and click Project/Solution. 12. In the virtual machine. click on the Revert toolbar icon. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. • • Right-click 623XB-MIA-DC and click Start. point to Administrative Tools. in the Virtual Machine Connection window.

2 using SHOWPLAN_XML 1. Highlight the following section of the script SELECT * FROM dbo. GO 2. click Show Execution Plan XML. 6. 51 – Lab Exercise 1. In the ExecutionPlanX. 2. 3. Close the XML window and the execution plan window. 4. right-click in the whitespace in the plan. 5.1 1. click Execute.DatabaseLog. Highlight the following section of the script SELECT * FROM dbo. Highlight the following section of the script SET SHOWPLAN_XML ON.sqlplan tab. click Execute. GO 3. Note: The XML is complex and it includes a large amount of detail that is not immediately obvious from the graphical plan. In the Results pane. f Task 4: Generate the actual execution plan for script 7.sql. In the Results pane.3 1.DatabaseLog. Note: A Table Scan operator was used. If prompted to save changes. f Task 3: View the estimated execution plan for script 7. GO SET SHOWPLAN_XML OFF. click Execute. Highlight the following section of the script: USE AdventureWorks2008R2. In the toolbar. select Display Estimated Execution Plan.DatabaseLog. From the Query menu. In the toolbar. In the Query menu and click Include Actual Execution Plan. do not save the changes. .L7-2 Lab: Reading SQL Server Execution Plans 2. f Task 2: Generate an estimated execution plan for script 7. click on the XML that is returned to view the execution plan. In the toolbar. GO SELECT * FROM dbo. GO 2. GO 3. review the XML.

st. Note: An Estimated Execution Plan cannot be created.dbid) AS ObjectName.SomeTable.query_plan AS QueryPlan FROM sys.objtype AS PlanType. GO .refcounts AS ReferenceCounts. Highlight the following section of the script SELECT cp. GO 2. INSERT INTO dbo. Highlight the following section of the script CREATE TABLE dbo. From the Query menu.5 1. In the toolbar. st. f Task 7: Review the execution plans currently cached in memory using script 7. cp.SomeTable ( SomeTableID INT IDENTITY(1. DROP TABLE dbo. cp.SomeTable VALUES('Hello').usecounts AS UseCounts.SomeTable. select Display Estimated Execution Plan. Highlight the following section of the script again CREATE TABLE dbo.SomeTable. Note: The returned plan shows the INSERT and SELECT statements but not the CREATE and DROP statements.4 1. 1) PRIMARY KEY. INSERT INTO dbo.dm_exec_sql_text(cp. f Task 5: Try to generate an estimated execution plan for script 7. FullName varchar(35) ).SomeTable. DROP TABLE dbo.SomeTable ( SomeTableID INT IDENTITY(1. SELECT * FROM dbo.('There').plan_handle) AS st. 1) PRIMARY KEY.('There'). 3.dm_exec_query_plan(cp. GO 2. SELECT * FROM dbo.text AS SQLBatch.SomeTable VALUES('Hello').objectid. qp.4 1.Lab: Reading SQL Server Execution Plans L7-3 4. f Task 6: Review the actual execution plan for script 7. Note: The plan is identical to the estimated plan from the previous task. Review the Execution Plan that has been returned. FullName varchar(35) ). Note the reason (invalid object name) for the inability to create a plan in the messages tab.plan_handle) AS qp CROSS APPLY sys. OBJECT_NAME(st. Click on the Execution Plan pane. click Execute.dm_exec_cached_plans AS cp CROSS APPLY sys.

f Task 4: Explain the actual execution plan from script 7. From the Query menu click Include Actual Execution Plan.7 1. Note: The table has a clustered index and the entire table is being read. 3.6 as shown in the code below SELECT * FROM Person. f Task 3: Explain the actual execution plan from script 7.8 as shown in the code below SELECT * FROM Production. In the toolbar. Highlight script 7. . 3. Note: The table has a clustered index and a specific clustering key is being used to seek. f Task 2: Explain the actual execution plan from script 7. Note: The results returned will vary from system to system. Highlight script 7. double-click the file 61 – Lab Exercise 2. click Execute. In the toolbar. Highlight the query as shown in the script below: USE AdventureWorks2008R2. In Solution Explorer.8 1.6 1. Exercise 2: Identify Common Plan Elements f Task 1: Load the test script 1. In the toolbar. Explain the results being returned. click Execute. click Execute. 4. GO 2.sql. click Execute. GO 2.BusinessEntityID = 12. In the toolbar. GO 2.L7-4 Lab: Reading SQL Server Execution Plans 2.ProductInventory ORDER BY Shelf. 3. Explain the results being returned.Person WHERE Person. Highlight script 7. 3.7 as shown in the code below SELECT * FROM Person. Review the results being returned.Person. Browse through the rows in the Results tab to gain an understanding of the types of plans currently in memory.

Lab: Reading SQL Server Execution Plans

L7-5

GO

2. 3.

In the toolbar, click Execute. Explain the results being returned. Note: The table has a clustered index and the entire table is being read. The rows are then sorted by Shelf.

f Task 5: Explain the actual execution plan from script 7.9
1. Highlight script 7.9 as shown in the code below
SELECT * FROM dbo.DatabaseLog WHERE DatabaseLogID = 1; GO

2. 3.

In the toolbar, click Execute. Explain the results being returned. Note: The table is structured as a heap. The table has a nonclustered index on DatabaseLogID that is being used to locate the row required. Because the entire row is then required, a lookup is being made into the heap.

f Task 6: Explain the actual execution plan from script 7.10
1. Highlight script 7.10 as shown in the code below
SELECT AddressID, AddressLine1, AddressLine2, City, StateProvinceID, PostalCode FROM Person.Address WHERE StateProvinceID = 32; GO

2. 3.

In the toolbar, click Execute. Explain the results being returned. Note: The table has a clustered index. There is a nonclustered index that is sufficiently selective to be useful in locating entries for the given StateProvinceID. After the rows are located by that index, lookups to the clustered index need to be performed because not all columns that are required for the query are contained within the nonclustered index.

f Task 7: Explain the actual execution plan from script 7.11
1. Highlight script 7.11 as shown in the code below
SELECT AddressID, AddressLine1, AddressLine2, City, StateProvinceID, PostalCode FROM Person.Address WHERE StateProvinceID = 79; GO

2.

In the toolbar, click Execute.

L7-6

Lab: Reading SQL Server Execution Plans

3. 4.

Explain the results being returned. Compare this plan to the one returned in script 7.10. The reason why the plans are different can be attributed to Note: SQL Server has chosen to scan an entire index as it covers the query. The rows with the correct StateProvinceID are being selected from that index. Note the Missing Index hint that appears.

f Task 8: Explain the actual execution plan from script 7.12
1. Highlight script 7.12 as shown in the code below
SELECT City, COUNT(City) AS CityCount FROM Person.Address GROUP BY City; GO

2. 3.

In the toolbar, click Execute. Explain the results being returned. Note: SQL Server has decided to read an entire index that contains the City column rather than reading the entire table. As the index is not in City order, it then needs to execute a hash match aggregate operation to calculate the required aggregate.

f Task 9: Explain the actual execution plan from script 7.13
1. Highlight script 7.13 as shown in the code below
SELECT StateProvinceID, COUNT(1) AS StateProvinceCount FROM Person.Address GROUP BY StateProvinceID; GO

2. 3. 4.

In the toolbar, click Execute. Explain the results being returned. Compare this plan to the one returned in script 7.12. The reason why the plans are different can be attributed to Note: There is a nonclustered index that is in StateProvinceID order. SQL Server has chosen to scan that index. As it is already in StateProvinceID order, a stream aggregate operation was able to be performed.

f Task 10: Explain the actual execution plan from script 7.14
1. Highlight script 7.14 as shown in the code below
SELECT City, COUNT(City) AS CityCount FROM Person.Address GROUP BY City HAVING COUNT(1) > 5; GO

2.

In the toolbar, click Execute.

Lab: Reading SQL Server Execution Plans

L7-7

3.

Note the difference in this plan from the plan for script 7.12. Note: This query is identical to the one in script 7.12 with the addition of the HAVING clause. That clause has caused SQL Server to add a filter operation.

Challenge Exercise 3: Query Cost Comparison (Only if time permits)
f Task 1: Load the test script
1. In Solution Explorer, double-click the file 71 – Lab Exercise 3.sql. Highlight the query as shown in the script below:
USE AdventureWorks2008R2; GO

2.

3. 4.

In the toolbar, click Execute. From the Query menu click Include Actual Execution Plan.

f Task 2: Explain the actual execution plan from script 7.15
1. Highlight script 7.15 as shown in the code below
SELECT DISTINCT a.City FROM Person.Address AS a ORDER BY a.City; SELECT a.City FROM Person.Address AS a GROUP BY a.City ORDER BY a.City; GO

2. 3.

In the toolbar, click Execute. Explain the results being returned. Note: Even though the two queries are structured quite differently, they are requesting exactly the same results in the same order. It is then logical that SQL Server executes the same plan for both queries.

L7-8

Lab: Reading SQL Server Execution Plans

Lab: Improving Performance through Nonclustered Indexes

L8-1

Module 8: Improving Performance through Nonclustered Indexes

Lab: Improving Performance through Nonclustered Indexes
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. • Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.  In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. • Right-click 623XB-MIA-SQL and click Connect. • In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears. In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: • On the Action menu, click the Ctrl-Alt-Delete menu item. • Click Switch User, and then click Other User. • Log on using the following credentials: i. User name: AdventureWorks\Administrator

4.

5. 6. 7.

ii. Password: Pa$$w0rd  From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.
8. 9. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

Exercise 1: Nonclustered index usage review
f Task 1: Review the query
1. Review the supporting documentation for Query 1.

L8-2

Lab: Improving Performance through Nonclustered Indexes

f Task 2: Review the existing Index and Table structures
1. In Object Explorer, expand Proseware, expand Databases, expand MarketDev, expand Tables, and expand Marketing.WebLog. Review existing indexes and table structures for this table. Note: Clustered Primary Key on WebLogID and Non-Clustered index on SessionStart.

2.

f Task 3: Design a more appropriate index
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
CREATE INDEX IX_WebLog_Perf_20100830_A ON Marketing.WebLog (SessionStart) INCLUDE (SessionID, ServerID, UserName); GO

3.

In the toolbar, click Execute.

f Task 4: Test your design
1. 2. 3. Right-click the MarketDev database and click New Query. From the Query menu, click Include Actual Execution Plan. Type the query below in the query pane:
DECLARE @StartTime datetime2 = '2010-08-30 16:27'; SELECT TOP(5000) wl.SessionID, wl.ServerID, wl.UserName FROM Marketing.WebLog AS wl WHERE wl.SessionStart >= @StartTime ORDER BY wl.SessionStart, wl.ServerID;

4.

In the toolbar, click Execute.

Exercise 2: Improving nonclustered index designs
f Task 1: Review the index design
1. Review the supporting documentation for Query 2.

f Task 2: Implement the index
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
CREATE INDEX IX_WebLog_Perf_20100830_B ON Marketing.WebLog (ServerID, SessionStart) INCLUDE (SessionID, UserName); GO

3.

In the toolbar, click Execute.

Lab: Improving Performance through Nonclustered Indexes

L8-3

f Task 3: Test the design and explain why the index was not used
1. 2. 3. Right-click the MarketDev database and click New Query. From the Query menu, click Include Actual Execution Plan. Type the query below in the query pane:
DECLARE @StartTime datetime2 = '2010-08-30 16:27'; SELECT TOP(5000) wl.SessionID, wl.ServerID, wl.UserName FROM Marketing.WebLog AS wl WHERE wl.SessionStart >= @StartTime ORDER BY wl.SessionStart, wl.ServerID; GO

4.

In the toolbar, click Execute. Note: The structure of the index does not support efficient selection of rows or ordering of results.

Exercise 3: SQL Server Profiler and Database Engine Tuning Advisor
f Task 1: Review the query
1. Review the supporting documentation for Query 3.

f Task 2: Review the existing Index and Table structures
1. In Object Explorer, expand Proseware, expand Databases, expand MarketDev, expand Tables, and expand Marketing.PostalCode. Review existing indexes and table structures for this table. Note: Clustered index on Country, PostalCode.

2.

f Task 3: Design a more appropriate index by following the Missing Index suggestion
1. 2. 3. Right-click the MarketDev database and click New Query. From the Query menu, click Include Actual Execution Plan. Type the query below in the query pane:
SELECT PostalCode, Country FROM Marketing.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode, PostalCode; GO

4. 5. 6.

In the toolbar, click Execute. In the Execution Plan tab, note the missing index suggestion in green. Right-click in whitespace in the middle of the graphical execution plan and choose Missing Index Details.

L8-4

Lab: Improving Performance through Nonclustered Indexes

Note: Review the suggested index design. 7. 8. Close the Missing Index Details query window. Type the query below in the previous query pane:
CREATE NONCLUSTERED INDEX IX_PostalCode_Perf_20100830_A ON Marketing.PostalCode (StateCode) INCLUDE (Country,PostalCode); GO

9.

Highlight the above query, click Execute.

10. Highlight the previous query as shown below in the query pane:
SELECT PostalCode, Country FROM Marketing.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode, PostalCode; GO

11. In the toolbar, click Execute. 12. In the Execution Plan tab, note that the missing index suggestion has now disappeared. Note: The query is now utilizing the new index. 13. Leave the query pane open for the next task.

f Task 4: Create a better index that removes the sort operation. If you create another
index, confirm that SQL Server selects it
1. Type the query below in the query pane from the previous task:
CREATE NONCLUSTERED INDEX IX_PostalCode_Perf_20100830_B ON Marketing.PostalCode (StateCode, PostalCode) INCLUDE (Country); GO

2. 3.

Highlight the above query, click Execute. Highlight the previous query as shown below in the query pane:
SELECT PostalCode, Country FROM Marketing.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode, PostalCode; GO

4. 5.

In the toolbar, click Execute. Click on the Execution Plan tab. Note: The sort operation is now unnecessary and the new index is now utilized.

trc file and click Open. 6. click Connect. In the Set maximum file size(MB) textbox. 5. click Run. click SQL Server Profiler. 8. f Task 2: Load and execute the workload file 1. click the DatabaseName column header. 11. In the DatabaseName pane. double-click 81 – Lab Exercise 4.Lab: Improving Performance through Nonclustered Indexes L8-5 Challenge Exercise 4: Nonclustered index design (Only if time permits) f Task 1: Open SQL Server Profiler and configure and start a trace 1. 10. Click Save to file checkbox. In the Trace Properties window. 4. depending upon the available hardware resources. 9. type MarketDev. Click Events Selection tab. From the Tools menu. click Stop Trace. In the Use the Template drop down list box. 6. 5. and click OK. In SQL Server Management Studio. type 500. click Database Engine Tuning Advisor. In the Workload group box. In SQL Server Profiler. Uncheck the Enable File Rollover checkbox. 2. select Windows Authentication and click Connect. select Tuning. Browse to the Desktop folder. 4. select the Module08Trace. f Task 3: Stop and analyze the trace using DTA 1. Note: The query will take approximately 3 minutes to execute. and click Column Filters. in the Tools menu. 3. click Desktop in the left-hand pane under Favorites and click Save. click Execute. ensure that AutoScroll is not selected. In SQL Server Management Studio. In the Trace Properties window.sql in Solution Explorer. 14. 12. Maximize the Database Engine Tuning Advisor window. In the toolbar. In the Save As window. 2. . Wait for the query to complete. expand the Like node. 13. In the Edit Filter pane. In the Connect to Server window. 2. type Proseware in the Server name text box. In the Authentication drop-down list box. type Module08Trace in the Trace Name textbox. In the Connect to Server window. In the Window menu. from the File menu. 3. 3. 7. ensure that File is selected and click the Browse for a Workload File icon (the icon is the first icon to the right of the text box in the Workload group box).

In the Database for workload analysis dropdown. check the MarketDev database. note the recommendations. 14. From the toolbar. 15. In the Select databases and tables to tune list. . Scroll the Index Recommendations output to the right and note the hyperlinks to sample code. Click the Tuning Options tab and click Advanced Options. Close SQL Server Profiler. but it is likely you will see a recommendation for two new indexes and a substantial estimated performance improvement. 11. Note: Observe the tuning progress and when the analysis is complete. 8. etc. note the Estimated improvement. 10. click the Start Analysis. Click each of the recommendations in the Definition column turn and note the suggested index structures. In the Advanced Tuning Options window. The exact recommendations you see will depend upon how long you ran the query. 12. Close DTA. On the Recommendations tab. check the Define max space for recommendations (MB) checkbox and enter 500 for the size and click OK.L8-6 Lab: Improving Performance through Nonclustered Indexes 7. 16. 9. select MarketDev. 13.

Wait for the revert action to complete. ii. 12. click Full Screen Mode. • Log on using the following credentials: i. In the Virtual Machines list. Before you begin the lab. select Windows Authentication and click Connect. you must complete the following steps: 1. In Solution Explorer. wait until the Press CTRL+ALT+DELETE to log on message appears. 13. Password: Pa$$w0rd  From the View menu. wait until the Press CTRL+ALT+DELETE to log on message appears. click on the Revert toolbar icon. if the user is not already logged on: • On the Action menu.ssmssln. In the Virtual Machine Connection window. and click Project/Solution. On the host computer. click Microsoft SQL Server 2008 R2. When the query window opens. • Right-click 623XB-MIA-DC and click Connect. click Open. and then click Other User. In the virtual machine. In Virtual Machine Connection window. click Revert. 14. Maximize the Hyper-V Manager window. open the project D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ. • Right-click 623XB-MIA-SQL and click Connect. 11. User name: AdventureWorks\Administrator 4. In the Open Project window. If the Server Manager window appears. 5. check the Do not show me this console at logon check box and close the Server Manager window. and then close the Virtual Machine Connection window. and then click Hyper-V Manager. click Start. 6. in the Virtual Machine Connection window. In the File menu. In the Authentication drop-down list box. double-click the query 00-Setup. 10. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. In the Virtual Machines list. 9. 15. 2. type Proseware in the Server name text box. click Execute on the toolbar. 3. • In the Virtual Machine Connection window. and click SQL Server Management Studio. click the Ctrl-Alt-Delete menu item. 8. If you are prompted to confirm that you want to revert.Lab: Designing and Implementing Stored Procedures L9-1 Module 9: Designing and Implementing Stored Procedures Lab: Designing and Implementing Stored Procedures Lab Setup For this lab. . 7. In Connect to Server window.sql. point to Administrative Tools. click All Programs. click Start. • In the Virtual Machine Connection window. • Click Switch User. you will use the available virtual machine environment. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start.

p.GetProductsAndModels stored procedure specification 1. create and test the Reports.GetProductsAndModels. f Task 4: Design.GetProductColors stored procedure 1.ProductModelID.ProductDescription AS ed ON pm.GetProductsAndModels AS SELECT p. create and test the Reports. COALESCE(fd.ProductModelID LEFT OUTER JOIN Marketing.p.Description.ProductModelID = pm. GO 2.SellEndDate. pm. COALESCE(cd. p.Description.GetProductColors stored procedure specification 1. f Task 2: Design. click Execute. 3.ProductModelID = ed.ProductModel AS pm ON p.L9-2 Lab: Designing and Implementing Stored Procedures Exercise 1: Create stored procedures f Task 1: Review the Reports. p.GetProductsAndModels stored procedure 1.ProductNumber. f Task 3: Review the Reports.id. Review the supplied design requirements in the supporting documentation for Reports.GetProductColors.p.ProductName) AS ChineseDescription FROM Marketing.ProductName. GO EXEC Reports. In the toolbar. Type the query below in the query pane: CREATE PROCEDURE Reports. 2. Type the query below in the query pane: CREATE PROCEDURE Reports.ProductName) AS FrenchDescription.Color IS NOT NULL ORDER BY p.id.ProductModelID AND ed. Right-click the MarketDev database and click New Query. right-click the MarketDev database and click New Query. p.ProductName) AS EnglishDescription. In Object Explorer.ProductID.Product AS p WHERE p.GetProductColors AS SELECT DISTINCT p.Product AS p LEFT OUTER JOIN Marketing. p. expand the Proseware server.Color. COALESCE(ed.Color.SellStartDate.Description.GetProductColors. Note: Ensure that approximately 9 colors are returned and that no NULL row is returned. p.Description. expand Databases. Review the supplied design requirements in the supporting documentation for Reports.Description.Description.id.LanguageID = 'en' .Color FROM Marketing.

click Execute.GetProductsByColor.ProductModelID AND cd.ProductModelID. GO 3.pm.Color.GetProductsByColor stored procedure specification 1. p.ProductDescription AS cd ON pm. p. Check that appropriate language descriptions appear.Lab: Designing and Implementing Stored Procedures L9-3 LEFT OUTER JOIN Marketing.ProductModelID = fd. p.LanguageID = 'zh-cht' LEFT OUTER JOIN Marketing. Ensure that approximately 248 rows are returned for products with no color. 2.ProductDescription AS id ON pm. GO EXEC Reports. f Task 2: Design. In the toolbar.Size. p.ListPrice AS Price.ProductModelID = cd. ProductID 1 should have the same description for all three languages.ProductDescription AS fd ON pm.LanguageID = '' ORDER BY p. Type the query below in the query pane: CREATE PROCEDURE Reports.SizeUnitMeasureCode AS UnitOfMeasure FROM Marketing.GetProductsByColor NULL.ProductModelID = id.ProductModelID AND id.GetProductsByColor 'Blue'. In the toolbar.GetProductsByColor stored procedure 1. Review the supplied design requirements in the supporting documentation for Reports. ProductID 776 should have different descriptions for each language.LanguageID = 'fr' LEFT OUTER JOIN Marketing. GO EXEC Reports.GetProductsAndModels.ProductName. Exercise 2: Create a parameterized stored procedure f Task 1: Review the Reports.ProductID. click Execute. Note: Ensure that approximately 504 rows are returned.Color IS NULL AND @Color IS NULL) ORDER BY ProductName. Note: Ensure that approximately 26 rows are returned for blue products.Product AS p WHERE (p. Right-click the MarketDev database and click New Query.GetProductsByColor @Color nvarchar(16) AS SELECT p.Color = @Color) OR (p. create and test the Reports. . GO 3. p.ProductID.ProductModelID AND fd. GO EXEC Reports.

Color.ProductID.LanguageID = 'fr' LEFT OUTER JOIN Marketing. Type the query below in the query pane: ALTER PROCEDURE Reports.Description.GetProductsAndModels WITH EXECUTE AS OWNER AS SELECT p.ProductName) AS ChineseDescription FROM Marketing.ProductName) AS EnglishDescription. p.ProductDescription AS fd ON pm.Description.Color.id.p.id.GetProductColors. f Task 2: Alter the Reports.ProductModel AS pm ON p. p. COALESCE(ed.ProductModelID AND cd.ProductDescription AS ed ON pm.Color FROM Marketing.ProductModelID = pm.Description.ProductNumber. In the toolbar.GetProductColors stored procedure to execute as OWNER 1.Description.LanguageID = '' ORDER BY p.ProductModelID AND ed.pm. Check that the procedure still executes without error. 2.ProductModelID LEFT OUTER JOIN Marketing.ProductModelID = fd. p.ProductDescription AS cd ON pm.LanguageID = 'en' LEFT OUTER JOIN Marketing.Color IS NOT NULL ORDER BY p.GetProductsAndModels stored procedure to execute as OWNER 1.Product AS p WHERE p.ProductModelID = ed.p.Description. .Description.Product AS p LEFT OUTER JOIN Marketing. GO 3.SellStartDate. GO EXEC Reports. Right-click the MarketDev database and click New Query.ProductName. p.SellEndDate.id.p.LanguageID = 'zh-cht' LEFT OUTER JOIN Marketing.ProductID.L9-4 Lab: Designing and Implementing Stored Procedures Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits) f Task 1: Alter the Reports. click Execute. 2. p.ProductModelID = cd. Type the query below in the query pane: ALTER PROCEDURE Reports. Right-click the MarketDev database and click New Query.GetProductColors WITH EXECUTE AS OWNER AS SELECT DISTINCT p. COALESCE(fd.ProductModelID AND fd. pm.ProductModelID.ProductName) AS FrenchDescription.ProductDescription AS id ON pm.ProductModelID AND id.ProductModelID.ProductModelID = id. COALESCE(cd.

ListPrice AS Price.GetProductsByColor NULL. GO EXEC Reports. p. In the toolbar.     . p. In the toolbar.Color = @Color) OR (p. 2. click Execute. GO 3. GO EXEC Reports.SizeUnitMeasureCode AS UnitOfMeasure FROM Marketing.Size. Right-click the MarketDev database and click New Query.GetProductsByColor 'Blue'.GetProductsByColor stored procedure to execute as OWNER 1. p. Check that the procedure still executes without error. Check that the procedure still executes without error.ProductName.ProductID. Type the query below in the query pane: ALTER PROCEDURE Reports. p. GO 3.GetProductsByColor @Color nvarchar(16) WITH EXECUTE AS OWNER AS SELECT p.Color IS NULL AND @Color IS NULL) ORDER BY ProductName.Product AS p WHERE (p. p. click Execute.Color.Lab: Designing and Implementing Stored Procedures L9-5 GO EXEC Reports.GetProductsAndModels. f Task 3: Alter the Reports.

L9-6 Lab: Designing and Implementing Stored Procedures   .

if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. click Start. In the virtual machine. click on the Revert toolbar icon. click Open. wait until the Press CTRL+ALT+DELETE to log on message appears. point to Administrative Tools.sql.GetProductsByColorList. click the Ctrl-Alt-Delete menu item. In the Open Project window. When the query window opens. wait until the Press CTRL+ALT+DELETE to log on message appears. If the Server Manager window appears. select Windows Authentication and click Connect. • Click Switch User. • Right-click 623XB-MIA-SQL and click Connect. . • In the Virtual Machine Connection window. 14. 5. • Log on using the following credentials: i. and click SQL Server Management Studio. Before you begin the lab. 6. Wait for the revert action to complete. check the Do not show me this console at logon check box and close the Server Manager window. click Start. you must complete the following steps: 1. 9. 12. Right-click 623XB-MIA-DC and click Connect. 2. On the host computer. click Full Screen Mode. if the virtual machine 623XB-MIA-DC is not started:  Right-click 623XB-MIA-DC and click Start. Review the supplied design requirements in the supporting documentation for Reports. if the user is not already logged on: • On the Action menu. click Revert. click All Programs. 4. and then click Hyper-V Manager. In the File menu. and then click Other User. 7. In Virtual Machine Connection window. open the project D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ. In the Virtual Machine Connection window. click Microsoft SQL Server 2008 R2. In the Virtual Machines list. click Execute on the toolbar. 10. In the Virtual Machine Connection window. and click Project/Solution.ssmssln. and then close the Virtual Machine Connection window. In Connect to Server window.Lab: Passing Tables and Merging Data L10-1 Module 10: Merging Data and Passing Tables Lab: Passing Tables and Merging Data Lab Setup For this lab. User name: AdventureWorks\Administrator ii. double-click the query 00-Setup. Password: Pa$$w0rd 8. In the Authentication drop-down list box. you will use the available virtual machine environment. In the Virtual Machines list. 15. From the View menu. • • • 3. in the Virtual Machine Connection window. Maximize the Hyper-V Manager window. Exercise 1: Create a Table Type f Task 1: Review the parameters of a stored procedure 1. 13. type Proseware in the Server name text box. In Solution Explorer. If you are prompted to confirm that you want to revert. 11.

2. In the toolbar.ProductName. In the toolbar. Type the query below in the query pane: DECLARE @ColorList StringList. In Object Explorer. click Execute.StringValue ORDER BY p.ProductID. In the toolbar.('Silver'). expand Programmability. . expand Databases. 2. Review the design of the existing function. 2. Right-click dbo.Color. click CREATE To. GO 3. Right-click the MarketDev database and click New Query. Exercise 2: Use a Table Type Parameter f Task 1: Create the stored procedure 1. expand Proseware. click Execute.Size. GO 3. select New Query Editor Window. expand Functions. p. Right-click the MarketDev database and click New Query. f Task 3: Create a new table type 1. and expand Table-valued Functions. expand MarketDev.ProductName. p. EXEC Reports.Product AS p INNER JOIN @ColorList AS cl ON p. Type the query below in the query pane: CREATE PROCEDURE Reports. 2.Color = cl.StringListToTable. click Execute. INSERT INTO @ColorList VALUES('Red').GetProductsByColorList_Test @ColorList. click Script Function as. Right-click the MarketDev database and click New Query. Type the query below in the query pane: CREATE TYPE StringList AS TABLE(StringValue nvarchar(1000) NOT NULL).L10-2 Lab: Passing Tables and Merging Data f Task 2: Review the existing function 1. p. 3. GO 3. p. p.GetProductsByColorList_Test (@ColorList StringList READONLY) AS SELECT p.('Blue').ListPrice AS Price. f Task 2: Test the new procedure 1.SizeUnitMeasureCode AS UnitOfMeasure FROM Marketing.

spd.SalespersonID WHEN MATCHED THEN UPDATE SET sp. sp. EmailAlias nvarchar(256) NULL. sp. Type the query below in the query pane: CREATE PROCEDURE Marketing.SalespersonMerge Stored Procedure. LastName nvarchar(50) NULL. Type the query below in the query pane: CREATE TYPE dbo.SalesTerritoryID = COALESCE(spd. EmailAlias. SalesTerritoryID) VALUES (spd. BadgeNumber nvarchar(15) NULL. sp. spd.MiddleName = COALESCE(spd. sp.BadgeNumber. 3.SalespersonID = spd. sp.LastName). spd.SalespersonList AS TABLE (SalespersonID int NOT NULL.EmailAlias).SalespersonID. Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits) f Task 1: Create a new table type 1. spd. FirstName nvarchar(50) NULL.SalesTerritoryID) WHEN NOT MATCHED THEN INSERT (SalespersonID.FirstName).FirstName. sp.EmailAlias.FirstName = COALESCE(spd. sp. Right-click the MarketDev database and click New Query. f Task 2: Create a replacement stored procedure 1. sp.MiddleName. sp.Salesperson AS sp USING @SalespersonDetails AS spd ON sp. LastName. click Execute. BadgeNumber.LastName.LastName. In the toolbar. spd. spd. MiddleName.SalesTerritoryID. GO 3.SalespersonMerge (@SalespersonDetails SalespersonList READONLY) AS BEGIN MERGE INTO Marketing. sp.FirstName.Lab: Passing Tables and Merging Data L10-3 Note: Approximately 107 rows should be returned. FirstName. Review the supplied design in the supporting documentation for the Marketing.BadgeNumber = COALESCE(spd. Right-click the MarketDev database and click New Query. sp.BadgeNumber. MiddleName nvarchar(50) NULL. .BadgeNumber). SalesTerritoryID int NULL).EmailAlias = COALESCE(spd.MiddleName).MiddleName.LastName = COALESCE(spd. 2.EmailAlias.SalesTerritoryID) 2.

'Wong'.'John'.NULL.'adventure-works\jwong'. 2. click Execute.L10-4 Lab: Passing Tables and Merging Data OUTPUT $action AS Action. In the toolbar. click Execute. EXEC Marketing.SalespersonID. (601.3). INSERT INTO @Salespeople (SalespersonID. Type the query below in the query pane: DECLARE @Salespeople SalespersonList. FirstName. GO 3.'Michael'. f Task 3: Test the replacement procedure 1.'adventure-works\mwong'. BadgeNumber.SalespersonMerge @Salespeople. LastName. MiddleName. In the toolbar.NULL). SalesTerritoryID) VALUES (276. GO 4.'Wong'. Right-click the MarketDev database and click New Query. .''. Note: The output should show UPDATE for SalesPersonID 276 and should show INSERT for SalesPersonID 601. EmailAlias.''. inserted. END.'234232'.

you must complete the following steps: 1. click Open. click Revert. you will use the available virtual machine environment. In the Virtual Machine Connection window. and then click Hyper-V Manager. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machines list. and click Project/Solution. In the virtual machine. From the View menu. click Full Screen Mode. In the Virtual Machines list. 11. Right-click 623XB-MIA-DC and click Connect. Right-click 623XB-MIA-DC and click Start. if the user is not already logged on: • • • On the Action menu. click on the Revert toolbar icon. check the Do not show me this console at logon check box and close the Server Manager window. . If the Server Manager window appears. wait until the Press CTRL+ALT+DELETE to log on message appears. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. type Proseware in the Server name text box. Click Switch User. wait until the Press CTRL+ALT+DELETE to log on message appears. 7. In the File menu. and then close the Virtual Machine Connection window. 5. 6. point to Administrative Tools. If you are prompted to confirm that you want to revert. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. click Microsoft SQL Server 2008 R2. click All Programs. ii. In the Authentication drop-down list box. On the host computer. 2. 9. Wait for the revert action to complete. click the Ctrl-Alt-Delete menu item. select Windows Authentication and click Connect. In the Virtual Machine Connection window. Before you begin the lab.Lab: Creating Highly Concurrent SQL Server Applications L11-1 Module 11: Creating Highly Concurrent SQL Server 2008 R2 Applications Lab: Creating Highly Concurrent SQL Server Applications Lab Setup For this lab. 12. click Start. 10. Log on using the following credentials: i. 3. click Start. 13. in the Virtual Machine Connection window. In Virtual Machine Connection window. and click SQL Server Management Studio. In Connect to Server window. if the virtual machine 623XB-MIA-DC is not started: • • • 4. and then click Other User.

sql. Review the results from the Deadlock Trace. double-click the query 00-Setup. from File menu. Expand Locks. When the query window opens. open the project D:\6232B_Labs\6232B_11_PRJ\6232B_11_PRJ. In Solution Explorer.sql in Solution Explorer. In the Trace Properties window. . 15. 2. De-select all events except the Deadlock graph. Wait for both to complete Note: One of the scripts will return a deadlock error. check Deadlock graph. f Task 2: Load and execute the test scripts 1. select Windows Authentication and click Connect. In Connect to Server window. You may need to scroll the window down to do this. 5. click Stop Trace. Review the script. Uncheck the Show all events checkbox. 3. In SQL Server Management Studio. Review the graph that appears at the bottom of the screen. Maximize the Trace window inside SQL Server Profiler.ssmssln. type Deadlock Detection in the Trace Name textbox. 10. 7. 4. Click Run to start the trace. type Proseware in the Server name text box. In SQL Server Management Studio. Execute 51 – Lab Exercise 1. f Task 3: Stop the trace and review the deadlock graph 1.sql. In SQL Server Management Studio. 3. Click Events Selection tab. Review the script. 8. 2. 4. In SQL Server Profiler. from Tools menu. Click on the event line that contains the Deadlock graph.L11-2 Lab: Creating Highly Concurrent SQL Server Applications 14. 4.sql in Solution Explorer. 5. 2.sql and then immediately execute 52 – Lab Exercise 1 2nd Window. double-click 51 – Lab Exercise 1. double-click 52 – Lab Exercise 1 2nd Window. Exercise 1: Detecting Deadlocks f Task 1: Start and configure SQL Server Profiler 1. click SQL Server Profiler. 5. 3. Check the Show all events checkbox. 6. click Execute on the toolbar. In the Open Project window. 9. In the Authentication drop-down list box.

double-click 61 – Lab Exercise 2. Hover your mouse over each of the ellipses that represent processes.Lab: Creating Highly Concurrent SQL Server Applications L11-3 6. Challenge Exercise 2: Investigating Transaction Isolation Levels (Only if time permits) f Task 1: Load the scripts 1. 2.sql in Solution Explorer. Note: When you hover your mouse over a process. Close SQL Server Profiler. In SQL Server Management Studio. Make sure that you execute only the code for each step and in the correct window as directed by the scripts. . Right-click the tab at the top of the window that opens and click Close All But This. you will see a pop-up window displaying the TSQL statement that was executed. double-click 62 – Lab Exercise 2 2nd Window. 3. Execute the code step by step by following the instructions in the script files. In SQL Server Management Studio. Note: This exercise involves two script windows.sql in Solution Explorer. f Task 2: Execute the code 1. 7.

L11-4 Lab: Creating Highly Concurrent SQL Server Applications .

14. Password: Pa$$w0rd From the View menu. you must complete the following steps: 1. 7. 15. click Microsoft SQL Server 2008 R2. In the Virtual Machine Connection window. In the Virtual Machine Connection window. In the Virtual Machines list. Wait for the revert action to complete. 12.sql.Lab: Handling Errors in T-SQL Code L12-1 Module 12: Handling Errors in T-SQL Code Lab: Handling Errors in T-SQL Code Lab Setup For this lab. if the virtual machine 623XB-MIA-SQL is not started: • • • Right-click 623XB-MIA-SQL and click Start. Click Switch User. click Start. click Open. and click Project/Solution. wait until the Press CTRL+ALT+DELETE to log on message appears. click Start. type Proseware in the Server name text box. If you are prompted to confirm that you want to revert. In the Virtual Machine Connection window. if the virtual machine 623XB-MIA-DC is not started: • • • 4. and then click Hyper-V Manager. . 13. Before you begin the lab. Maximize the Hyper-V Manager window. click Revert.ssmssln. and click SQL Server Management Studio. if the user is not already logged on: • • • On the Action menu. and then click Other User. In the File menu. In Virtual Machine Connection window. User name: AdventureWorks\Administrator ii. Log on using the following credentials: 8. click All Programs. and then close the Virtual Machine Connection window. in the Virtual Machine Connection window. Right-click 623XB-MIA-DC and click Start. 2. click Full Screen Mode. When the query window opens. double-click the query 00-Setup. wait until the Press CTRL+ALT+DELETE to log on message appears. In the Open Project window. point to Administrative Tools. i. click on the Revert toolbar icon. 9. In Solution Explorer. Right-click 623XB-MIA-SQL and click Connect. select Windows Authentication and click Connect. click the Ctrl-Alt-Delete menu item. 5. In Connect to Server window. 10. 6. 11. In the virtual machine. open the project D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ. check the Do not show me this console at logon check box and close the Server Manager window. If the Server Manager window appears. In the Virtual Machines list. click Execute on the toolbar. In the Authentication drop-down list box. 3. Right-click 623XB-MIA-DC and click Connect. you will use the available virtual machine environment. On the host computer.

. COMMIT TRANSACTION. click Execute. @BalanceToMove decimal(18. Type the query below in the query pane: EXEC Marketing.MoveCampaignBalance_Test ( @FromCampaignID int. expand Databases. Right-click the MarketDev database and click New Query. 2. 2. END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION. right-click Marketing. -. Right-click the MarketDev database and click New Query.2) ) AS BEGIN SET XACT_ABORT ON. expand MarketDev. GO 3. UPDATE Marketing.CampaignBalance SET RemainingBalance -= @BalanceToMove WHERE CampaignID = @FromCampaignID. and click Modify.2. 2.CampaignBalance SET RemainingBalance += @BalanceToMove WHERE CampaignID = @ToCampaignID.MoveCampaignBalance. END. 4. @ToCampaignID int. f Task 2: Rewrite the stored procedure to use structured exception handling 1.51. BEGIN TRY BEGIN TRANSACTION UPDATE Marketing.L12-2 Lab: Handling Errors in T-SQL Code Exercise 1: Replace @@ERROR based error handling with structured exception handling f Task 1: Review the existing code 1. RETURN 1. Review the existing stored procedure. expand Proseware.7 END CATCH. GO 3. In Object Explorer. click Execute. expand Programmability. In the toolbar. PRINT 'Unable to move balance'. expand Stored Procedures. Note: You should see two messages each indicating that a single row has been updated. Leave the query window open for use in the next exercise. Type the query below in the query pane: CREATE PROCEDURE Marketing.MoveCampaignBalance_Test 3. In the toolbar. f Task 3: Test the stored procedure 1.50.

END. WAITFOR DELAY '00:00:05'. RETURN 1. click Execute. END. return to the query window with the Marketing. SET XACT_ABORT ON. f Task 2: Test the stored procedure 1.MoveCampaignBalance_Test code as shown in the query pane: EXEC Marketing. click Execute. END ELSE BEGIN SET @RetriesRemaining = 0. In SQL Server Management Studio. @BalanceToMove decimal(18. -. WHILE (@RetriesRemaining > 0) BEGIN BEGIN TRY BEGIN TRANSACTION UPDATE Marketing. PRINT 'Warning: deadlock retry'.MoveCampaignBalance_Test stored procedure code. SET @RetriesRemaining = 0. GO 2.CampaignBalance SET RemainingBalance += @BalanceToMove WHERE CampaignID = @ToCampaignID.MoveCampaignBalance_Test 3. GO 2. COMMIT TRANSACTION.MoveCampaignBalance_Test ( @FromCampaignID int. Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits) f Task 1: Modify the code to re-try on deadlock 1. END CATCH. return to the query window with the EXEC Marketing. @ToCampaignID int.2.CampaignBalance SET RemainingBalance -= @BalanceToMove WHERE CampaignID = @FromCampaignID. 3. END TRY BEGIN CATCH IF (ERROR_NUMBER() = 1205) BEGIN SET @RetriesRemaining -=1. In SQL Server Management Studio. END.50.exit the retry loop IF XACT_STATE() <> 0 ROLLBACK TRANSACTION.2) ) AS BEGIN DECLARE @RetriesRemaining int = 5. Leave the query window open for use in the next exercise.51. PRINT 'Unable to move balance'. In the toolbar. . Modify the query as per the code shown below: ALTER PROCEDURE Marketing. In the toolbar.Lab: Handling Errors in T-SQL Code L12-3 4. UPDATE Marketing.

.L12-4 Lab: Handling Errors in T-SQL Code Note: You should see two messages each indicating that a single row has been updated.

In the Virtual Machine Connection window. In the virtual machine. 9. click on the Revert toolbar icon. if the user is not already logged on: • On the Action menu. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. 5. you must complete the following steps: 1. 4. In the Virtual Machines list. From the View menu. 3. • Log on using the following credentials: i.Lab: Designing and Implementing User-Defined Functions L13-1 Module 13: Designing and Implementing User-Defined Functions Lab: Designing and Implementing User-Defined Functions Lab Setup For this lab. If the Server Manager window appears. Password: Pa$$w0rd 8. click Microsoft SQL Server 2008 R2. • Right-click 623XB-MIA-SQL and click Connect. In the File menu. and then click Hyper-V Manager. and click SQL Server Management Studio. 13. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. point to Administrative Tools. Before you begin the lab. When the query window opens. open the project D:\6232B_Labs\6232B_13_PRJ\6232B_13_PRJ. In the Open Project window.sql. double-click the query 00-Setup. 6. In Virtual Machine Connection window. If you are prompted to confirm that you want to revert. User name: AdventureWorks\Administrator ii. click Execute on the toolbar. In Solution Explorer. and click Project/Solution. Wait for the revert action to complete. wait until the Press CTRL+ALT+DELETE to log on message appears. type Proseware in the Server name text box. • Click Switch User. click Revert. click All Programs. 11. • Right-click 623XB-MIA-DC and click Connect. • In the Virtual Machine Connection window. check the Do not show me this console at logon check box and close the Server Manager window. On the host computer. 2. click the Ctrl-Alt-Delete menu item. in the Virtual Machine Connection window. In the Authentication drop-down list box.ssmssln. In Connect to Server window. click Start. Maximize the Hyper-V Manager window. and then click Other User. click Full Screen Mode. click Open. 12. 7. 15. you will use the available virtual machine environment. wait until the Press CTRL+ALT+DELETE to log on message appears. 14. and then close the Virtual Machine Connection window. In the Virtual Machines list. select Windows Authentication and click Connect. . • In the Virtual Machine Connection window. 10. click Start.

In the toolbar. Right-click the MarketDev database and click New Query.FormatPhoneNumber('94852342'). END.4) WHEN 8 THEN SUBSTRING(@Digits. IF (@Character >= N'0') AND (@Character <= N'9') SET @Digits += @Character.L13-2 Lab: Designing and Implementing User-Defined Functions Exercise 1: Formatting Phone Numbers f Task 1: Review the design requirements 1. RETURN CASE LEN(@Digits) WHEN 10 THEN N'(' + SUBSTRING(@Digits. dbo. DECLARE @Character nchar(1). END. WHILE (LEN(@Remaining) > 0) BEGIN SET @Character = LEFT(@Remaining.4) WHEN 6 THEN SUBSTRING(@Digits.FormatPhoneNumber ( @PhoneNumberToFormat nvarchar(16) ) RETURNS nvarchar(16) AS BEGIN DECLARE @Digits nvarchar(16) = ''.1.3) + N'-' + SUBSTRING(@Digits. Type the query below in the query pane: CREATE FUNCTION dbo. GO 3.2. .FormatPhoneNumber('85-2342'). dbo. In the toolbar.FormatPhoneNumber('(41) 5485-2342').5. 2. Type the query below in the query pane: SELECT SELECT SELECT SELECT SELECT GO dbo. click Execute.1. IF LEFT(@Remaining.4. Review the supplied function specifications in the supporting documentation in the Lab section of the Student Manual. click Execute.4.1.LEN(@Remaining)). for the Phone Number. Right-click the MarketDev database and click New Query.FormatPhoneNumber('415 485-2342'). f Task 2: Design and create the function 1.3) + N') ' + SUBSTRING(@Digits.1) = N'+' RETURN @Remaining.FormatPhoneNumber('+61 3 9485-2342').4) + N'-' + SUBSTRING(@Digits. f Task 3: Test the function 1.3) ELSE @Digits END. 2. dbo. dbo.3) + N'-' + SUBSTRING(@Digits. 3. SET @Remaining = SUBSTRING(@Remaining.1).7. DECLARE @Remaining nvarchar(16) = @PhoneNumberToFormat.

SET @CurrentToken = SUBSTRING(@RemainingString. Type the query below in the query pane: CREATE FUNCTION dbo. DECLARE @CurrentToken nvarchar(8). IF (@DelimiterPosition = 0) SET @DelimiterPosition = LEN(@RemainingString) + 1.IntegerListToTable ( @InputList nvarchar(MAX). LEN(@RemainingString)). click Execute.1. GO 3.@DelimiterPosition . @DelimiterPosition + 1. WHILE LEN(@RemainingString) > 0 BEGIN SET @DelimiterPosition = CHARINDEX(@Delimiter. @Delimiter nchar(1) = N'. @RemainingString).') RETURNS @OutputTable TABLE (PositionInList int IDENTITY(1. Right-click the MarketDev database and click New Query. IntegerValue int) AS BEGIN DECLARE @RemainingString nvarchar(MAX) = @InputList. Type the query below in the query pane: . END. RETURN. f Task 2: Design and create the function 1. INSERT INTO @OutputTable (IntegerValue) VALUES(CAST(@CurrentToken AS int)). f Task 3: Test the function 1. END. for the dbo. SET @RemainingString = SUBSTRING(@RemainingString.1).IntegerListToTable function. 2. In the toolbar. IF (@DelimiterPosition > 8) SET @DelimiterPosition = 8. Review the supplied function specifications in the supporting documentation in the Lab section of the Student Manual.Lab: Designing and Implementing User-Defined Functions L13-3 Note: The output should resemble the following: +61 3 9485-2342 (415) 485-2342 (415) 485-2342 9485-2342 852-342 Exercise 2: Modifying an Existing Function f Task 1: Review the requirements 1. 1) NOT NULL. 2. DECLARE @DelimiterPosition int. Right-click the MarketDev database and click New Query.

JoinNames(FirstName.IntegerListToTable('234. In the toolbar.L13-4 Lab: Designing and Implementing User-Defined Functions SELECT * FROM dbo. Note: The output should resemble the following: Challenge Exercise 3: Resolve a Function-related Performance Issue (Only if time permits) f Task 1: Review the query 1. GO SELECT dbo.LastName) AS FullName FROM Marketing.2'. Review the supplied problematic query in the supporting documentation in the Lab section of the Student Manual. Type the problem query from the supporting documentation and the replacement query in the query pane: SET STATISTICS TIME ON. Note: The output should resemble the following: f Task 4: Test the function with an alternate delimiter such as the pipe | character 1. Right-click the MarketDev database and click New Query. 2. 2.'. GO 3. In the toolbar.IntegerListToTable('234|354253|3242|2'. Right-click the MarketDev database and click New Query. click Execute.').Prospect .354253. f Task 2: Design an alternate query 1. Type the query below in the query pane: SELECT * FROM dbo.'|').MiddleName.3242. click Execute. GO 3.

Lab: Designing and Implementing User-Defined Functions L13-5 ORDER BY FullName.Prospect ORDER BY FullName.Prospect ORDER BY FullName. GO SELECT dbo. In the toolbar. GO 3. 2.LastName) AS FullName FROM Marketing. Right-click the MarketDev database and click New Query.JoinNames(FirstName. f Task 3: Use SET STATISTICS TIME ON to compare the performance of the new and old queries 1.Prospect ORDER BY FullName. SELECT FirstName + N' ' + CASE WHEN LEN(MiddleName) > 0 THEN MiddleName + N' ' ELSE N'' END + LastName AS FullName FROM Marketing.MiddleName. GO SET STATISTICS TIME OFF. Type the query below in the query pane: SET STATISTICS TIME ON. click Execute. click Execute. . GO 3. GO SELECT FirstName + N' ' + CASE WHEN LEN(MiddleName) > 0 THEN MiddleName + N' ' ELSE N'' END + LastName AS FullName FROM Marketing. In the toolbar.

The output should resemble the following: . The actual times will vary from computer to computer.L13-6 Lab: Designing and Implementing User-Defined Functions Note: The execution time for the alternate query should be shorter than the time for the original query.

you must complete the following steps: 1. and click Project/Solution. click Start. and then click Hyper-V Manager. On the host computer. 6. click All Programs. wait until the Press CTRL+ALT+DELETE to log on message appears. click on the Revert toolbar icon. 9. 12. • Right-click 623XB-MIA-DC and click Connect. and then close the Virtual Machine Connection window. 10. In the Virtual Machines list. In the Authentication drop-down list box. click Revert.Lab: Ensuring Data Integrity through Constraints L14-1 Module 14: Ensuring Data Integrity Through Constraints Lab: Ensuring Data Integrity through Constraints Lab Setup For this lab. if the user is not already logged on: • On the Action menu. • In the Virtual Machine Connection window. click the Ctrl-Alt-Delete menu item. If the Server Manager window appears. point to Administrative Tools. wait until the Press CTRL+ALT+DELETE to log on message appears. check the Do not show me this console at logon check box and close the Server Manager window. click Start. i. If you are prompted to confirm that you want to revert. 3. 5. double-click the query 00-Setup. Wait for the revert action to complete.sql. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. 7. 11. select Windows Authentication and click Connect. In the File menu. In Solution Explorer. User name: AdventureWorks\Administrator  Password: Pa$$w0rd  From the View menu. 14. When the query window opens. 8. you will use the available virtual machine environment. click Open. click Execute on the toolbar. In the Open Project window. type Proseware in the Server name text box. and click SQL Server Management Studio. • In the Virtual Machine Connection window. • Log on using the following credentials: 4. in the Virtual Machine Connection window. In Virtual Machine Connection window. click Full Screen Mode. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. and then click Other User. open the project D:\6232B_Labs\6232B_14_PRJ\6232B_14_PRJ. click Microsoft SQL Server 2008 R2. ii. 2. In the Virtual Machines list. 15. 13. • Click Switch User. Maximize the Hyper-V Manager window. In Connect to Server window. In the virtual machine. .ssmssln. Before you begin the lab. In the Virtual Machine Connection window. • Right-click 623XB-MIA-SQL and click Connect.

Yield ADD CONSTRAINT DF_Yield_LastUpdate DEFAULT (SYSDATETIME()) FOR LastUpdate. GO ALTER TABLE Marketing. GO ALTER TABLE Marketing.Yield ALTER COLUMN ProspectID int NOT NULL.Yield ADD CONSTRAINT DF_Yield_YieldOutcome DEFAULT (0) FOR YieldOutcome. f Task 2: Alter the Marketing.Prospect(ProspectID).L14-2 Lab: Ensuring Data Integrity through Constraints Exercise 1: Constraint Design f Task 1: Review the supporting documentation 1.Yield ADD CONSTRAINT FK_Yield_Prospect FOREIGN KEY (ProspectID) REFERENCES Marketing. LanguageID). right-click the MarketDev database and click New Query.Yield ADD CONSTRAINT DF_Yield_RowID DEFAULT (NEWID()) FOR RowID.Yield ALTER COLUMN YieldOutcome int NOT NULL. Review the supplied table design requirements in the supporting documentation. GO ALTER TABLE Marketing.Language(LanguageID). GO ALTER TABLE Marketing. Type the query below in the query pane: ALTER TABLE Marketing.Yield ADD CONSTRAINT FK_Yield_Language FOREIGN KEY (LanguageID) REFERENCES Marketing. GO ALTER TABLE Marketing. GO ALTER TABLE Marketing. In Object Explorer.Yield ALTER COLUMN LanguageID nchar(6) NOT NULL. expand the Proseware server. GO 2. GO ALTER TABLE Marketing. expand Databases. .Yield ADD CONSTRAINT PK_Yield PRIMARY KEY CLUSTERED (ProspectID.Yield table 1. GO ALTER TABLE Marketing.Yield ALTER COLUMN LastUpdate datetime2 NOT NULL. GO ALTER TABLE Marketing.Yield ALTER COLUMN RowID uniqueidentifier NOT NULL. GO ALTER TABLE Marketing.

2.  Note: This should fail due to the primary key constraint.Yield (ProspectID. 'Excellent outcome'). 2. Notes) . In the toolbar.Yield (ProspectID. Note: This should execute without errors. GO 3. click Execute. In the toolbar. GO 3. Type the query below in the query pane: INSERT INTO Marketing. GO 3. LanguageID. click Execute. 2.'en'. LanguageID. f Task 4: Test the foreign key reference on prospect 1. Right-click the MarketDev database and click New Query. 'Excellent outcome'). Type the query below in the query pane: INSERT INTO Marketing. f Task 3: Test the foreign key reference on language 1.Yield (ProspectID. In the toolbar.'en'. Right-click the MarketDev database and click New Query.Lab: Ensuring Data Integrity through Constraints L14-3 3. f Task 2: Test the primary key 1. Challenge Exercise 2: Test the constraints (Only if time permits) f Task 1: Test the default values and data types 1. Type the query below in the query pane: INSERT INTO Marketing. LanguageID. In the toolbar. Type the query below in the query pane: INSERT INTO Marketing. 'Another excellent outcome'). Notes) VALUES (2.  Note: This should fail due to the foreign key reference. Notes) VALUES (1. SELECT * FROM Marketing. 2.Yield. LanguageID. click Execute. Notes) VALUES (1. Right-click the MarketDev database and click New Query.Yield (ProspectID. Right-click the MarketDev database and click New Query. click Execute.'ex'.

In the toolbar.'en'. 'Excellent outcome').L14-4 Lab: Ensuring Data Integrity through Constraints VALUES (29292. click Execute.  Note: This should fail due to the foreign key reference. . GO 3.

2. if the user is not already logged on: • On the Action menu. and then click Other User. In the Open Project window. . From the View menu. In the Virtual Machines list. click Execute on the toolbar. you must complete the following steps: 1. Maximize the Hyper-V Manager window. 9. On the host computer. 13. 3. 5. • In the Virtual Machine Connection window. click Start. double-click the query 00-Setup. click on the Revert toolbar icon. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. click the Ctrl-Alt-Delete menu item. Wait for the revert action to complete. If you are prompted to confirm that you want to revert. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. 12. 4. • Right-click 623XB-MIA-SQL and click Connect. In Virtual Machine Connection window. click All Programs. In the virtual machine. If the Server Manager window appears. click Full Screen Mode. click Open. and then close the Virtual Machine Connection window. • Log on using the following credentials: i. In the Virtual Machines list. type Proseware in the Server name text box. click Revert. click Start.Lab: Responding to Data Manipulation via Triggers L15-1 Module 15: Responding to Data Manipulation via Triggers Lab: Responding to Data Manipulation via Triggers Lab Setup For this lab. In the Authentication drop-down list box. check the Do not show me this console at logon check box and close the Server Manager window. User name: AdventureWorks\Administrator ii. In the File menu.ssmssln. In Solution Explorer.sql. Password: Pa$$w0rd 8. and click SQL Server Management Studio. 10. 14. click Microsoft SQL Server 2008 R2. wait until the Press CTRL+ALT+DELETE to log on message appears. you will use the available virtual machine environment. In the Virtual Machine Connection window. 15. and then click Hyper-V Manager. wait until the Press CTRL+ALT+DELETE to log on message appears. In Connect to Server window. in the Virtual Machine Connection window. point to Administrative Tools. When the query window opens. • Right-click 623XB-MIA-DC and click Connect. and click Project/Solution. • Click Switch User. 7. 6. open the project D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ. Before you begin the lab. 11. • In the Virtual Machine Connection window. select Windows Authentication and click Connect.

In the toolbar.CampaignAudit table. Note: The output should be similar to the following: . 2. expand Proseware.TR_CampaignBalance_Update ON Marketing. END.CampaignID WHERE deleted. f Task 3: Write code to test the behavior of the trigger 1. RemainingBalance) SELECT SYSDATETIME().CampaignBalance.CampaignAudit (AuditTime. expand Tables.RemainingBalance FROM deleted INNER JOIN inserted ON deleted. Right-click the MarketDev database and click New Query. In Object Explorer. f Task 2: Design a trigger to meet the requirements as stated in the scenario for this exercise 1. Review the table design. Right-click the MarketDev database and click New Query.CampaignAudit. In the toolbar. expand MarketDev. INSERT Marketing. expand Marketing.CampaignBalance. GO 3. click Execute.MoveCampaignBalance 3. Type the query below in the query pane: EXEC Marketing. Review the supplied table requirements in the supporting documentation for Marketing. ModifyingUser. and expand Columns. GO 3.2.RemainingBalance > 10000 OR inserted.RemainingBalance > 10000. inserted.CampaignID = inserted. click Execute. 3. Type the query below in the query pane: CREATE TRIGGER Marketing. expand Databases. 2.L15-2 Lab: Responding to Data Manipulation via Triggers Exercise 1: Creating and Testing the Audit Trigger f Task 1: Review the supporting documentation and existing system 1. GO SELECT * FROM Marketing. 2.CampaignBalance AFTER UPDATE AS BEGIN SET NOCOUNT ON. ORIGINAL_LOGIN(). GO SELECT * FROM Marketing.101000.

CampaignID WHERE ABS(deleted. expand Databases. Type the query below in the query pane: . INSERT Marketing. Challenge Exercise 2: Improve the Audit Trigger (Only if time permits) f Task 1: Modify the trigger based on the updated requirements 1. expand Tables.CampaignID = inserted. and expand Triggers. END.CampaignBalance AFTER UPDATE AS BEGIN SET NOCOUNT ON. Right-click the MarketDev database and click New Query. expand Marketing.CampaignAudit table 1. inserted.RemainingBalance . GO 2.inserted.TR_CampaignBalance_Update ON Marketing. 4.RemainingBalance) > 10000. f Task 2: Delete all rows from the Marketing. expand Proseware. RemainingBalance) SELECT SYSDATETIME(). 2. 5. Right-click the MarketDev database and click New Query. click Execute. ORIGINAL_LOGIN(). In Object Explorer. ModifyingUser. 3. expand MarketDev.CampaignAudit (AuditTime. Type the query below in the query pane: ALTER TRIGGER Marketing. In the toolbar.RemainingBalance FROM deleted INNER JOIN inserted ON deleted.CampaignAudit.Lab: Responding to Data Manipulation via Triggers L15-3 Note: The dates and times will depend upon when you execute the code. Review the trigger design.

click Execute. In the toolbar.MoveCampaignBalance 3. GO EXEC Marketing.L15-4 Lab: Responding to Data Manipulation via Triggers DELETE FROM Marketing.CampaignBalance. Note: The output should be similar to the following: Note: The dates and times will depend upon when you execute the code. 2.CampaignAudit.CampaignAudit. Type the query below in the query pane: SELECT * FROM Marketing. GO EXEC Marketing.MoveCampaignBalance 3. . GO 3. In the toolbar.1010. GO SELECT * FROM Marketing.2.10100. Right-click the MarketDev database and click New Query. click Execute. GO 3.2. f Task 3: Test the modified trigger 1.

• Log on using the following credentials: i. • In the Virtual Machine Connection window. • Click Switch User. 7. click Start. double-click the query 00-Setup. Before you begin the lab. User name: AdventureWorks\Administrator ii. In the Virtual Machine Connection window. click Revert. wait until the Press CTRL+ALT+DELETE to log on message appears. in the Virtual Machine Connection window. Review the supplied proposed SQLCLR functionality list in the supporting documentation. and click SQL Server Management Studio. and click Project/Solution.sql. select Windows Authentication and click Connect. In the Authentication drop-down list box. and then click Hyper-V Manager. and then click Other User. 4. 3. 2. In the File menu. From the View menu. 14. 9. click the Ctrl-Alt-Delete menu item. In the Virtual Machines list. Password: Pa$$w0rd 8. 12. click Start. Maximize the Hyper-V Manager window. check the Do not show me this console at logon check box and close the Server Manager window. 1. In the Virtual Machines list. you must complete the following steps: On the host computer. . Wait for the revert action to complete. • Right-click 623XB-MIA-SQL and click Connect. click Open. If you are prompted to confirm that you want to revert. 13. 15. click All Programs. In Solution Explorer. click Full Screen Mode. Exercise 1: Assess Proposed CLR Code  Task 1: Review the supporting documentation 1.Lab: Implementing Managed Code in SQL Server L16-1 Module 16: Implementing Managed Code in SQL Server 2008 R2 Lab: Implementing Managed Code in SQL Server Lab Setup For this lab. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start.ssmssln. if the user is not already logged on: • On the Action menu. In Connect to Server window. click Execute on the toolbar. 11. 5. click Microsoft SQL Server 2008 R2. open the project D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ. 10. In the Open Project window. In Virtual Machine Connection window. If the Server Manager window appears. click on the Revert toolbar icon. and then close the Virtual Machine Connection window. type Proseware in the Server name text box. you will use the available virtual machine environment. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. When the query window opens. point to Administrative Tools. • In the Virtual Machine Connection window. • Right-click 623XB-MIA-DC and click Connect. wait until the Press CTRL+ALT+DELETE to log on message appears. In the virtual machine. 6.

Function that formats phone numbers as strings. and right-click the MarketDev database and click New Query. and right-click the master database and click New Query. good use of external access. In Object Explorer. 3.DLL' WITH PERMISSION_SET = EXTERNAL_ACCESS. Type the query below in the query pane: EXEC sp_configure 'clr enabled'. A new Customer data type. Function that counts rows in a table. under Proseware expand Databases. Trigger that records balance movements with a value of more than 1000. Yes. GO 2. Type the query below in the query pane: CREATE ASSEMBLY SQLCLRDemo FROM 'D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ\SQLCLRDemo.  Task 2: Catalog the assembly and the functions contained within it 1. only involves data access.1. Proposed SQLCLR Functionality Should be implemented Table-valued function that returns a list of files Yes. The following components should be included in SQL CLR. only involves data access. good use of string handling. . under Proseware expand Databases. In Object Explorer. No. No. GO RECONFIGURE. good use of external access.L16-2 Lab: Implementing Managed Code in SQL Server  Task 2: For each object listed. Stored procedure that writes an XML file for a given XML parameter. determine if implementing it in managed code is appropriate or not 1. No. GO ALTER DATABASE MarketDev SET TRUSTWORTHY ON. not an object oriented database. In the toolbar. Exercise 2: Implement a CLR Assembly  Task 1: Ensure the database is configured appropriately to support an EXTERNAL_ACCESS assembly 1. GO 2. Yes. click Execute. in a particular folder. expand System Databases.

Type the query below in the query pane: CREATE FUNCTION dbo.CLRDemoClass].CLRDemoClass].IsValidEmailAddress('test@somewhere.FolderList( 'D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ'. Highlight the query above and in the toolbar click Execute.assemblies.FolderList. Type the query below in the query pane: SELECT dbo.FormatAustralianPhoneNumber.[SQLCLRDemo.IsValidEmailAddress. .FolderList(@RequiredPath NVARCHAR(4000). 2.FormatAustralianPhoneNumber('9 87 2 41 23'). click Execute.  Task 3: Test the functions contained within the assembly 1. Type the query below in the query pane: CREATE FUNCTION dbo.[SQLCLRDemo. Type the query below in the query pane: SELECT * FROM sys. SELECT dbo. In the toolbar. 4. GO 11. Highlight the query above and in the toolbar click Execute. 8. Highlight the query above and in the toolbar click Execute. 6. GO SELECT dbo. GO SELECT * FROM dbo.somewhere. Right-click the MarketDev database and click New Query.CLRDemoClass]. In the toolbar.Lab: Implementing Managed Code in SQL Server L16-3 3. 10.@FileMask NVARCHAR(4000)) RETURNS TABLE (FileName NVARCHAR(4000)) AS EXTERNAL NAME SQLCLRDemo.'*.IsValidEmailAddress(@email NVARCHAR(4000)) RETURNS BIT AS EXTERNAL NAME SQLCLRDemo.com').[SQLCLRDemo. Highlight the query above and in the toolbar click Execute.FormatAustralianPhoneNumber('039 87 2 41 23').assembly_files. GO 9. GO SELECT dbo. GO 7.FormatAustralianPhoneNumber(@PhoneNumber NVARCHAR(4000)) RETURNS NVARCHAR(4000) AS EXTERNAL NAME SQLCLRDemo. GO 5.IsValidEmailAddress('test.txt'). GO 3. Type the query below in the query pane: CREATE FUNCTION dbo.com'). click Execute. SELECT * FROM sys.FormatAustralianPhoneNumber('0419201410'). SELECT dbo.

ToString().[SQLCLRDemo.CompressedLength().TestTable VALUES('Some GO SELECT TextValue. In the toolbar. GO 3. 2. Right-click the MarketDev database and click New Query. In the toolbar. In the toolbar.CompressionPercentage() FROM dbo. TextValue. Type the query below in the query pane: CREATE TABLE dbo.Product WHERE Color = 'Black'. GO SELECT dbo.AggString]. . Right-click the MarketDev database and click New Query.TestTable.AggString(@s nvarchar(4000)) RETURNS nvarchar(4000) EXTERNAL NAME SQLCLRDemo. GO 3. 4.1). 8. 2. Type the query below in the query pane: CREATE AGGREGATE dbo. Right-click the MarketDev database and click New Query.AggString(DISTINCT ProductNumber) FROM Marketing.TestTable ( RecID int IDENTITY(1.zVarChar EXTERNAL NAME SQLCLRDemo.[SQLCLRDemo.zVarChar]. TextValue zVarchar ). GO compressible data'). Type the query below in the query pane: CREATE TYPE dbo.  Task 2: Catalog and test the user-defined data type 1. click Execute. click Execute. TextValue. Type the query below in the query pane: INSERT INTO dbo. click Execute. 5. Right-click the MarketDev database and click New Query. 7.L16-4 Lab: Implementing Managed Code in SQL Server Challenge Exercise 3: Implement a CLR User-defined Aggregate and CLR Userdefined Data Type (Only if time permits)  Task 1: Catalog and test the user-defined aggregate 1. GO 6.

Right-click the MarketDev database and click New Query. SET @TestString = 'Some compressible PRINT @TestString.Lab: Implementing Managed Code in SQL Server L16-5 SELECT AVG(TextValue. .TestTable.CompressionPercentage()) FROM dbo. In the toolbar. GO PRINT zVarChar::Compress( 'Some compressible GO value'). 10. GO 9. click Execute. Type the query below in the query pane: DECLARE @TestString zVarChar. click Execute. In the toolbar. GO DROP TABLE dbo.CompressedValue(). value'. 12. 11.TestTable.

L16-6 Lab: Implementing Managed Code in SQL Server .

13. In the Virtual Machines list. In the Virtual Machine Connection window. 11. In the Authentication drop-down list box. in the Virtual Machine Connection window. On the host computer.sql. In the File menu. 2. 12. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. • Log on using the following credentials: 4. you will use the available virtual machine environment. click All Programs. • Right-click 623XB-MIA-SQL and click Connect. click Start. When the query window opens. 8.Lab: Storing XML Data in SQL Server L17-1 Module 17: Storing XML Data in SQL Server 2008 R2 Lab: Storing XML Data in SQL Server Lab Setup For this lab. i. In Virtual Machine Connection window. In the Virtual Machines list. point to Administrative Tools. • Click Switch User. click Open. • In the Virtual Machine Connection window. wait until the Press CTRL+ALT+DELETE to log on message appears. open the project D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ. check the Do not show me this console at logon check box and close the Server Manager window. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. • Right-click 623XB-MIA-DC and click Connect. 6. Maximize the Hyper-V Manager window. if the user is not already logged on: • On the Action menu. click Start.ssmssln. ii. click the Ctrl-Alt-Delete menu item. click Full Screen Mode. In the virtual machine. double-click the query 00-Setup. In the Open Project window. Before you begin the lab. and click Project/Solution. 14. wait until the Press CTRL+ALT+DELETE to log on message appears. click on the Revert toolbar icon. click Revert. and then close the Virtual Machine Connection window. click Microsoft SQL Server 2008 R2. In Connect to Server window. User name: AdventureWorks\Administrator  Password: Pa$$w0rd  From the View menu. In Solution Explorer. 15. click Execute on the toolbar. select Windows Authentication and click Connect. 3. and then click Hyper-V Manager. Wait for the revert action to complete. 5. and then click Other User. If the Server Manager window appears. and click SQL Server Management Studio. If you are prompted to confirm that you want to revert. . 9. 10. 7. • In the Virtual Machine Connection window. you must complete the following steps: 1. type Proseware in the Server name text box.

Script 17.9 separately. and review the results 1. Review the supplied Use Cases requirements in the supporting documentation. Relational data that is being passed through a system but not processed within it. Should be database columns.1 Create a table with an xml column CREATE TABLE #Invoices ( InvoiceID int. Only if the data is being sent and received as XML.sql. CustomerID int. Highlight and execute the first command block as shown: USE tempdb. Double-click the script 61 – Lab Exercise 2. ItemList xml). Storing attributes that are nested (that is attributes stored within attributes). DECLARE @itemDoc xml. 2.2 Use implicit casting to assign an xml variable DECLARE @itemString nvarchar(2000).Script 17. Exercise 2: Investigate the Storage of XML Data in Variables f Task 1: Review and execute the queries. GO -. f Task 2: Determine whether each is appropriate for XML 1. SET @itemDoc = @itemString. Highlight and execute scripts 17. No Perhaps Yes Not standard relational data.1 to 17. comparing the results of each script with the script comment. SET @itemString = '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'. GO 3. Should be implemented Yes Reason Data is already XML and does not need to be processed. . -. Storing attributes for a customer. SalesDate datetime.L17-2 Lab: Storing XML Data in SQL Server Exercise 1: Appropriate Usage of XML Data Storage in SQL Server f Task 1: Review the list of Use Cases 1. The following components should be implemented Use Cases Requirements Existing XML data that is stored but not processed. in Solution Explorer.

SET @convertedDoc = CONVERT(xml.7 Well-formed fragment. GetDate().Script 17. GO -. DECLARE @convertedDoc xml. @itemDoc). GetDate(). 2. 2.4 Explicitly cast string to xml DECLARE @varToCast nvarchar(2000).Lab: Storing XML Data in SQL Server L17-3 INSERT INTO #Invoices VALUES (1. GetDate(). SET @varToCast = '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'. INSERT INTO #Invoices VALUES(1.6 Well-formed document. GetDate().3 Use implicit casting to assign a string constant INSERT INTO #Invoices VALUES (1.5 Explicitly convert string to xml DECLARE @varToConvert nvarchar(2000). GetDate(). 2. 2. GO -. SELECT * FROM #Invoices. '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>').Script 17.Script 17. GO -. SELECT * FROM #Invoices. SELECT * FROM #Invoices. '<Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/>'). SET @castedDoc = CAST(@varToCast AS xml). @convertedDoc). 2. INSERT INTO #Invoices VALUES(1. SET @varToConvert = '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'. GO -. GO -. 2. SELECT * FROM #Invoices. GetDate(). '<?xml version="1. This will succeed INSERT INTO #Invoices VALUES (1. DECLARE @castedDoc xml. SELECT * FROM #Invoices.Script 17.Script 17. @castedDoc).0" ?> <Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'). This will succeed INSERT INTO #Invoices VALUES (1. . @varToConvert).

GO 4.Script 17. 17.9 Clean up the temporary table DROP TABLE #Invoices. '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/>').7 17. Well-formed document. GO . Exercise 3: Investigate the use of XML Schema Collections f Task 1: Review and execute the queries. This will succeed. SELECT * FROM #Invoices. This will fail. Double-click the script 71 – Lab Exercise 3. Highlight and execute the first command block as shown: USE tempdb. Query Number 17. Use implicit casting to assign an xml variable. One row is inserted. GO -. GetDate(). Output Command completed successfully. 17.4 17.2 Query Title Create a table with an xml column.L17-4 Lab: Storing XML Data in SQL Server SELECT * FROM #Invoices. One row is inserted. One row is inserted.3 One row is inserted.1 17. Command completed successfully.Script 17. Command will fail due to incorrect XML format. Use implicit casting to assign a string constant.9 Clean up the temporary table.8 Well-formed fragment. 17.8 Not well-formed.6 One row is inserted. Not well-formed. 2. This will fail INSERT INTO #Invoices VALUES (1. in Solution Explorer. Explicitly convert string to xml. One row is inserted. 2. This will succeed. Explicitly cast string to xml. 17.sql. and review the results 1. GO -.5 17. Review the results from each script.

xml_collection_id WHERE c.xml_schema_collections AS c ON cp.adventure-works.0" ?> <xsd:schema targetNamespace="http://schemas. . -. GO -.Script 17.w3.10 to 17.Script 17.xml_collection_id = c. GO 4. Output Schema collection is created.Lab: Storing XML Data in SQL Server L17-5 3.com/EmployeeResume" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsd="http://www. Note the schema collection values in the kind_desc column.10 Query Title Create an xml schema collection for resumes. not as the original -schema text SELECT cp.11 Retrieve information about the components in the schema collection -Note that schemas are stored as components. Review the results from each script. comparing the results of each script with the script comment. 17.com/EmployeeResume" xmlns="http://schemas. Highlight and execute scripts 17.11 separately.10 Create an xml schema collection for resumes CREATE XML SCHEMA COLLECTION ResumeSchemaCollection AS N'<?xml version="1.* FROM sys.11 Retrieve information about Ten rows showing how the individual components of the components in the the XML schema collection are stored.adventure-works.name = 'ResumeSchemaCollection'.org/2001/XMLSchema" > <xsd:element name="resume"> <xsd:complexType> <xsd:sequence> <xsd:element name="name" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="employmentHistory"> <xsd:complexType> <xsd:sequence minOccurs="1" maxOccurs="unbounded"> <xsd:element name="employer"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="endDate" use="optional"/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>'.xml_schema_components AS cp JOIN sys. Query Number 17.

-. GO -.0" ?> <resume xmlns="http://schemas.0" ?> <resume xmlns="http://schemas.com/EmployeeResume"> <name>Guy Gilbert</name> </resume>').Script 17. Double-click the script 81 – Lab Exercise 4.L17-6 Lab: Storing XML Data in SQL Server Challenge Exercise 4: Investigate the Creation of Database Columns Based on XML (Only if time permits) f Task 1: Review and execute the queries.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>').0" ?> <resume xmlns = "http://schemas. '<?xml version="1.15 Use CONTENT keyword CREATE TABLE #EmployeeResumeContent ( EmployeeID int.12 to 17.Script 17.Script 17.Script 17.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>').20 separately.adventure-works.16 Insert a single document into a CONTENT column INSERT INTO #EmployeeResumeContent VALUES (1. Resume xml (CONTENT ResumeSchemaCollection)). SELECT * FROM #EmployeeResume. Highlight and execute the first command block as shown: USE tempdb. GO -. and review the results 1.13 Insert valid XML INSERT INTO #EmployeeResume VALUES (1.12 Create a table with a typed xml column for documents CREATE TABLE #EmployeeResume ( EmployeeID int. GO -. Highlight and execute scripts 17.adventure-works. comparing the results of each script with the script comment. '<?xml version="1.adventure-works. Resume xml (ResumeSchemaCollection)). GO -.Script 17. in Solution Explorer. GO 3. 2. .14 Try to insert invalid XML (this will fail) INSERT INTO #EmployeeResume VALUES (1. '<?xml version="1.sql.

18 Use DOCUMENT keyword CREATE TABLE #EmployeeResumeDocument ( EmployeeID int.adventure-works. GO -.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>').com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>'). . INSERT INTO #EmployeeResumeDocument VALUES (1. Resume xml (DOCUMENT ResumeSchemaCollection)). ' <resume xmlns="http://schemas. GO -.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>'). ' <resume xmlns="http://schemas.17 Insert multiple valid elements into a CONTENT column INSERT INTO #EmployeeResumeContent VALUES (1.19 Insert a single document into a DOCUMENT column INSERT INTO #EmployeeResumeDocument VALUES (1. SELECT * FROM #EmployeeResumeContent.adventure-works. This will fail.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> </employmentHistory> </resume> <resume xmlns="http://schemas.adventure-works. GO -. SELECT * FROM #EmployeeResumeDocument.Script 17.20 Insert multiple valid elements into a DOCUMENT column.Script 17.0" ?> <resume xmlns="http://schemas. GO -. '<?xml version="1.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> </employmentHistory> </resume> <resume xmlns="http://schemas.Script 17.adventure-works.Script 17.Lab: Storing XML Data in SQL Server L17-7 SELECT * FROM #EmployeeResumeContent.

17.12 Query Title Output Create a table with a typed xml column Command completed successfully. This will fail.17 One row is inserted. Insert multiple valid elements into a CONTENT column.L17-8 Lab: Storing XML Data in SQL Server SELECT * FROM #EmployeeResumeDocument. it did not meet the required schema. GO 4.15 17. 17. for documents. Insert a single document into a CONTENT column.13 17. Insert a single document into a DOCUMENT column. Review the results from each script. even though no root element is present.19 Use DOCUMENT keyword. 17. Insert valid XML. Query Number 17. One row is inserted. Command completed successfully.16 Use CONTENT keyword. Command completed successfully. .20 No row is inserted as no root element is present.14 17. Try to insert invalid XML (this will fail). Insert multiple valid elements into a DOCUMENT column. One row is inserted.18 17. 17. Note the row is inserted. Even though wellformed XML was supplied. One row is inserted. No rows are inserted.

and then close the Virtual Machine Connection window.sql. click Start. 2. When the query window opens. • Log on using the following credentials: i. in Solution Explorer. 3. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. 7. and then click Other User. open the project D:\6232B_Labs\6232B_18_PRJ\6232B_18_PRJ. you must complete the following steps: 1. . In the virtual machine. check the Do not show me this console at logon check box and close the Server Manager window. and then click Hyper-V Manager. click Microsoft SQL Server 2008 R2. In the Virtual Machines list. 13. wait until the Press CTRL+ALT+DELETE to log on message appears. In Solution Explorer. In the Virtual Machine Connection window. In Connect to Server window. Wait for the revert action to complete. Password: Pa$$w0rd 8. User name: AdventureWorks\Administrator ii. • Right-click 623XB-MIA-DC and click Connect.sql. click Open. In the Authentication drop-down list box. type Proseware in the Server name text box. From the View menu. 12. If the Server Manager window appears. Before you begin the lab. Exercise 1: Learn to query SQL Server data as XML f Task 1: Review and execute the query and review the results 1. select Windows Authentication and click Connect. • In the Virtual Machine Connection window. click Revert. click Execute on the toolbar. If you are prompted to confirm that you want to revert. 11. In Virtual Machine Connection window. and click SQL Server Management Studio. wait until the Press CTRL+ALT+DELETE to log on message appears. In the Virtual Machines list. 9. click on the Revert toolbar icon. 5. double-click the query 00-Setup. click the Ctrl-Alt-Delete menu item. click Full Screen Mode. 15. 4. In the File menu. In the Open Project window. click Start. Maximize the Hyper-V Manager window. 14. and click Project/Solution. point to Administrative Tools. 6. click All Programs. you will use the available virtual machine environment. • Click Switch User. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. in the Virtual Machine Connection window.Lab: Querying XML Data in SQL Server L18-1 Module 18: Querying XML Data in SQL Server 2008 R2 Lab: Querying XML Data in SQL Server Lab Setup For this lab.ssmssln. On the host computer. Double-click the script 51 – Lab Exercise 1. 10. • In the Virtual Machine Connection window. • Right-click 623XB-MIA-SQL and click Connect. if the user is not already logged on: • On the Action menu.

-.Script 18.Product AS Product.3 NULL columns with ELEMENTS SELECT ProductID. ListPrice . TYPE) AS Description FROM Marketing.Product FOR XML AUTO.1 to 18.ProductModelID = Product.Product AS Product FOR XML AUTO. GO -.L18-2 Lab: Querying XML Data in SQL Server In the query below. ELEMENTS XSINIL. GO -. Color FROM Marketing.7 PATH mode SELECT ProductID AS "@ProductID". ProductName. ProductName. GO -. GO -. ListPrice.2 ELEMENTS with RAW mode SELECT ProductID. ProductName. Color AS "Description/text()" FROM Marketing.Script 18.Script 18.1 FOR XML AUTO Use MarketDev GO SELECT ProductID. GO -. ELEMENTS.Product FOR XML RAW. ProductName. ListPrice FROM Marketing.Script 18. ROOT('AvailableItems'). highlight and execute scripts 18. ListPrice FROM Marketing.Product AS Product FOR XML AUTO. Description.9 Named element in RAW modes SELECT ProductID. ListPrice FROM Marketing. GO -.ProductModelID.ProductDescription AS Description WHERE Description. comparing the results of each script with the script comment. Size AS "Description/@Size".3 SELECT ProductID. ELEMENTS XSINIL.6 Nested XML with TYPE SELECT ProductID. ProductName.ProductModelID FOR XML AUTO.9 separately.Script 18. ELEMENTS.Product AS Product FOR XML AUTO.8 ROOT directive SELECT ProductID. ProductName. ProductName.Description FROM Marketing. Color FROM Marketing. ProductName. GO -.Script 18.4 Note the effect of the column alias compared to 18. (SELECT Description. XMLSCHEMA.Product AS Product FOR XML PATH.Script 18.Script 18. GO -.5 Inline XSD schema SELECT ProductID.Product FOR XML AUTO. ProductName AS "*". ListPrice FROM Marketing.Script 18.

GetAvailableModelsAsXML AS BEGIN SELECT p. GO Query Number 18.ListPrice. based on the alias column alias name of the table. Nested XML with TYPE.Product AS Product FOR XML RAW('AvailableItem'). Note that rows with a value in the Description column show that value as XML.Color. Note the “AvailableItems” root node.1 Query Title FOR XML AUTO. Other products show the color. p.4 Note the effect of the Note the element name is now Product. .ProductName. Review the supplied stored procedure specification in the supporting documentation for WebStock. Products without color show xsi:nil=”true”.8 18.3. NULL columns with ELEMENTS. Inline XSD schema. f Task 2: Create the stored procedure 1. Named element in RAW modes. p. p.9 ROOT directive. PATH Mode. Note how the output can be constructed with a PATH query.5 18. 2. 18.GetAvailableModelsAsXML. In the output locate each of the elements in the SELECT clause. Note the element name is based on the table name. p. pm. Note the element centric output and the element name is “row”. Note the “AvailableItem” ElementName. 18.ProductID. Exercise 2: Write a stored procedure returning XML f Task 1: Review the requirements 1. Right-click the MarketDev database and click New Query.Lab: Querying XML Data in SQL Server L18-3 FROM Marketing. compared to 18.7 18. 18.ProductModelID. Output One row per product.SellStartDate. Type the query below in the query pane: CREATE PROCEDURE WebStock.3 18.2 ELEMENTS with RAW mode.6 18. Note the inclusion of an XSD schema.

Right-click the MarketDev database and click New Query.UpdateSalesTerritoriesByXML.SalesTerritoryID = spm. ROOT('AvailableModels'). UPDATE sp SET sp.'SalespersonMods/SalespersonMod/Mods/Mod'. 2. .SalespersonID = spm. click Execute. END. GO 3. @SalespersonMods. EXEC master. In the toolbar.SellStartDate IS NOT NULL AND p.sp_xml_removedocument @Handle. Right-click the MarketDev database and click New Query.SalespersonID. GO 3.L18-4 Lab: Querying XML Data in SQL Server pm. END. In the toolbar. Type the query below in the query pane: CREATE PROCEDURE Marketing.SellStartDate. Review the supplied stored procedure specification in the supporting documentation for Marketing.ProductModel FROM Marketing./.SellEndDate IS NULL ORDER BY p.ProductModel AS pm ON p.Salesperson AS sp INNER JOIN OPENXML(@Handle. p. 2.. f Task 3: Test the stored procedure 1. click Execute.1) WITH (SalesTerritoryID int '@SalesTerritoryID'.dbo. Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits) f Task 1: Review the requirements 1. SalespersonID int '. EXEC master.ProductModelID = pm.GetAvailableModelsAsXML.UpdateSalesTerritoriesByXML ( @SalespersonMods xml ) AS BEGIN DECLARE @Handle int. In the toolbar.ProductModelID WHERE p.. Type the query below in the query pane: EXEC WebStock.Product AS p INNER JOIN Marketing./@SalespersonID') AS spm ON sp.sp_xml_preparedocument @Handle OUTPUT.dbo. GO 3. f Task 2: Create the stored procedure 1.SalesTerritoryID FROM Marketing. click Execute.ProductName FOR XML RAW('AvailableModel').

In the toolbar. SET @SalespersonMods = '<SalespersonMods> <SalespersonMod SalespersonID="274"> <Mods> <Mod SalesTerritoryID="3"/> </Mods> </SalespersonMod> <SalespersonMod SalespersonID="278"> <Mods> <Mod SalesTerritoryID="4"/> </Mods> </SalespersonMod> </SalespersonMods>'.UpdateSalesTerritoriesByXML @SalespersonMods. EXEC Marketing.Lab: Querying XML Data in SQL Server L18-5 f Task 3: Test the stored procedure 1. GO 3. . Right-click the MarketDev database and click New Query. 2. Type the query below in the query pane: DECLARE @SalespersonMods xml.Salesperson. click Execute. GO SELECT * FROM Marketing.

L18-6 Lab: Querying XML Data in SQL Server .

open the project D:\6232B_Labs\6232B_19_PRJ\6232B_19_PRJ. in the Virtual Machine Connection window. you must complete the following steps: 1. In the virtual machine. . click Revert. If you are prompted to confirm that you want to revert. In the Virtual Machines list. • Right-click 623XB-MIA-DC and click Connect. In Virtual Machine Connection window. • In the Virtual Machine Connection window. and click Project/Solution. Password: Pa$$w0rd 8. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. • Click Switch User. If the Server Manager window appears. 9. 6. In the Open Project window. type Proseware in the Server name text box. and then click Hyper-V Manager. and then close the Virtual Machine Connection window. In the Virtual Machines list. and click SQL Server Management Studio. 12. • Log on using the following credentials: i.ssmssln. Before you begin the lab. 4. if the user is not already logged on: • On the Action menu. 14. in Solution Explorer. 3. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. wait until the Press CTRL+ALT+DELETE to log on message appears.sql. click Full Screen Mode. click the Ctrl-Alt-Delete menu item. click on the Revert toolbar icon. 13. click All Programs. Exercise 1: Familiarity With Geometry Data Type f Task 1: Review and execute the sample script 1. and then click Other User. 15. In Connect to Server window. In the Virtual Machine Connection window. click Start. Double-click the script 51 – Lab Exercise 1. • In the Virtual Machine Connection window. 5. 2. select Windows Authentication and click Connect. Maximize the Hyper-V Manager window. click Execute on the toolbar. In Solution Explorer. point to Administrative Tools. In the Authentication drop-down list box. double-click the query 00-Setup. 7. 10. you will use the available virtual machine environment.Lab: Working with SQL Server Spatial Data L19-1 Module 19: Working with SQL Server 2008 R2 Spatial Data Lab: Working with SQL Server Spatial Data Lab Setup For this lab. In the File menu. click Start. User name: AdventureWorks\Administrator ii. From the View menu. click Open. When the query window opens. wait until the Press CTRL+ALT+DELETE to log on message appears. check the Do not show me this console at logon check box and close the Server Manager window. 11. On the host computer.sql. Wait for the revert action to complete. • Right-click 623XB-MIA-SQL and click Connect. click Microsoft SQL Server 2008 R2.

60 40.90 10. 5 5.10 40.40 10.40 10.Script 19.0). 25 5. @Shape2 GEOMETRY. @Shape2 GEOMETRY.0). GO -. -. 30 25))'. 40 40. 65 45.40 10. highlight and execute scripts 19.Script 19. 40 10. SELECT @Shape AS Square. @Shape2 GEOMETRY. SELECT @Shape AS ColoredArea. SET @Shape = GEOMETRY::STPolyFromText('POLYGON((0 0.Script 19. 45 45.3 Draw a more complex shape DECLARE @Shape GEOMETRY. comparing the results of each script with the script comment. 60 40.Script 19. SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((30 25. In the query below.0).4 Multiple shapes DECLARE @Shape1 GEOMETRY.1 to 19.1 Draw a square USE tempdb. 95 45. SELECT @Shape1 AS Multishapes UNION ALL SELECT @Shape2. 90 40. 45 45. 40 40.60 20.10 40.30 40. 10 10))'. 5 5. GO -. SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10. GO DECLARE @Shape GEOMETRY.0). 45 45.6 Union of the two shapes DECLARE @Shape1 GEOMETRY. SELECT @Shape1.note the 6522 error and the wrapped error message BEGIN TRY DECLARE @Shape GEOMETRY.0). 10 10))'.Script 19.7 Intersection of shapes .0). SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((60 25. 40 40.L19-2 Lab: Working with SQL Server Spatial Data 2.0).5 5))'.40 10.10 10. 65 45. 40 40. 10 10))'. 10 10))'.10 40. GO -. 5 5. END CATCH. 45 45.20 15. 55 5. 60 25))'. 25 5. GO -. SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10. 40 40. 60 40.Script 19. SET @Shape = GEOMETRY::STGeomFromText('POLYGON ((10 10.30 40.0 15.9 separately. 10 40. SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10.0).60 20. GO -. SELECT @Shape1 AS Overlapping UNION ALL SELECT @Shape2. 30 25))'. SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((30 25.2 Try an invalid value . SET @Shape = GEOMETRY::STGeomFromText('POLYGON ((10 10. 5 5.10 40.Script 19.5 Intersecting shapes DECLARE @Shape1 GEOMETRY. 0). GO -.STUnion(@Shape2) AS Unioned. 10 10))'. END TRY BEGIN CATCH SELECT ERROR_MESSAGE().

228744506835938.650595664978027.58901977539063 -14. 143.92631530761719 -43. 148.37675476074219 -12.96563720703125 -35.12933349609375 -42.415578842163086. 147.29037475585938 26.438838958740234. 150.03501892089844 -25.STIntersection(@Shape2).27639770507813 24.993001937866211. 144.Lab: Working with SQL Server Spatial Data L19-3 DECLARE @Shape1 GEOMETRY.61477661132813 38.90054321289063 -40. 60 40. 153.800580978393555.69715881347656 -28. 153.82795715332031 -42. SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10.030624389648438.185646057128906. 149. 150.546205520629883.352115631103516. 144. 146.650703430175781. 144. 143.876548767089844.10769653320313 .823896408081055. 145.4830322265625 -42.682428359985352.30514526367188 -21. 150. 151.91603088378906 -37.987766265869141. 152. 142.26838684082031 -14.329910278320312.96830749511719 -32.075611114501953.223194122314453.73284912109375 -14. 145.713462829589844. SELECT @Shape1 AS Intersected UNION ALL SELECT @Shape2 UNION ALL SELECT @Shape1. 30 25))'. 152.18850708007813 -37.724786758422852. 151. 146.60 20.777362823486328. 151. ((142.25955200195313 -40.210777282714844.58587646484375 -41. 145.02470397949219 -38. 145. 45 45. 153. 148.52163696289063 -24.77070617675781 -20.93380737304688 -24.40 10.296232223510742.72958374023438 -39.34538269042969 -43. 153.065319061279297. 146. SET @Australia = geometry::STGeomFromText('MULTIPOLYGON (((146.47319030761719 -41.796828269958496.17445373535156 -12. 148.704837799072266)).637355804443359.07573413848877.17660522460938 20.080898284912109.902679443359375.704837799072266. 148.61637878417969 -19. 145.824363708496094.66114616394043. 143. 150.14988708496094 -27.19784545898438 -17.07258605957031 -41.575309753417969.73957824707031 -38.898410797119141.Script 19. 152. 145. 145. 40 40.473457336425781.70791625976563 -38. 145.901708602905273.324020385742188. 147.239631652832031.401203155517578.52920532226563 -16.24066162109375 -38.859695434570312.52542114257813 -19. 146.517995834350586. 10 10))'.17349243164063 -38. 148. 144.37985229492188 -32.17552185058594 31. 153. SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((30 25.806430816650391.111736297607422.56846618652344 -38.90739440917969 -20.57481384277344 -12. 151.89729309082031 -22. 148. 143.14321899414063 -30.38800048828125 -15.38616943359375 -42.4251708984375 35.0).56816101074219 -33.788833618164062.30 40. GO -.00613403320313 -23.8 Draw Australia DECLARE @Australia geometry. 146. 152.27273559570313 -26.845218658447266. 147.84793090820313 -11.577156066894531.582916259765625. 148.236156463623047. 145.94683837890625 -14. 5 5.163665771484375.68940734863281 -25.50288391113281 38. 150. 153.91639709472656 43. 153.12821960449219 -18. 25 5.04315185546875.91639709472656 -43.048786163330078. 145.0).22093200683594 22.291374206542969.49560546875.76042175292969 -22. 148. 146.147617340087891.9527587890625.60006713867188 -28.14051628112793.501945495605469. 149.104367256164551.079109191894531.464195251464844. 149.80001831054688 -41.54121398925781 -10.448851585388184. @Shape2 GEOMETRY.95124816894531 -38. 143.70556640625.503929138183594. 144.52291870117188 -41. 142.454490661621094. 144. 65 45.424533843994141. 150. 146.1484375 -22.6771354675293.02713012695313 -11.239715576171875. 143.10 40. 147.306673049926758. 153.

139. 113.76168060302734 -33.320106506347656. 137.23101043701172 22.21568298339844 37. 114. 122.749591827392578. 115.45505523681641 -35.57157897949219 -35. 138.016206741333008.80059051513672 -20.024333953857422. 134. 138. 113.503608703613281.62245941162109 -20.27078247070313 33. 113.076744079589844.0718994140625 -32. 113.008373260498047. 118.71554565429688 -34.325000762939453. 114. 113.820150375366211. 115.02070426940918. 141.91609191894531 -35. 126.13991546630859 -20.56556701660156 -24.26192474365234 30. 140.90133666992188 -32.558475494384766. 121.70594787597656 -35.61318206787109 -33.56221771240234 -34. 137.99697875976563 -35.11587524414063 -29. 116. 114. 114.64814758300781 -36.189453125 -33.025871276855469. 118.499790191650391. 133.37458801269531 -34.17213439941406 20.048313140869141.000068664550781.535476684570312.617877960205078.38589477539063 32.25058746337891 34. 138. 114. 138. 118. 118.781232833862305. 114.190639495849609.94303894042969 -26.455646514892578.L19-4 Lab: Working with SQL Server Spatial Data -38.26606559753418.367696762084961. 115.30978393554688 -34.02616882324219 -37. 131.41074371337891 -35.04069519042969 -32.66084289550781 -33. 137.53349304199219 34.103199005126953.87643432617188 -34. 114.737743377685547. 119. 120.950927734375 -32. 140. 114.41212463378906 -33.073368072509766.562080383300781.439579010009766. 119.127155303955078.11616516113281 33. 116.61216735839844 -33. 119. 137.555038452148438.58287048339844 24. 114.339134216308594.040727615356445.624660491943359.91389465332031 -33. 124.953533172607422.011432647705078.66001129150391 -22.548957824707031. 114.93798065185547 -20.38905334472656 -31.29524993896484 -26. 113. 113. 134. 132.190467834472656. 138.364013671875. 134.5973014831543.229286193847656. 137.44065856933594 -32.38618469238281 -26. 127. 134. 138.131229400634766.254417419433594.598531723022461. 113.313907623291016.32875061035156 -32. 134. 139.46874237060547 -32.02934265136719 -36. 138.649562835693359.885986328125. 135.43566131591797 -22.15071105957031 -35.25409698486328 -26.42892456054688 -38.145689010620117.588871002197266. 136.464162826538086.271642684936523.910751342773438.161888122558594. 114.12889099121094 -27.38450622558594 -26.4920597076416.276569366455078. 138.786540985107422.442138671875.0837516784668. 137. 132. 114.240230560302734.96568298339844 -23. 129.02352905273438 -33.454486846923828.77128601074219 -34. 113. 115.300273895263672.45204925537109 33. 115.97515106201172 -34.31146240234375 33. 123.730152130126953.08432006835938 26. 138. 137.680290222167969.26261138916016 -32.072917938232422.514995574951172.40083312988281 -35. 117.63349914550781 -35.405483245849609.578449249267578.596633911132812.195281982421875.30516052246094 -34.48382568359375 -31.10423278808594 -22.5560302734375 35.39241027832031 -33.29875946044922 -26.63665008544922 -26.673364639282227.83406066894531 -28.31202697753906 -35.739955902099609.053794860839844.8480339050293.01618194580078 . 140. 115.23877716064453 26. 115. 117.934112548828125.297161102294922.417392730712891.347339630126953.82909393310547 -22.88699340820313 35.521648406982422.52482604980469 -25.724918365478516.741361618041992.007402420043945.16830444335938 -28.41265869140625.

132. 141.71826171875 11.05227661132813 -14.029497146606445. 129.607682228088379.07581329345703 -19.26980590820313 -15.66252136230469 -14. 125.008792877197266. 122. 140.0462007522583.261057853698731.16641235351563 -16. 136.898410797119141 )))'. 136. 136. 124.640926361083984.606078147888184.614999771118164.75660705566406 -16.168212890625 -13.33218383789063 -12.85267639160156 -12. 130.Script 19. 128.9 Draw Australia with a buffer around it DECLARE @Australia geometry.7398042678833. 138.562946319580078. 123. 136. 133. 134.05709075927734 -13.89231109619141 -15.62026977539063 -14.13264465332031 -11.11570739746094 -16.226715087890625.802490234375 -13. 124.50227355957031 -12.77950286865234 -16.467802047729492.77999877929688 18. 142.685539245605469. 141.73275756835938 14.467185020446777.558222770690918.450845718383789. 136. 124.66716003417969 -12. 132.369593620300293. 140.613780975341797. 121.06253051757813 -12. 122. 135.685775756835938.957944869995117.29487609863281 -12.54121398925781 10. 125.06686401367188 -14.91496276855469 -15.186027526855469.89080810546875 -16.766800880432129.0).359770774841309.054102897644043.678993225097656.26387023925781 -17.494205474853516.251283645629883.47202301025391 -14.301631927490234.9947509765625 -12.513069152832031.209720611572266.874351501464844.05001068115234 16.23200988769531 -12.659969329833984.22822570800781 -11.825523376464844.686156272888184.566312789916992.12260437011719 -12.27737426757813 -16. 129.28913879394531 -17. 128. 139. 126.74357604980469 -12. 122.383670806884766.869436264038086.744054794311523. 123. 141.95478820800781 -12.231498718261719.76284790039063 -11.03050994873047 -17.63816833496094 12.40965270996094 -13. 130.429638862609863.62816619873047 -15. 141. 136. 140.91120910644531 17.8359375 15. 135.67181396484375 -14. 121. 125.171424865722656. 132. 133. 124.099803924560547.96577453613281 12.7875337600708.516201972961426.31279754638672 -15.975923538208008. 141.813465118408203. 135. 130.15493774414063 12.40011596679688 -18.71598815917969 13.74971008300781 -14.4639892578125 16.097315788269043. SELECT @Australia AS Australia. 123. 127.092321395874023.449649810791016.178533554077148. 136.353300094604492.956218719482422.245037078857422. GO -. 129.08430480957031 14.802887916564941.381425857543945. 142.20579719543457.16622924804688 -14.40925598144531 -11.934375762939453. 127.87205505371094 -14. 131.460931777954102.741966247558594. 126.414670944213867.288888931274414. 135.94200134277344 -16.33607482910156 -16. 131.67274475097656 -13. 141.976600646972656. 142.100902557373047. 124.677942276000977.66123962402344 -14.014326095581055. 136. 139.140419960021973.333209991455078.152227401733398.62236785888672 -17. 126. 131.45198059082031 -17. 136. 141. 132.35932159423828 14.66370964050293.373815536499023.940177917480469.Lab: Working with SQL Server Spatial Data L19-5 -20. .54142761230469 -16.88218688964844 -12.40008544921875 -14.03456115722656 -13.32931518554688 -11.71196746826172 17. 123.792503356933594. 128. 137. 131.63021850585938 -14.02192687988281 -17.

17552185058594 31.18850708007813 -37.L19-6 Lab: Working with SQL Server Spatial Data SET @Australia = geometry::STGeomFromText('MULTIPOLYGON (((146.704837799072266)).17349243164063 -38. 153. 143.578449249267578. 138. 144. 142.501945495605469.02616882324219 -37. 143. 147.682428359985352.796828269958496.147617340087891.845218658447266. 151. 143. 145. 149.63349914550781 -35. 144.448851585388184.4251708984375 35.07573413848877.00613403320313 -23.876548767089844. 151.72958374023438 -39.291374206542969. 145. 153.329910278320312.424533843994141. 153.228744506835938. 148.637355804443359.91639709472656 -43. 145.030624389648438.111736297607422.40083312988281 -35.739955902099609. 140. 145. 145. 138.71554565429688 -34.229286193847656.37985229492188 -32.61637878417969 -19.777362823486328. 137. 152.9527587890625. 146.57157897949219 -35.90054321289063 -40. 150.17445373535156 -12.84793090820313 -11.473457336425781.859695434570312.22093200683594 22.12821960449219 -18. . 151. 146.27639770507813 24.823896408081055.080898284912109.34538269042969 -43.339134216308594.210777282714844.70556640625.1484375 -22. 150.66114616394043.96830749511719 -32.52163696289063 -24. 144.30516052246094 -34. 145. 137.56816101074219 -33. 153. 146.185646057128906. 144.4830322265625 -42.575309753417969. 153.07258605957031 -41. 137. 152. 153.14321899414063 -30. 145.12933349609375 -42.898410797119141.788833618164062.239631652832031.96563720703125 -35.008373260498047.70791625976563 -38. 145.306673049926758.77070617675781 -20. 138.624660491943359.73957824707031 -38.70594787597656 -35.401203155517578. 142.6771354675293.713462829589844.650595664978027.92631530761719 -43.90739440917969 -20.52542114257813 -19.58587646484375 -41.76042175292969 -22.910751342773438.21568298339844 37.60006713867188 -28.352115631103516. 138.239715576171875.901708602905273.77128601074219 -34.27273559570313 -26.464195251464844.17660522460938 20.075611114501953. 139.30514526367188 -21. 138.58901977539063 -14.163665771484375.52291870117188 -41. 148. 146.223194122314453.56846618652344 -38.415578842163086.902679443359375.8480339050293.41265869140625.54121398925781 -10.29037475585938 26.987766265869141. 150.50288391113281 38. 145.95124816894531 -38. 137.053794860839844.454490661621094.442138671875. 145. 149.236156463623047.25955200195313 -40. 146.91639709472656 43. 143. 146.503929138183594.650703430175781.03501892089844 -25. 139.02934265136719 -36.104367256164551.582916259765625.10769653320313 -38. 140. 151.14051628112793.517995834350586. 141.91603088378906 -37.49560546875. 146.438838958740234.94683837890625 -14.38800048828125 -15.02470397949219 -38.88699340820313 35. 140.19784545898438 -17.024333953857422. 150.455646514892578.26838684082031 -14. 148. 144.52920532226563 -16.324020385742188.5973014831543.47319030761719 -41. 147.42892456054688 -38.079109191894531.04315185546875. ((142.806430816650391.824363708496094. 150.5560302734375 35.69715881347656 -28.15071105957031 -35.499790191650391.93380737304688 -24.296232223510742.57481384277344 -12. 153.546205520629883. 144.80001831054688 -41. 150. 147. 143.64814758300781 -36.439579010009766.048786163330078. 147.24066162109375 -38. 148.31202697753906 -35.800580978393555.68940734863281 -25. 152. 148. 152. 148.535476684570312.11616516113281 33. 149.704837799072266.38616943359375 -42.73284912109375 -14. 138. 137. 143. 148.724786758422852.02713012695313 -11.37675476074219 -12.993001937866211.313907623291016.065319061279297.577156066894531. 153.14988708496094 -27.61477661132813 38.89729309082031 -22.82795715332031 -42. 148.

38618469238281 -26. 114.44065856933594 -32. 114. 113. 115. 123. 134. 124. 116.724918365478516.54142761230469 -16. 123. 134.607682228088379. 131.016206741333008.0837516784668.56221771240234 -34. 116.52482604980469 -25. 113. 123.092321395874023.87643432617188 -34. 114.23877716064453 26.26606559753418.953533172607422.454486846923828.16830444335938 -28.127155303955078.80059051513672 -20.680290222167969.566312789916992.381425857543945.02352905273438 -33.007402420043945. 124. 115.820150375366211. 118.03050994873047 -17.11570739746094 -16. 115.39241027832031 -33.37458801269531 -34.190467834472656.71196746826172 17.161888122558594.325000762939453. 124.32875061035156 -32. 138.63665008544922 -26.66084289550781 -33.934112548828125. 121.513069152832031.Lab: Working with SQL Server Spatial Data L19-7 138.62245941162109 -20. 114.685775756835938. 132.011432647705078. 115.367696762084961. 113.41212463378906 -33.75660705566406 -16.94200134277344 -16. 114.730152130126953. 114.100902557373047.53349304199219 34.31279754638672 -15.103199005126953.548957824707031. 117.38450622558594 -26.10423278808594 -22. 124.562946319580078.145689010620117. 119.82909393310547 -22.46874237060547 -32.957944869995117.27078247070313 33.0718994140625 -32. 122.43566131591797 -22.025871276855469.076744079589844.320106506347656.073368072509766.195281982421875. 123. 134.048313140869141.189453125 -33.781232833862305. 113. 133. . 122. 121. 113. 115.25409698486328 -26.94303894042969 -26.08432006835938 26. 118. 115.649562835693359. 125.05001068115234 16.93798065185547 -20.741361618041992.521648406982422. 114. 122.38905334472656 -31. 137.254417419433594.45204925537109 33.90133666992188 -32. 125. 123.29524993896484 -26. 119.40011596679688 -18.617877960205078. 134.072917938232422. 134.99697875976563 -35. 114.885986328125.35932159423828 14.596633911132812.950927734375 -32.240230560302734.364013671875. 126.514995574951172.07581329345703 -19.62236785888672 -17. 127.83406066894531 -28.66001129150391 -22.62816619873047 -15.558475494384766.588871002197266. 120.276569366455078.17213439941406 20.25058746337891 34. 113.31146240234375 33. 137. 136. 114.41074371337891 -35.297161102294922.786540985107422.12889099121094 -27. 122.13991546630859 -20. 113. 113.562080383300781.464162826538086. 118.131229400634766.77950286865234 -16. 138.29875946044922 -26.96568298339844 -23.77999877929688 18.45505523681641 -35.26261138916016 -32. 115.48382568359375 -31.347339630126953. 124. 124.749591827392578.91609191894531 -35.300273895263672.04069519042969 -32. 129.58287048339844 24.040727615356445.417392730712891. 117. 118.4920597076416.91389465332031 -33.26192474365234 30.640926361083984.76168060302734 -33.245037078857422.11587524414063 -29.659969329833984.28913879394531 -17.678993225097656.23101043701172 22.7875337600708.737743377685547. 135. 119. 125. 121.373815536499023. 114.38589477539063 32.56556701660156 -24. 132. 114.61318206787109 -33.190639495849609.271642684936523.598531723022461. 114.000068664550781.01618194580078 -20.555038452148438.673364639282227.89231109619141 -15.449649810791016.226715087890625.97515106201172 -34. 113.02070426940918.61216735839844 -33.503608703613281.30978393554688 -34.231498718261719.405483245849609.

138. 130.88218688964844 -12.209720611572266.16641235351563 -16.1 19.4639892578125 16.note the 6522 error and the wrapped error message. 132.02192687988281 -17. 131.40925598144531 -11.STBuffer(1) UNION ALL SELECT @Australia. 132.140419960021973. 141. 128. 126. 136. 136.792503356933594.976600646972656. GO 3.460931777954102.76284790039063 -11.0).23200988769531 -12.26980590820313 -15.369593620300293.NET error is returned. 137.613780975341797. 135. Try an invalid value .353300094604492.898410797119141 )))'. 135.63816833496094 12. 130. 126.008792877197266. Note how specific the message is.67181396484375 -14.802887916564941.66716003417969 -12.45198059082031 -17.802490234375 -13. 133. 141. 136.66252136230469 -14. 141. 131.014326095581055.06253051757813 -12.33607482910156 -16. 128. 130.686156272888184.54121398925781 10. 129.32931518554688 -11. Output A square is drawn.91120910644531 17.66123962402344 -14.33218383789063 -12.429638862609863.L19-8 Lab: Working with SQL Server Spatial Data 126. 140. 139.20579719543457. 133.26387023925781 -17.494205474853516. 142.16622924804688 -14.96577453613281 12.741966247558594.63021850585938 -14.097315788269043.869436264038086.874351501464844.956218719482422.22822570800781 -11. 135.13264465332031 -11.940177917480469.71826171875 11.934375762939453.677942276000977. 141.975923538208008. Review the results from each script.152227401733398.467185020446777.467802047729492.383670806884766.766800880432129.168212890625 -13.73275756835938 14. 140. 141.47202301025391 -14. 136. 136. .95478820800781 -12.7398042678833.813465118408203. 131.40008544921875 -14. Scroll to the right to read the full message.05227661132813 -14.558222770690918. 127.171424865722656.516201972961426.2 Query Title Draw a square.614999771118164.178533554077148.261057853698731.450845718383789. 129. 142.12260437011719 -12.359770774841309.05709075927734 -13. 128.744054794311523.054102897644043.50227355957031 -12.06686401367188 -14.85267639160156 -12.87205505371094 -14. 131.74971008300781 -14.74357604980469 -12. 140.71598815917969 13.15493774414063 12. 127.8359375 15. 136. 132.288888931274414.27737426757813 -16.40965270996094 -13. 141.685539245605469. 139. 132.89080810546875 -16. SELECT @Australia. Remember to click on the Spatial results tab to see the output.62026977539063 -14.66370964050293.91496276855469 -15.606078147888184.03456115722656 -13.0462007522583.301631927490234.29487609863281 -12. 135.029497146606445.414670944213867. 134.67274475097656 -13.251283645629883.099803924560547. 142.9947509765625 -12.186027526855469. 141.825523376464844. Query Number 19. 129. 136.08430480957031 14. 136.333209991455078. A . 136.

Right-click the MarketDev database and click New Query. The shapes are moved to intersect. Right-click the MarketDev database and click New Query. Type the query below in the query pane: . The two intersecting shapes and the intersection are drawn.5 19.6 19. Right-click the MarketDev database and click New Query. Draw Australia with a buffer around it. Note how a polygon is represented in text in the query. Type the query below in the query pane: ALTER TABLE Marketing. 2.ProspectLocation ADD Location GEOGRAPHY NULL. Output The shape is drawn. 2. Two shapes are drawn.8 19.4326).7 Multiple shapes. Union of two shapes. Intersection of shapes. Note the calculation of a buffer region around the map. In the toolbar. Australian map is drawn. Type the query below in the query pane: UPDATE Marketing. 19. Exercise 2: Adding Spatial Data to an Existing Table f Task 1: Add a Location column 1.3 Query Title Draw a more complex shape.ProspectLocation SET Location = GEOGRAPHY::STGeomFromText( 'POINT(' + CAST(Longitude AS varchar(20)) + ' ' + CAST(Latitude AS varchar(20)) + ')'. A combined shape is drawn. GO 3. click Execute. 19.Lab: Working with SQL Server Spatial Data L19-9 Query Number 19. GO 3.4 19. f Task 3: Drop the existing Latitude and Longitude columns 1. In the toolbar. Intersecting shapes.9 Draw Australia. click Execute. f Task 2: Write code to assign values to this column 1. 2.

Long AS Longitude. pl. GO ALTER TABLE Marketing.CellPhoneNumber. click Execute.Location FROM Marketing.L19-10 Lab: Working with SQL Server Spatial Data ALTER TABLE Marketing.GetNearbyProspects ( @ProspectID int.Location. p. Right-click the MarketDev database and click New Query. p.Location. SELECT pl.ProspectLocation DROP COLUMN Latitude. pl. p.ProspectID .Location. Type the query below in the query pane: CREATE PROCEDURE Marketing. Review the supporting documentation for details of the required stored procedure.FirstName.ProspectID = @ProspectID).ProspectID = pl. pl.ProspectLocation (Location). @DistanceInKms int ) AS BEGIN DECLARE @LocationToTest GEOGRAPHY. GO 3.ProspectLocation AS pl ON p. GO 3.AddressLine2. p. In the toolbar.LastName. click Execute. Challenge Exercise 3: Business Application of Spatial Data (Only if time permits) f Task 1: Review the requirements 1.Prospect AS p INNER JOIN Marketing.ProspectID. f Task 2: Create a spatial index 1. Right-click the MarketDev database and click New Query.AddressLine1.ProspectLocation DROP COLUMN Longitude.City. SET @LocationToTest = (SELECT pl. p.WorkPhoneNumber. In the toolbar. pl. Type the query below in the query pane: CREATE SPATIAL INDEX IX_ProspectLocation_Location ON Marketing. 2. 2. pl.ProspectLocation AS pl WHERE pl.Lat AS Latitude FROM Marketing.STDistance(@LocationToTest) / 1000 AS Distance. f Task 3: Design and implement the Stored Procedure 1.

END. Type the query below in the query pane: EXEC Marketing.Lab: Working with SQL Server Spatial Data L19-11 WHERE pl. f Task 4: Test the procedure 1. GO 3. Right-click the MarketDev database and click New Query. click Execute.Location.STDistance(@LocationToTest) < (@DistanceInKms * 1000) AND p. In the toolbar. click Execute. In the toolbar.GetNearbyProspects 2. . 2. 3.50.ProspectID <> @ProspectID ORDER BY Distance.

L19-12 Lab: Working with SQL Server Spatial Data .

click All Programs. Maximize the Hyper-V Manager window. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. When the query window opens. In the Authentication drop-down list box. Before you begin the lab.sql. In the Open Project window. In Virtual Machine Connection window. click Open. double-click the query 00-Setup. In the virtual machine. wait until the Press CTRL+ALT+DELETE to log on message appears. wait until the Press CTRL+ALT+DELETE to log on message appears. type Proseware in the Server name text box. check the Do not show me this console at logon check box and close the Server Manager window. you must complete the following steps: 1.Lab: Working with Full -Text Indexes and Queries L20-1 Module 20: Working with Full-Text Indexes and Queries Lab: Working with Full -Text Indexes and Queries Lab Setup For this lab. Password: Pa$$w0rd 8. click Start. • In the Virtual Machine Connection window. click Start. 6. and then close the Virtual Machine Connection window. In the Virtual Machine Connection window. and click Project/Solution. If the Server Manager window appears. • Click Switch User. 2. In the File menu. click on the Revert toolbar icon. Wait for the revert action to complete. open the project D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ. In the Virtual Machines list. click Revert. From the View menu. click Execute on the toolbar. you will use the available virtual machine environment. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. and then click Other User. and then click Hyper-V Manager. User name: AdventureWorks\Administrator ii. 11. click the Ctrl-Alt-Delete menu item. select Windows Authentication and click Connect. In Solution Explorer. If you are prompted to confirm that you want to revert.ssmssln. 7. and click SQL Server Management Studio. 4. 13. In the Virtual Machines list. • Right-click 623XB-MIA-SQL and click Connect. 15. if the user is not already logged on: • On the Action menu. • Right-click 623XB-MIA-DC and click Connect. click Full Screen Mode. 14. 5. point to Administrative Tools. • Log on using the following credentials: i. 3. 10. • In the Virtual Machine Connection window. On the host computer. in the Virtual Machine Connection window. click Microsoft SQL Server 2008 R2. . In Connect to Server window. 9. 12.

Re-execute the query until the has_crawl_completed column shows the value 1. expand the Proseware server. Right-click the MarketDev database and click New Query. Type the query below in the query pane: ALTER FULLTEXT INDEX ON Marketing. Type the query below in the query pane: CREATE FULLTEXT CATALOG DefaultFullTextCatalog AS DEFAULT.ProductDescription SET CHANGE_TRACKING AUTO.ProductDescription table 1. right-click the MarketDev database and click New Query. GO 3. Right-click the MarketDev database and click New Query.fulltext_indexes. . Right-click the MarketDev database and click New Query. crawl_end_date FROM sys. In Object Explorer. even though the command executed successfully. In the toolbar. crawl_start_date. it can be ignored. If a warning appears. GO 2. crawl_type. expand Databases. NO POPULATION. In the toolbar. 2. 3. click Execute. GO 3. click Execute. In the toolbar. f Task 3: Enable automatic change tracking for the index 1. GO 3.L20-2 Lab: Working with Full -Text Indexes and Queries Exercise 1: Implement a full-text index f Task 1: Create a full-text catalog 1. 2. Note that a warning might be returned when you execute the above command. f Task 2: Create a full-text index on the Description column of the Marketing. f Task 4: Check to see that the population of the index is complete 1. 2. 4. Type the query below in the query pane: SELECT is_enabled. has_crawl_completed. click Execute.ProductDescription(Description) KEY INDEX PK_ProductDescription WITH CHANGE_TRACKING OFF. click Execute. In the toolbar. Type the query below in the query pane: CREATE FULLTEXT INDEX ON Marketing.

'elastic AND lycra') ORDER BY d. Right-click the MarketDev database and click New Query.'bottle') ORDER BY d.ProductDescriptionID. Note: Three rows are returned. f Task 7: Write a CONTAINS query that uses INFLECTIONAL forms 1.ProductDescription AS d WHERE CONTAINS(d. In the toolbar. Exercise 2: Implement a stoplist f Task 1: Review the existing system stopwords 1.ProductDescriptionID.ProductDescriptionID. Note: One row is returned. 2.ProductDescription AS d WHERE CONTAINS(d.Description. Right-click the MarketDev database and click New Query. In the toolbar.ProductDescriptionID. . 2. Note: One row is returned. Type the query below in the query pane: SELECT d. d.Description FROM Marketing. 2.'FORMSOF(INFLECTIONAL. In the toolbar. d. d.Description FROM Marketing. GO 3. Type the query below in the query pane: SELECT d. Right-click the MarketDev database and click New Query. click Execute. click Execute. Type the query below in the query pane: SELECT d.ProductDescriptionID. GO 3.ProductDescription AS d WHERE CONTAINS(d. click Execute.Description FROM Marketing. f Task 6: Write a CONTAINS query that searches for two words 1. Right-click the MarketDev database and click New Query.wash)') ORDER BY d.Description.Lab: Working with Full -Text Indexes and Queries L20-3 f Task 5: Write a simple CONTAINS query 1. GO 3.Description.ProductDescriptionID.

. A list of system stop words for the English language is returned. click Execute. f Task 3: Add words to the stoplist 1. GO 3.fulltext_system_stopwords WHERE language_id = 1033. Type the query below in the query pane: SELECT * FROM sys. GO SELECT * FROM sys. and test the stored procedure 1. 2. f Task 2: Create a full-text stoplist 1. In the toolbar. GO 3. In the toolbar. Right-click the MarketDev database and click New Query. f Task 4: View the stoplist 1. Right-click the MarketDev database and click New Query. Right-click the MarketDev database and click New Query. A list of stoplists and stopwords is returned. 3. Type the query below in the query pane: SELECT * FROM sys. click Execute. In the toolbar. implement. Right-click the MarketDev database and click New Query. Review the supporting documentation for specification for a new stored procedure.L20-4 Lab: Working with Full -Text Indexes and Queries 2.fulltext_stoplists. click Execute. Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits) f Task 1: Review the supporting documentation 1. click Execute. Type the query below in the query pane: CREATE FULLTEXT STOPLIST CommonWords. In the toolbar. GO 3. 2. Type the query below in the query pane: ALTER ADD ALTER ADD GO FULLTEXT STOPLIST CommonWords 'Bike' LANGUAGE 1033. FULLTEXT STOPLIST CommonWords 'AdventureWorks' LANGUAGE 1033.fulltext_stopwords. f Task 2: Design. 2.

[KEY] WHERE d. @PhraseToSearch) AS ft ON d.GetRelevantDescriptions 'strong frame'.Description.RANK DESC.Lab: Working with Full -Text Indexes and Queries L20-5 2. In the toolbar. . Type the query below in the query pane: CREATE PROCEDURE Marketing. END. Note: The first query returns twenty rows. GO 3. ft. click Execute.ProductDescription AS d INNER JOIN FREETEXTTABLE(Marketing. d.GetRelevantDescriptions ( @PhraseToSearch nvarchar(1000) ) AS BEGIN SELECT d.GetRelevantDescriptions 'serious competition'. Description. GO EXEC Marketing.ProductDescriptionID. The second query returns five rows. GO EXEC Marketing.ProductDescriptionID = ft.LanguageID = 'en' ORDER BY ft.ProductDescription.RANK AS Ranking FROM Marketing.

L20-6 Lab: Working with Full -Text Indexes and Queries .