You are on page 1of 480

QuickStart Intelligence

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 1

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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-52339
Released: 03/2011

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing a Microsoft® SQL Server® 2008 R2 Database

iii

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

iv

Implementing a Microsoft® SQL Server® 2008 R2 Database

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing a Microsoft® SQL Server® 2008 R2 Database

v

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

vi

Implementing a Microsoft® SQL Server® 2008 R2 Database

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing a Microsoft® SQL Server® 2008 R2 Database

vii

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

viii

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. Their effort at various stages in the development has ensured that you have a good
classroom experience.

Greg Low – Lead Developer
Dr Greg Low is a SQL Server MVP, an MCT, and a Microsoft Regional Director for Australia. Greg has
worked with SQL Server since version 4.2 as an active mentor, consultant, and trainer. 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. Greg is best known for his SQL Down
Under podcast (at www.sqldownunder.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 is the author of a number whitepapers on the Microsoft MSDN and
TechNet web sites and a number of SQL Server related books.

Herbert Albert – SolidQ Technical Reviewer
Herbert Albert started his career in 1994. He works as a trainer, consultant, and author focusing on SQL
Server technologies. Herbert is a mentor and Managing Director of Solid Quality Mentors Central Europe
located in Vienna, Austria. He has several Microsoft certifications including being an MCT since 1997. 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. Together with Gianluca Hotz,
Herbert writes a regular column at the SolidQ Journal.

Chris Barker – Technical Reviewer
Chris Barker is an MCT in New Zealand and currently employed as a staff trainer at Auldhouse, one of
New Zealand’s major CPLS training centers in Wellington. 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 .NET) and databases (mostly Microsoft SQL Server), Chris has
also been an infrastructure trainer and has both Novell and Microsoft networking qualifications.

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, where he started working with minicomputers, mainframes, and mature students in
1984. He first met Microsoft SQL Server when it ran on OS/2, and has delivered training on every version
since. An independent MCT and consultant for many years, he is a highly-rated presenter at TechEd, has
designed SQL Server exams for Microsoft, and has delivered deep-dive courses through the Microsoft
Partner Channel. Mark is now the Principal SQL Server Instructor and Consultant at DesTech, which is the
largest provider of SQL Server training in the Toronto area.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing a Microsoft® SQL Server® 2008 R2 Database

ix

Contents
Module 1: Introduction to SQL Server 2008 R2 and its Toolset
Lesson 1: Introduction to the SQL Server Platform

1-3

Lesson 2: Working with SQL Server Tools

1-14

Lesson 3: Configuring SQL Server Services

1-28

Lab 1: Introduction to SQL Server and its Toolset

1-36

Module 2: Working with Data Types
Lesson 1: Using Data Types

2-3

Lesson 2: Working with Character Data

2-19

Lesson 3: Converting Data Types

2-27

Lesson 4: Specialized Data Types

2-34

Lab 2: Working with Data Types

2-40

Module 3: Designing and Implementing Tables
Lesson 1: Designing Tables

3-3

Lesson 2: Working with Schemas

3-15

Lesson 3: Creating and Altering Tables

3-21

Lab 3: Designing and Implementing Tables

3-32

Module 4: Designing and Implementing Views
Lesson 1: Introduction to Views

4-3

Lesson 2: Creating and Managing Views

4-13

Lesson 3: Performance Considerations for Views

4-22

Lab 4: Designing and Implementing Views

4-27

Module 5: Planning for SQL Server 2008 R2 Indexing
Lesson 1: Core Indexing Concepts

5-3

Lesson 2: Data Types and Indexes

5-11

Lesson 3: Single Column and Composite Indexes

5-19

Lab 5: Planning for SQL Server Indexing

5-24

Module 6: Implementing Table Structures in SQL Server 2008 R2
Lesson 1: SQL Server Table Structures

6-3

Lesson 2: Working with Clustered Indexes

6-13

Lesson 3: Designing Effective Clustered Indexes

6-20

Lab 6: Implementing Table Structures in SQL Server

6-26

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence x Implementing a Microsoft® SQL Server® 2008 R2 Database Module 7: Reading SQL Server 2008 R2 Execution Plans Lesson 1: Reading SQL Server Execution Plans 7-3 Lesson 2: Common Execution Plan Elements 7-14 Lesson 3: Working with Execution Plans 7-24 Lab 7: Reading SQL Server Execution Plans 7-31 Module 8: Improving Performance through Nonclustered Indexes Lesson 1: Designing Effective Nonclustered Indexes 8-3 Lesson 2: Implementing Nonclustered Indexes 8-10 Lesson 3: Using the Database Engine Tuning Advisor 8-18 Lab 8: Improving Performance through Nonclustered Indexes 8-25 Module 9: Designing and Implementing Stored Procedures Lesson 1: Introduction to Stored Procedures 9-3 Lesson 2: Working With Stored Procedures 9-11 Lesson 3: Implementing Parameterized Stored Procedures 9-23 Lesson 4: Controlling Execution Context 9-33 Lab 9: Designing and Implementing Stored Procedures 9-39 Module 10: Merging Data and Passing Tables Lesson 1: Using the MERGE Statement Lesson 2: Implementing Table Types 10-3 10-14 Lesson 3: Using TABLE Types As Parameters 10-22 Lab 10: Passing Tables and Merging Data 10-26 Module 11: Creating Highly Concurrent SQL Server 2008 R2 Applications Lesson 1: Introduction to Transactions 11-3 Lesson 2: Introduction to Locks 11-17 Lesson 3: Management of Locking 11-28 Lesson 4: Transaction Isolation Levels 11-38 Lab 11: Creating Highly Concurrent SQL Server Applications 11-44 Module 12: Handling Errors in T-SQL Code Lesson 1: Designing T-SQL Error Handling 12-3 Lesson 2: Implementing T-SQL Error Handling 12-13 Lesson 3: Implementing Structured Exception Handling 12-23 Lab 12: Handling Errors in T-SQL Code 12-31 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. .com or by calling +1 800-785-3448. redistribute. It is illegal to reprint. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.

table valued parameters. covering indexes. its components. redistribute. audience. Course Description This five-day instructor-led course is intended for Microsoft® SQL Server database developers who are responsible for implementing a database on SQL Server 2008 R2. the student should have knowledge of basic relational database concepts and writing T-SQL queries. students will be able to: • Understand the product. and provided to you by QuickStart Intelligence. and course objectives. . In this course. To be successful in this course. transaction isolation levels. and basic configuration • Work with the data types supported by SQL Server • Design and implement tables and work with schemas • Design and implement views and partitioned views • Describe the concept of an index and determine the appropriate data type for indexes and composite index structures • Identify the appropriate table structures and implement clustered indexes and heaps • Describe and capture execution plans • Design and implement non-clustered indexes. Audience This course is intended for IT Professionals who want to become skilled on SQL Server 2008 R2 product features and technologies for implementing a database. students learn the skills and best practices on how to use SQL Server 2008 R2 product features and tools related to implementing a database server. Student Prerequisites This course requires that you meet the following prerequisites: • Working knowledge of Transact-SQL (ability to write Transact-SQL queries) • Working knowledge of relational databases (database design skills) • Core Windows Server skills • Completed Course 2778: Writing Queries Using Microsoft SQL Server 2008 Transact-SQL Course Objectives After completing this course. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. and the MERGE statement • Describe transactions.com or by calling +1 800-785-3448. and included columns • Design and implement stored procedures • Implement table types. guarantees or conditions. and application design patterns for highlyconcurrent applications • Design and implement T-SQL error handling and structured exception handling • Design and implement scalar and table-valued functions • Design and implement constraints This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence About This Course xi About This Course This section provides you with a brief description of the course. Please report any unauthorized use of this content to piracy@microsoft. suggested prerequisites. It is illegal to reprint.

“Implementing Managed Code in SQL Server 2008 R2” describes the implementation of and target use-cases for SQL CLR integration. density. Module 8. “Implementing Table Structures in SQL Server 2008 R2” covers clustered indexes and heaps. isolation levels. “Reading SQL Server 2008 R2 Execution Plans” introduces the concept of reading execution plans. “Ensuring Data Integrity through Constraints” describes the design and implementation of constraints. “Working with Data Types” describes the data types supported by SQL Server and how to work with them. Please report any unauthorized use of this content to piracy@microsoft. Module 6. “Improving Performance through Nonclustered Indexes” covers non-clustered indexes. “Creating Highly Concurrent SQL Server 2008 R2 Applications” covers transactions. or resell this content. Module 12. “Merging Data and Passing Tables” covers table types. covering indexes and included columns. It is illegal to reprint. and concepts of services and service accounts. “Introduction to SQL Server 2008 R2 and its Toolset” introduces you to the entire SQL Server platform and its major tools.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. Module 5. Module 9. Module 7. versions. Module 14. “Designing and Implementing User-Defined Functions” describes the design and implementation of functions. Module 15. and designing for concurrency. Module 13. “Designing and Implementing Views” describes the design and implementation of views. This module also covers appropriate data type choices and choices around composite index structures. and statistics. The Licensed Content is licensed "as-is. Module 10. This module also covers editions. both scalar and table-valued. Module 4. “Responding to Data Manipulation via Triggers” describes the design and implementation of triggers. redistribute. “Designing and Implementing Stored Procedures” describes the design and implementation of stored procedures. basics of network listeners. “Handling Errors in T-SQL Code” describes structured exception handling and gives solid examples of its use within the design of stored procedures. guarantees or conditions.QuickStart Intelligence xii About This Course • Design and implement triggers • Describe and implement target use cases of SQL CLR integration • Describe and implement XML data and schema in SQL Server • Use FOR XML and XPath queries • Describe and use spatial data types in SQL Server • Implement and query full-text indexes Course Outline This section provides an outline of the course: Module 1. “Designing and Implementing Tables” describes the design and implementation of tables. Module 11. . Module 2. Module 3. Module 16." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. table valued parameters and the MERGE statement as used in stored procedures. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. “Planning for SQL Server 2008 R2 Indexing” describes the concept of an index and discusses selectivity.

and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. guarantees or conditions. typed and untyped columns and appropriate use cases for XML in SQL Server." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. “Working with SQL Server 2008 R2 Spatial Data” describes spatial data and how this data can be implemented within SQL Server. redistribute. Module 20. It is illegal to reprint. Module 19. Module 18. .com or by calling +1 800-785-3448. “Storing XML Data in SQL Server 2008 R2” covers the XML data type. “Querying XML Data in SQL Server 2008 R2” covers the basics of FOR XML and XPath Queries. “Working with Full-Text Indexes and Queries” covers full text indexes and queries.QuickStart Intelligence About This Course xiii Module 17. schema collections. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

• • Modules: Include companion content. easy-to-navigate digital content with integrated premium on-line resources designed to supplement the Course Handbook. guarantees or conditions. and provided to you by QuickStart Intelligence. such as questions and answers. they include Lab Review questions and answers and Module Reviews and Takeaways sections. tightly-focused format. Additionally. you will have the opportunity to complete an online evaluation to provide feedback on the course.QuickStart Intelligence xiv About This Course Course Materials The following materials are included with your kit: • Course Handbook A succinct classroom learning guide that provides all the critical technical information in a crisp. training facility. and instructor.com/learning/companionmoc/ Site: Searchable. which is just right for an effective in-class learning experience. Microsoft Press® Student Course files on the http://www. redistribute. • Course evaluation At the end of the course.com. • Module Reviews and Takeaways: Provide improved on-the-job reference material to boost knowledge and skills retention. Course Companion Content on the http://www.microsoft. The Licensed Content is licensed "as-is.com. or resell this content. send e-mail to support@mscourseware.com/learning/companionmoc/ Site: Includes the Allfiles. for each lesson. • Lessons: Guide you through the learning objectives and provide the key points that are critical to the success of the in-class learning experience." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. To inquire about the Microsoft Certification Program.microsoft. and real-world issues and scenarios with answers. hands-on platform for you to apply the knowledge and skills learned in the module. . a self-extracting executable file that contains all the files required for the labs and demonstrations. detailed demo steps and additional reading links. MSDN®. Resources: Include well-categorized additional resources that give you immediate access to the most up-to-date premium content on TechNet. send e-mail to mcphelp@microsoft. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • To provide additional comments or feedback on the course. • Labs: Provide a real-world.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft.exe. best practices. • Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips when it’s needed. common issues and troubleshooting tips with answers. which contain the review questions and answers.

.20 Software Configuration The following software is installed on each VM: • SQL Server 2008 R2 (on the SQL Server VMs) Course Files There are files associated with the labs in this course. redistribute. and provided to you by QuickStart Intelligence. The lab files are located in the folder D:\6232B_Labs on the student computers. Course Hardware Level To ensure a satisfactory student experience. The following table shows the role of each virtual machine used in this course: Virtual machine Role 623XB-MIA-DC Domain Controller 623XB-MIA-SQL1 SQL Server VM for Module 1 only 623XB-MIA-SQL SQL Server VM for Modules 2 ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.com or by calling +1 800-785-3448. you will use Microsoft Virtual Server 2005 R2 with SP1 to perform the labs. The Licensed Content is licensed "as-is.QuickStart Intelligence About This Course xv Virtual Machine Environment This section provides the information for setting up the classroom environment to support the business scenario of the course. It is illegal to reprint. Virtual Machine Configuration In this course. Classroom Setup Each classroom computer will have the same virtual machine configured in the same way. Please report any unauthorized use of this content to piracy@microsoft. Microsoft Learning requires a minimum equipment configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft Learning Product courseware are taught. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. redistribute.QuickStart Intelligence xvi About This Course This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. or resell this content. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.

QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-1 Module 1 Introduction to SQL Server 2008 R2 and its Toolset Contents: Lesson 1: Introduction to the SQL Server Platform 1-3 Lesson 2: Working with SQL Server Tools 1-14 Lesson 3: Configuring SQL Server Services 1-28 Lab 1: Introduction to SQL Server and its Toolset 1-36 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. and provided to you by QuickStart Intelligence. It is illegal to reprint. .com or by calling +1 800-785-3448. redistribute.

Individual components of SQL Server can operate within separate security contexts. Objectives After completing this lesson.QuickStart Intelligence 1-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Before beginning to work with SQL Server in either a development or an administration role. you will be able to: • • • Describe the SQL Server Platform Work with SQL Server Tools Configure SQL Server Services This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Correctly configuring SQL Server services is important where enterprises are operating with a policy of least possible permissions. Please report any unauthorized use of this content to piracy@microsoft. SQL Server provides a series of tools that make the product easy to manage and good target for the application development. In particular.com or by calling +1 800-785-3448. . It is illegal to reprint. it is useful to understand that SQL Server is not just a database engine but it is a complete platform for managing enterprise data. or resell this content. redistribute. guarantees or conditions. Along with a strong platform. it is important to understand the overall SQL Server platform." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.

The Licensed Content is licensed "as-is. guarantees or conditions. SQL Server is shipped in a variety of editions. you will be able to: • • • • • Describe the overall SQL Server platform Explain the role of each of the components that make up the SQL Server platform Describe the functionality provided by SQL Server Instances Explain the available SQL Server Editions Explain how SQL Server has evolved through a series of versions This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. each with a different set of capabilities. SQL Server is structured as a series of components. redistribute. Each of these copies is called an instance and can be separately configured and managed. More than a single copy of SQL Server can be installed on a server. Rather than being a single monolithic application. It is important to understand the target business cases for each of the SQL Server editions and how SQL Server has evolved through a series of improving versions over many years. It is illegal to reprint.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. and provided to you by QuickStart Intelligence. Objectives After completing this lesson. . It is important to understand the use of each of the components.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-3 Lesson 1 Introduction to the SQL Server Platform SQL Server is a platform for developing business applications that are data focused. It is a stable and robust platform.

or resell this content. Organizations need constant access to their data. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. High Availability Impressive performance is necessary but not at the cost of availability. guarantees or conditions. SQL Server is used to manage organizational data and to provide analysis and insights into that data. Many enterprises are now finding a need to have 24 hour x 7 day access available. it provides a very secure. Security is not able to be retrofitted after an application or a product is created. The database engine is one of the highest performing database engines available and regularly features in the top of industry performance benchmarks. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. and stable relational database management system.org. SQL Server has been built from the ground up with the highest levels of security as a goal. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. more and more capabilities have been added to minimize any potential downtime.com or by calling +1 800-785-3448. You can review industry benchmarks and scores at www. Security Utmost in the minds of enterprise managers is the need to secure organizational data. The SQL Server platform was designed with the highest levels of availability in mind. As each version of the product has been released.tpc. The Licensed Content is licensed "as-is. robust. Question: Which other database platforms have you worked with? Enterprise Ready While SQL Server is much more than a relational database management system.QuickStart Intelligence 1-4 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Architecture Key Points SQL Server is an integrated and enterprise-ready platform for data management that offers a low total cost of ownership. . redistribute.

Please report any unauthorized use of this content to piracy@microsoft. For example. The productivity achieved when working with the tools is enhanced by the high degree of integration between the tools.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-5 Scalability Organizations have a need for data management capabilities for systems of all sizes. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. SQL Server tooling (both management and development) builds on existing Windows knowledge. many of the SQL Server tools have links to launch and preconfigure other SQL Server tools. guarantees or conditions.com or by calling +1 800-785-3448. SQL Server offers very low total cost of ownership. Cost of Ownership Many competing database management systems are expensive to both purchase and to maintain. SQL Server scales from the smallest needs to the largest via a series of editions with increasing capabilities. Most users tend to become familiar with the tools quite quickly. or resell this content. and provided to you by QuickStart Intelligence. . redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

and provided to you by QuickStart Intelligence. It is illegal to reprint. Component Purpose Database Engine Is a relational database engine based on the SQL language Analysis Services Is an online analytical processing (OLAP) engine that works with analytic cubes Integration Services Is a tool used to orchestrate the movement of data between SQL Server components and external systems (in both directions) Reporting Services Offers a reporting engine based on web services and provides a web portal and end-user reporting tools Master Data Services Provides tooling and a hub for managing master or reference data StreamInsight Is a platform for building applications to process high-speed events Data Mining Provides tooling and an inference engine for deriving knowledge and insights from existing OLAP data or relational data Full-Text Search Allows building sophisticated search options into applications PowerPivot Allows end-users. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. each designed to enhance data management capabilities. power users." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. SQL Server Components SQL Server is a platform comprising many components. .QuickStart Intelligence 1-6 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Components Key Points SQL Server is a very good relational database engine but as a data platform. and business analysts to quickly analyze large volumes of data from different locations Replication Allows moving data between servers to suit data distribution needs This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. redistribute. it offers much more than a relational database engine. guarantees or conditions.

. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. guarantees or conditions. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-7 Question: Which components of SQL Server have you worked with? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. redistribute. or resell this content.

Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. It is illegal to reprint. While each database can have different collations. Application databases might need to be supported with different levels of service. particularly in relation to availability. Applications that need to be supported by an organization may require server configurations that are inconsistent or incompatible with the server requirements of other applications. guarantees or conditions. The Licensed Content is licensed "as-is. redistribute. and provided to you by QuickStart Intelligence. this mode of connection is still supported and is known as a "default" instance. To maintain backward compatibility. . SQL Server Instances The ability to install multiple instances of SQL Server components on a single server is useful in a number of situations: • • • • • There may be a need to have different administrators or security environments for sets of databases. or resell this content. Each instance of SQL Server is separately manageable and securable. Each instance of SQL Server is separately configurable.QuickStart Intelligence 1-8 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Instances Key Points It is sometimes useful to install more than a single copy of a SQL Server component on a single server. This can assist when testing upgrade scenarios or performing upgrades. only a single copy of SQL Server could be installed on a server system. an application might be dependent on the collation of the tempdb database when the application is using temporary objects. Applications might require different server-level collations. Different versions of SQL Server might need to be supported. SQL Server instances can be used to separate workloads with differing service level agreements (SLAs) that need to be met. SQL Server was addressed by the name of the server. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Many SQL Server components can be installed more than once as separate instances. Question: Why might you need to separate databases by service level agreement? Different versions of SQL Server can often be installed side-by-side using multiple instances. Default and Named Instances Prior to SQL Server 2000.

com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. guarantees or conditions. There is no need to install SQL Server tools and utilities more than once. or resell this content. . Please report any unauthorized use of this content to piracy@microsoft. SQL Server Integration Services is installed once per server.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-9 Additional instances of SQL Server require an instance name in addition to the server name and are known as "named" instances. It is illegal to reprint. A single installation of the tools is able to manage and configure all instances. Not all components of SQL Server are able to be installed in more than one instance. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In particular. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

. Parallel Data Warehouse systems are sold as a complete "appliance" rather than via standard software licenses Datacenter Provides the highest levels of scalability for mission-critical applications Enterprise Provides the highest levels of reliability for demanding workloads Standard Delivers a reliable. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. guarantees or conditions. redistribute. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. optimized for a very small memory footprint Developer Allows building. testing. with different price points and different levels of capability." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 1-10 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Editions Key Points SQL Server is available in a wide variety of editions. SQL Server Editions Each SQL Server edition is targeted to a specific business use case as shown in the following table: Edition Business Use Case Parallel Data Warehouse Uses massively parallel processing (MPP) to execute queries against vast amount of data quickly.com or by calling +1 800-785-3448. or resell this content. and demonstrating all SQL Server functionality This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. complete data management and Business Intelligence (BI) platform Express Is a free edition for lightweight web and small server-based applications Compact Is a free edition for standalone and occasionally connected mobile applications.

redistribute. guarantees or conditions.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset Workgroup Runs branch applications with secure remote synchronization and management capabilities Web Provides a secure. The Licensed Content is licensed "as-is. . and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. cost effective. and scalable platform for public web sites and applications SQL Azure Allows building and extending SQL Server applications to a cloud-based platform 1-11 Question: What would be a good business case example for using a cloud-based service? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

Early Versions The earliest versions (1. SQL Server Integration Services replaced a former tool known as Data Transformation Services (DTS). SQL Server has been available for many years.QuickStart Intelligence 1-12 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Versions Key Points SQL Server is a platform with a rich history of innovation achieved while maintaining strong levels of stability. OLAP Services (which later became Analysis Services) was introduced. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. Another key addition to the product was the introduction of support for objects created using the Common Language Runtime (CLR). Substantial advances were made in reducing the administration workload for the product. including structured exception handling. initially on the Windows NT operating system. and provided to you by QuickStart Intelligence. redistribute. yet it is rapidly evolving new capabilities and features. Please report any unauthorized use of this content to piracy@microsoft. along with support for 64-bit processors. Versions 4. It also introduced support for data mining. or resell this content.0 saw a significant rewrite of the product." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SQL Server Management Studio was released to replace several previous administrative tools. SQL Server Reporting Services was introduced after the product release as an add-on enhancement to the product. Later Versions Version 7.2 and later moved to the Windows operating system. . SQL Server 2005 provided another significant rewrite of many aspects of the product. The T-SQL language was substantially enhanced.com or by calling +1 800-785-3448. It introduced support for: • • • • • Non-relational data stored and queried as XML.1) were based on the OS/2 operating system.0 and 1. It is illegal to reprint. SQL Server 2000 featured support for multiple instances and collations. guarantees or conditions.

A policy-based management framework was introduced to assist with a move to more declarativebased management practices. rather than reactive practices. Filestream support improved the handling of structured and semi-structured data. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. before storing the data in a database. Upcoming Versions The next version of SQL Server has been announced. (Previously full-text indexing was based on interfaces to operating system level services). Support for column encryption was introduced. SQL Server 2008 R2 The enhancements and additions to the product in SQL Server 2008 R2 included: • • • • • • Substantial enhancements to SQL Server Reporting Services. A PowerShell provider for SQL Server was introduced. redistribute. and troubleshooting. The introduction of advanced analytic capabilities with PowerPivot. This version will enable the efficient delivery of mission-critical solutions through a highly scalable and available platform. guarantees or conditions. SQL Server 2008 also provided many enhancements: • • • • • • • • The "SQL Server Always On" technologies were introduced to reduce potential downtime. Question: Which versions of SQL Server have you worked with? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset • • • 1-13 Dynamic Management Views and Functions were introduced to enable detailed health monitoring. including support for timezones within datetime data. Data-Tier applications assist with packaging database applications as part of application development projects. Spatial data types were introduced. StreamInsight provides the ability to query data that is arriving at high speed. or resell this content.and time-related data types were introduced.com or by calling +1 800-785-3448. Additional productivity tools and features will assist developers and the reach of business intelligence tooling to end-users will be enhanced. Database compression and encryption technologies were added. Substantial high availability improvements were included in the product. . Please report any unauthorized use of this content to piracy@microsoft. Full-text indexing was integrated directly within the database engine. Specialized date. performance tuning. Support for managing reference data was provided with the introduction of Master Data Services. Database mirroring was introduced. Improved multi-server management capabilities were added. It is illegal to reprint.

redistribute. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. then look at the tools that are most commonly used when working with SQL Server. or resell this content. it needs to make a network connection to the server.QuickStart Intelligence 1-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Working with SQL Server Tools Working effectively with SQL Server requires familiarity with the tools that are used in conjunction with SQL Server. you will see how these connections are made. you will be able to: • • • • • Connect from Clients and Applications Describe the roles of Software Layers for Connections Use SQL Server Management Studio Use Business Intelligence Development Studio Use Books Online This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . Objectives After completing this lesson. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. Before any tool can connect to SQL Server. In this lesson.

It is illegal to reprint. SQL Server supports two forms of authentication. These logins are known as SQL Logins. Authentication For the majority of applications and organizations. the Named Pipes protocol. a Windows user can be granted access to the server. The process of verifying the identity of a user (or more formally. However. A variety of communication protocols are available for making connections. in this course. known as their "default" database. and provided to you by QuickStart Intelligence. the user is connected to a specific database." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. is known as authentication. guarantees or conditions. Also.com or by calling +1 800-785-3448. TDS is a high-level protocol that is transported by lower-level protocols. When a connection is made. either directly or via his/her Windows group memberships. or implemented over a shared memory connection. of any principal).QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-15 Connecting from Clients and Applications Key Points Client applications connect to endpoints. users need to be identified before they are permitted to use the server. it can be configured to trust a Windows authenticator (such as Active Directory). For example. or resell this content. Connectivity The protocol that client applications use when connecting to the SQL Server relational database engine is known as Tabular Data Stream (TDS). The Licensed Content is licensed "as-is. It can store the login details for users directly within its own system databases. It is most commonly transported by the TCP/IP protocol. Other components of SQL Server use alternate protocols. clients to SQL Server Analysis Services communicate via the XML for Analysis (XML/A) protocol. It defines how requests are issued and how results are returned. . data must be held securely and access to the data is based on the identity of the user attempting to access the data. In that case. Please report any unauthorized use of this content to piracy@microsoft. SQL Server 2008 R2 does support connection over the Virtual Interface Adapter (VIA) protocol but the use of this protocol with SQL Server is now deprecated and should not be used for new implementations. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. Alternately. you are primarily concerned with the relational database engine.

without the need for application changes. Client Libraries Client applications use programming libraries to simplify their access to databases such as SQL Server. Please report any unauthorized use of this content to piracy@microsoft. This knowledge will assist you when you need to perform configuration or troubleshooting. and provided to you by QuickStart Intelligence. however. guarantees or conditions.QuickStart Intelligence 1-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Software Layers for Connections Key Points Connections to SQL Server are made through a series of software layers. For client applications that are This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. SNAC connects to these endpoints via network libraries such as TCP/IP. an application could be altered to work with a different database engine. It is important to understand how each of these layers interacts. This primarily involves wrapping the commands and results in the TDS protocol. OLEDB passes it to the database server without modification. By changing the ODBC configuration. OLEDB originally stood for Object Linking and Embedding for Databases. Open Database Connectivity (ODBC) is a commonly used library." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. When an application sends a SQL command. Network Libraries SQL Server exposes endpoints that client applications can connect to. . or resell this content. The SQL Server Native Access Component (SNAC) is a software layer that encapsulates commands issued by libraries such as OLEDB and ODBC into commands that can be understood by SQL Server and encapsulates results returned by SQL Server ready for consumption by these libraries. or VIA. Please note that the use of the VIA protocol with SQL Server is now deprecated. OLEDB is a library that does not translate commands. It operates as a translation layer that shields the application from some details of the underlying database engine. Named Pipes. The Licensed Content is licensed "as-is. The endpoint is used to pass commands and data to/from the database engine.com or by calling +1 800-785-3448. that meaning is now not very relevant. redistribute.

.com or by calling +1 800-785-3448. SQL Server Operating System (SQL OS) is a software layer that provides a layer of abstraction between the Relational engine and the available server resources. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-17 executing on the same computer as the SQL Server service. and provided to you by QuickStart Intelligence. It is illegal to reprint. redistribute. SQL Server Software Layers SQL Server receives commands via endpoints and sends results to clients via endpoints. The Licensed Content is licensed "as-is. Clients interact with the Relational engine which in turn utilizes the Storage engine to manage the storage of databases. a special "shared memory" network connection is also available. Please report any unauthorized use of this content to piracy@microsoft.

and SQL Server Compact Edition. SSMS provides IntelliSense to assist with writing queries. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 1-18 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Management Studio Key Points SQL Server Management Studio (SSMS) is the primary tool supplied by Microsoft for interacting with SQL Server services. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. When working with . Reporting Services. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. SSMS is used to execute queries and return results but it is also capable of helping users to analyze queries.com or by calling +1 800-785-3448. SQL Server Management Studio SSMS is an integrated environment that has been created within the Microsoft Visual Studio platform shell. SSMS is capable of connecting to a variety of SQL Server services including the database engine. or resell this content. SSMS shares many common features with Visual Studio. etc.sql files. and provided to you by QuickStart Intelligence. redistribute.). Analysis Services. SSMS provides graphical interfaces for configuring databases and servers. While all SQL Server relational database management tasks can be performed using the T-SQL language. The Licensed Content is licensed "as-is. guarantees or conditions. It offers rich editors for a variety of document types (.sql files. . Integration Services. many users prefer graphical administration tools as they are typically easier to use than the T-SQL commands.xml files.

expand Databases. Type the query shown in the snippet below. click Start. 4. 4. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. SELECT * FROM Production. 2. click Revert. and click Connect. 3. 5. or resell this content. click Microsoft SQL Server 2008 R2. 2. click Object Explorer. If you are prompted to confirm that you want to revert. In Hyper-V Manager. and Tables. Click Start. right-click 623XB-MIA-SQL1 and click Revert. . redistribute. In Object Explorer. The Licensed Content is licensed "as-is. point to Administrative Tools. In the Virtual Machine. 3. If you do not already have a Virtual Machine Connection window. 8. expand AdventureWorks2008R2. select Windows Authentication. Demonstration Setup 1. From the View menu. and click SQL Server Management Studio. ensure that Server Type is set to Database Engine. guarantees or conditions. click All Programs." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Product ORDER BY ProductID.com or by calling +1 800-785-3448.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-19 Demonstration 2A: SQL Server Management Studio Key Points In this demonstration you will see how to work with SQL Server Management Studio. In the Connect to Server window. Right-click the AdventureWorks2008R2 database and choose New Query. right-click 623XB-MIA-SQL1 and click Connect. In the Server name text box. Review the database objects. In the Authentication drop-down list. in the Virtual Machines pane. 7. and then click Hyper-V Manager. On the host computer. type (local). and provided to you by QuickStart Intelligence. 6. Demonstration Steps 1. Please report any unauthorized use of this content to piracy@microsoft.

com or by calling +1 800-785-3448. In the Connect to Database Engine window. Right-click in the query window and click Connection. open the project D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ. Note the contents of Solution Explorer. 12. 22. and click Connect. From the View menu. 17. In the Solution Explorer. In Object Explorer. click No. click Solution Explorer. From the View menu. and expand General. click Close. and click Options." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click tempdb database. Note that SSMS is capable of more than simply executing queries. expand SQL Server. From the Tools menu.QuickStart Intelligence 1-20 Implementing a Microsoft® SQL Server® 2008 R2 Database 9. Right-click Dev Servers and click New Server Registration… This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 19. The Licensed Content is licensed "as-is. 16. click Open. In the Open Project window. From the File menu click Save SQLQuery1. expand Query Results. click New.ssmssln. right-click on the cell for ProductID 1 (first row and first cell) and click Save Results As…. and click New Server Group… 28.sql. click Registered Servers. from the Connect toolbar icon. 20. In the Authentication drop-down list. In the Registered Servers window. 11. In the FileName textbox. type Demonstration2AResults and click Save. 24. 25. 10. right-click Local Server Groups. In the Microsoft SQL Server Management Studio window. Review the available configuration options and click Cancel. It is illegal to reprint. guarantees or conditions. Note how the results can be returned. Note this will change the database that the query is executed against. and click Project/Solution. 14. In the Results tab. In the New Server Group Properties window type Dev Servers in the Group name textbox and click OK. and then click Execute on the toolbar. Note this saves the query to a file. or resell this content. 23. and click Database Engine Query to open a new connection. From the File menu. 26. expand Database Engine. click Display Estimated Execution Plan. type (local) in the Server name text box. 18. redistribute. and provided to you by QuickStart Intelligence. SQL Server projects have been supplied for each module of the course and contain demonstration steps and suggested lab solutions. From the File menu. . 13. In the Options pane. and click Change Connection… Note: this will reconnect the query to another instance of SQL Server. Note the use of Intellisense while entering it. In the File menu. 29. 15. From the Query menu. note the other SQL Server components that connections can be made to: • Database Engine • Analysis Services • Integration Services • Reporting Services • SQL Server Compact 21. along with any required setup/shutdown code for the module. In the Available Databases drop-down list. click the X to close it. select Windows Authentication. 27. Please report any unauthorized use of this content to piracy@microsoft. Note this saves the query results to a file.

In the New Server Registration window. Type the query as shown in the snippet below and click Execute toolbar icon. It is illegal to reprint. click Server name drop-down list. . Question: When would displaying an estimated execution plan be helpful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. type (local) and click Save.\MKTG and click Save. guarantees or conditions. redistribute. click Server name drop-down list. Right-click Dev Servers and click New Server Registration… 32. 34.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-21 30. and provided to you by QuickStart Intelligence. right-click the Dev Servers group and choose New Query. In the Registered Servers window. 31. In the New Server Registration window. or resell this content. 33. type . SELECT @@version." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.

The Licensed Content is licensed "as-is. Integration Services.com or by calling +1 800-785-3448.QuickStart Intelligence 1-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Business Intelligence Development Studio Key Points The SQL Server platform comprises a number of components." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. SQL Server installation will first install the "partner" edition of Visual Studio 2008 and then add the required project templates. If an existing installation of Visual Studio 2008 is present. and provided to you by QuickStart Intelligence. or resell this content. guarantees or conditions. SQL Server will install the partner edition of Visual Studio 2008 side-by-side with the existing Visual Studio 2010 installation. redistribute. BIDS in SQL Server 2008 R2 is based on Visual Studio 2008. Projects for several of the Business Intelligence related components are created and modified using Business Intelligence Development Studio (BIDS). . If no existing Visual Studio 2008 installation is present. Visual Studio does not need to be installed before SQL Server. The Partner edition of Visual Studio 2008 is essentially an empty Visual Studio shell with a template for a "blank solution". If Visual Studio 2010 is already installed. and Reporting Services. SQL Server installation will add project templates into that environment. The templates allow the creation and editing of projects for Analysis Services. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. Business Intelligence Development Studio BIDS is a series of project templates that have been added to the Microsoft Visual Studio 2008 environment.

guarantees or conditions. In the Select the Data Source window. SELECT ProductID. Name. click Microsoft SQL Server 2008 R2. Demonstration Steps 1. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Click Start. In the Design the Query window.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-23 Demonstration 2B: Business Intelligence Development Studio Key Points In this demonstration you will see how to work with SQL Server Business Intelligence Development Studio. type the following query as shown in snippet below and click Next. or resell this content. 3. 4. click Next. expand New. Please report any unauthorized use of this content to piracy@microsoft. and click Project. and click OK. right-click Reports and click Add New Report. note how they are still present as well). 8. In the Report Wizard window. redistribute. and provided to you by QuickStart Intelligence. If Demonstration 2A was not performed: Revert the 623XB-MIA-SQL1 virtual machine using Hyper-V Manager on the host system. . and click SQL Server Business Intelligence Development Studio (BIDS). Color. click Next. In the Templates pane. select AdventureWorks2008R2.Product ORDER BY ProductID. The Licensed Content is licensed "as-is. 6. click All Programs. 2. click Report Server Project. In Solution Explorer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 10. 9. In the Select the Data Source window. From the File menu. 7. It is illegal to reprint. Note the available project templates(If other languages are installed. In the Select the Report Type window. and connect to the Virtual Machine. In the Connection Properties window. Size FROM Production.com or by calling +1 800-785-3448. In the Virtual Machine. 5. for the Query string textbox. type (local) for the Server name and in the Connect to a database drop-down list. click Next. click Edit. and click OK.

click Preview and note the report that is rendered. In the Design the Table window. Please report any unauthorized use of this content to piracy@microsoft. 14. and provided to you by QuickStart Intelligence.QuickStart Intelligence 1-24 Implementing a Microsoft® SQL Server® 2008 R2 Database 11.com or by calling +1 800-785-3448. Question: Can you suggest a situation where the ability to schedule the execution of a report would be useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. In the Report1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click Details four times. and click Finish>>|. click Finish. 12. . 13.rdl [Design] tab. from the File menu click Exit. In the Completing the Wizard window. redistribute. Click on the Design tab. Note do not save the changes. The Licensed Content is licensed "as-is. or resell this content. guarantees or conditions.

redistribute. To avoid excess download file sizes. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. BOL is regularly updated and a regular check should be made for updates.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-25 Books Online Key Points Books Online (BOL) is the primary reference for SQL Server. many users will find the examples supplied easier to follow than the formal syntax definition. the formal syntax is shown at the top of the page and the examples are usually at the bottom of the page. For most T-SQL commands. or resell this content. . A common mistake when installing BOL locally on a SQL Server installation is to neglect to update BOL regularly. It is important to make sure you are working with the pages designed for the version of SQL Server that you are working with. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. Note that when viewing the reference page for a statement. Books Online BOL should be regarded as the primary technical reference for SQL Server. BOL is available for all supported versions of SQL Server. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Many pages in BOL provide links to related pages from other versions of the product. The Licensed Content is licensed "as-is. guarantees or conditions. and provided to you by QuickStart Intelligence. It can be installed offline (for use when disconnected from the Internet) and can also be used online directly from the Microsoft MSDN web site (via an Internet connection). BOL is not included in SQL Server service pack and cumulative update packages.

guarantees or conditions. 4. click Documentation and Tutorials. click All Programs. 9. Note the basic navigation options available within BOL. or resell this content. and click SQL Server Books Online. In the Server name text box. SELECT SUBSTRING('test string'.QuickStart Intelligence 1-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2C: Books Online Key Points In this demonstration you will see how to work with SQL Server Business Books Online. From the File menu. 2. click All Programs. type the query as shown in the snippet below and click Execute toolbar icon." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and connect to the Virtual Machine. In the Connect to Server window. Click Start. and click Connect. 6. In the Authentication drop-down list. In the Virtual Machine. . 7. then hit the F1 key to open the BOL topic for SUBSTRING.sql tab. Please report any unauthorized use of this content to piracy@microsoft. click Microsoft SQL Server 2008 R2. click Microsoft SQL Server 2008 R2. In the SQLQuery1.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. Click the name of the function SUBSTRING. ensure that Server Type is set to Database Engine. click New. 8. and click SQL Server Management Studio. Demonstration Steps 1.2.7). Click Start. 10. In the Contents window. click SQL Server 2008 R2 Books Online. In the Virtual Machine. It is illegal to reprint. If Demonstration 2A was not performed: Revert the 623XB-MIA-SQL1 virtual machine using Hyper-V Manager on the host system. select Windows Authentication. and click Query with Current Connection. 3. type (local). 5. and provided to you by QuickStart Intelligence. redistribute.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In the host system. It is illegal to reprint. 13. From the File menu. In the Online Help Settings window. and click OK. click Exit. redistribute. 12. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. open Internet Explorer and browse to the SQL Server Books Online page: http://msdn.aspx and note the available online options. and provided to you by QuickStart Intelligence. Note the content of the page and scroll to the bottom to see the examples. ensure Use local Help as primary source option button. guarantees or conditions.microsoft.com/en-us/library/ms130214." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-27 11. . or resell this content.com or by calling +1 800-785-3448.

or resell this content. and provided to you by QuickStart Intelligence. as part of a policy of least privilege execution. guarantees or conditions. including the accounts that the services operate under. The ability to provide individual configuration for services assists organizations that aim to minimize the permissions assigned to service accounts. Please report any unauthorized use of this content to piracy@microsoft. Objectives After completing this lesson. It is important to know what each of these tools and utilities is used for. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .QuickStart Intelligence 1-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Configuring SQL Server Services Each SQL Server service can be configured individually. you will be able to: • • • • • Use SQL Server Configuration Manager Use SQL Server Services Use Network Ports and Listeners Create Server Aliases Use other SQL Server tools This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. SQL Server Configuration Manager is used to configure services. redistribute. It is illegal to reprint. SQL Server also ships with a variety of tools and utilities. and the network libraries used by the SQL Server services.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. or resell this content. redistribute. there is a need to configure how connections from those tools are made to SQL Server.com or by calling +1 800-785-3448. . Managing Client Protocols – When client applications (such as SSMS) are installed on a server. and provided to you by QuickStart Intelligence. Managing Server Protocols – It is possible to configure the endpoints that are exposed by the SQL Server services. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. to configure the network libraries exposed by SQL Server services. SSCM can be used to configure the protocols required and can be used to create aliases for the servers to simplify connectivity. The Licensed Content is licensed "as-is. Question: Why would a server system need to have a client configuration node? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and to configure how client connections are made to SQL Server. SQL Server Configuration Manager SSCM can be used for three distinct purposes: • • • Managing Services – Each service can be controlled (started or stopped) and configured. This includes the protocols and ports used.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-29 SQL Server Configuration Manager Key Points SQL Server Configuration Manager (SSCM) is used to configure SQL Server services.

it shows the associated instance of SQL Server in parentheses after the name of the service. Services that are set to the Manual start mode can be manually started. Each service has a start mode. MSSQLSERVER is the default name allocated to the default instance of the SQL Server database engine. SSCM should be used to make this change. Please report any unauthorized use of this content to piracy@microsoft. When SSCM lists each service. When service identities are modified from within SSCM. The components of SQL Server that you choose during installation determine which of the SQL Server services are installed. there are two instances of the database engine installed. If there is a need to alter the assigned identity for a service. . Services that are set to the Automatic start mode are automatically started when the operating system starts. While this applet will change the identity for the service. it will not update the other permissions and access control lists that are required for the service to operate correctly. Instances Many SQL Server components are instance-aware and can be installed more than once on a single server. or Disabled. Manual. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. In the example shown in the slide. or resell this content. This mode can be set to Automatic. The Licensed Content is licensed "as-is. guarantees or conditions. SQL Server Services These services operate within a specific Windows identity." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Many components provided by SQL Server are implemented as operating system services. A common error is to use the Services applet in the server's administrative tools to change the service identity.com or by calling +1 800-785-3448. the required permissions and access control lists are also modified. redistribute. PARTNER is the name of a named instance of the database engine. Services that are set to the Disabled start mode cannot be started.QuickStart Intelligence 1-30 Implementing a Microsoft® SQL Server® 2008 R2 Database SQL Server Services Key Points SQL Server Configuration Manager can be used to configure the individual services that are provided by SQL Server. and provided to you by QuickStart Intelligence.

this will involve settings such as protocol port numbers. Each network endpoint that is exposed by an instance of SQL Server can be configured. Many protocols provide multiple levels of configuration. The client configuration nodes within SSCM can be used to configure how those connections are made. Typically. it uses the SNAC library to make connections to the SQL Server services that are on the same system. You should discuss the required network protocol configuration of SQL Server with your network administrator. and provided to you by QuickStart Intelligence. SSMS is a 32-bit application. When SSMS is installed on the server.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-31 Network Ports and Listeners Key Points SQL Server Configuration Manager can be used to configure both server and client protocols and ports. even when SQL Server is installed as a 64-bit application.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. One set is used for 32-bit applications. guarantees or conditions. for each library." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . This includes the determination of which network libraries are enabled and. It is illegal to reprint. redistribute. SNAC is installed on the server as well as on client systems. or a general set of configurations that are applied to all IP addresses. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. the configuration for the TCP/IP protocol allows for different settings on each configured IP address if required. the other set is used for 64-bit applications. Network Ports and Listeners SSCM provides two sets of network configurations. For example. Note that two sets of client configurations are provided. Client Configurations Every computer that has SNAC installed needs the ability to configure how that library will access SQL Server services. The Licensed Content is licensed "as-is. or resell this content. the configuration of the network library.

Please report any unauthorized use of this content to piracy@microsoft." and utilizing the named pipes protocol "np" and named pipe address that is based on the name of the computer or the value "." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and port. In the example shown in the slide. protocol. protocol. redistribute. and port within an application is not desirable as these might need to change over time. or resell this content. and provided to you by QuickStart Intelligence. and port (if required). The client then only needs to connect to the name "Marketing". A server alias can be created and associated with a server. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." for the local computer. Aliases for 32-bit applications are configured independently of the aliases for 64-bit applications. Aliases Hard-coding connection details for a specific server. guarantees or conditions. aliases can be created for servers. The Licensed Content is licensed "as-is. To make this easier for client applications and to provide a level of available redirection.QuickStart Intelligence 1-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Creating Server Aliases Key Points Connecting to a SQL Server service can involve multiple settings such as server address.com or by calling +1 800-785-3448. Client applications can then connect to the alias without being concerned about how those connections are made. protocol. Each client system that utilizes SNAC (including the server itself) can have one or more aliases configured. . It is illegal to reprint. the alias "Marketing" has been created for the local server ".

redistribute. guarantees or conditions. . Database Engine Tuning Advisor Design indexes and statistics to improve database performance. or resell this content.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-33 Other SQL Server Tools Key Points SQL Server provides a rich set of tools and utilities to make working with the product easier." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SQL Server Management Objects (SMO) Provide a detailed . based on analysis of trace workloads. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. It is illegal to reprint. Master Data Services Configuration Manager Configure and manage SQL Server Master Data Services Reporting Services Configuration Manager Configure and manage SQL Server Reporting Services SQL Server Error and Usage Configure the level of automated reporting back to the SQL Server product Reporting team about errors that occur and on usage of different aspects of the product. and provided to you by QuickStart Intelligence. The most commonly used tools are listed in the following table: Tool Purpose SQL Server Profiler Trace activity from client applications to SQL Server.NET based library for working with management aspects of SQL Server directly from application code. Supports both the database engine and Analysis Services. PowerShell Provider Allow configuring and querying SQL Server using PowerShell. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft.

7. ensure that Server Type is set to Database Engine. It is illegal to reprint. 10. Switch to SSMS." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . In the Query window. In the Server name text box. type the query as shown in the snippet below. USE AdventureWorks2008R2 GO SELECT * FROM Person. 4. redistribute. 12. click SQL Server Profiler. 6. type (local). and click Connect. In the Virtual Machine. In the Server name text box. click All Programs. 3. In the Authentication drop-down list. In the Trace Properties window. 11. or resell this content. select Windows Authentication. 9. select Windows Authentication.QuickStart Intelligence 1-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: SQL Server Profiler Key Points In this demonstration you will see how SQL Server Profiler can capture traces of statements executed. type (local). In the Connect to Server window. In the Connect to Server window. Demonstration Steps 1. 5. Please report any unauthorized use of this content to piracy@microsoft. 2. and click SQL Server Management Studio. click New Query toolbar icon. Click Start. click Microsoft SQL Server 2008 R2. Note this will start a new trace with the default options. ensure that Server Type is set to Database Engine. The Licensed Content is licensed "as-is. If Demonstration 2A was not performed: Revert the 623XB-MIA-SQL1 virtual machine using Hyper-V Manager on the host system. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. From the Tools menu. and click Connect. and connect to the Virtual Machine.Person ORDER BY FirstName. guarantees or conditions.com or by calling +1 800-785-3448. In the Authentication drop-down list. and provided to you by QuickStart Intelligence. click Run. and click Execute toolbar icon. 8.

and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. 14. redistribute. Note the statement trace occurring in SQL Server Profiler. or resell this content. . From the File menu and click Stop Trace. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. Question: What could you use captured trace files for? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Switch to SQL Server Profiler." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-35 GO 13. 15.com or by calling +1 800-785-3448. click individual statements to see the detail shown in the lower pane. guarantees or conditions. In the Results grid.

Log on using the following credentials: • • User name: AdventureWorks\Administrator Password: Pa$$w0rd 12. If the Server Manager window appears. you will use the available virtual machine environment. In the Virtual Machines list. wholesaler and retailer of cycle products. 7. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 1-36 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 1: Introduction to SQL Server and its Toolset Lab Setup For this lab. and then click Hyper-V Manager.com or by calling +1 800-785-3448. In the Virtual Machine Connection window. 11. The owners of the company have decided to start a new direct marketing arm of the company. 10. On the host computer. Before you begin the lab. wait until the Press CTRL+ALT+DELETE to log on message appears. or resell this content. 9." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. check the Do not show me this console at logon check box and close the Server Manager window. Click Switch User. 8. . right-click 623XB-MIA-DC and click Start. click the Ctrl+Alt+Delete menu item. Lab Scenario AdventureWorks is a global manufacturer. It is illegal to reprint. The Licensed Content is licensed "as-is. In Hyper-V Manager. It has been created as a new company named Proseware. Even though it has been set up as a separate company. click Full Screen Mode. redistribute. then close the Virtual Machine Connection window. point to Administrative Tools. 5. it will receive This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In the Virtual Machine Connection window. On the Action menu. right-click 623XB-MIA-SQL1 and click Start. you must complete the following steps: 1. guarantees or conditions. and provided to you by QuickStart Intelligence. Right-click 623XB-MIA-SQL1 and click Connect. 6. From the View menu. 4. 2. wait until the Press CTRL+ALT+DELETE to log on message appears. in the Virtual Machines list. then click Other User. click Start. 13. Maximize the Hyper-V window. in the Virtual Machine Connection window. 3. Right-click 623XB-MIA-DC and click Connect. Inc.

and provided to you by QuickStart Intelligence. you are ensuring that the additional instance of SQL Server has been configured appropriately and making a number of additional required configuration changes." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. redistribute. Please report any unauthorized use of this content to piracy@microsoft. . guarantees or conditions. In this lab. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The existing AdventureWorks company SQL Server platform has been moved to a new server that is capable of supporting both the existing workload and the workload from the new company. It is illegal to reprint.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-37 some IT-related services from the existing AdventureWorks company and will be provided with a subset of the corporate AdventureWorks data. or resell this content. The Licensed Content is licensed "as-is.

(Ignore the Full Text Filter Daemon at this time). In the first exercise. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. .  Task 1: Check that Database Engine and Reporting Services have been installed for the MKTG instance • Open SQL Server Configuration Manager. and provided to you by QuickStart Intelligence. Results: After this exercise. you have checked that the required SQL Server services are installed.com or by calling +1 800-785-3448. Ensure that all required services including SQL Server Agent are started and set to autostart for both instances. • Check the installed list of services for the MKTG instance and ensure that the database engine and Reporting Services have been installed for the MKTG instance. (Ignore the Full Text Filter Daemon at this time). It will be used by the new direct marketing company. 2. redistribute. started. 3. It is illegal to reprint.  Task 2: Note the services that are installed for the default instance and that Integration Services is not installed on a per instance basis • Note the list of services that are installed for the default instance. Note the services that are installed for the default instance and that Integration Services is not installed on a per instance basis. and configured to autostart. you need to verify that the required SQL Server components have been installed. • Ensure that all the services for the default instance are set to autostart. The main tasks for this exercise are as follows: 1. guarantees or conditions. The SQL Server named instance is called MKTG.  Task 3: Ensure that all required services including SQL Server Agent are started and set to autostart for both instances • Ensure that all the MKTG services are started and set to autostart. Please report any unauthorized use of this content to piracy@microsoft. Check that Database Engine and Reporting Services have been installed for the MKTG instance. The Licensed Content is licensed "as-is. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 1-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Verify SQL Server Component Installation A new instance of SQL Server has been installed by the IT department at AdventureWorks. • Note that Integration Services has no instance name shown as it is not installed on a per-instance basis.

redistribute. Results: After this exercise. you will configure the services to execute under the AdventureWorks\PWService service account. Change the service account for the MKTG database engine. Please report any unauthorized use of this content to piracy@microsoft. Change the service account for the MKTG Reporting Services service.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-39 Exercise 2: Alter Service Accounts for New Instance Scenario The SQL Server services for the MKTG instance have been configured to execute under the AdventureWorks\SQLService service account." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. you have configured the service accounts for the MKTG instance.com or by calling +1 800-785-3448. . guarantees or conditions. The Licensed Content is licensed "as-is.  Task 1: Change the service account for the MKTG database engine • Change the service account for the MKTG database engine service to AdventureWorks\PWService using the properties page for the service. or resell this content. It is illegal to reprint. Change the service account for the MKTG SQL Server Agent. In this exercise. 2. and provided to you by QuickStart Intelligence. The main tasks for this exercise are as follows: 1.  Task 2: Change the service account for the MKTG SQL Server Agent • Change the service account for the MKTG SQL Server Agent service to AdventureWorks\PWService using the properties page for the service and then restart the service. 3.

 Task 3: Restart both database engine services • Restart the default database engine instance • Restart the MKTG database engine instance • Check to ensure that both instances have been restarted successfully Results: After this exercise. Restart database engine services for both instances. redistribute. 3. The Licensed Content is licensed "as-is. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 1-40 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 3: Enable Named Pipes Protocol for Both Instances Scenario Client applications that are installed on the server will connect to the database engine using the named pipes protocol. . Enable the named pipes protocol for the default instance.  Task 2: Enable the named pipes protocol for the MKTG instance • Enable the named pipes protocol for the MKTG database engine instance using the Protocols window. you should have enabled the named pipes protocol for both database engine instances." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. you will enable the named pipes protocol for both database engine instances. In this exercise. Enable the named pipes protocol for the MKTG instance. 2.  Task 1: Enable the named pipes protocol for the default instance • Enable the named pipes protocol for the default database engine instance using the Protocols window. It is illegal to reprint. and provided to you by QuickStart Intelligence. The main tasks for this exercise are as follows: 1.com or by calling +1 800-785-3448.

and provided to you by QuickStart Intelligence. you should have created and tested aliases for both database engine instances. • Connect to the Proseware alias. The Licensed Content is licensed "as-is. redistribute.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-41 Exercise 4: Create Aliases for AdventureWorks and Proseware Scenario Client applications that are installed on the server will use aliases to connect to the database engine services. Call the alias AdventureWorks and connect via named pipes. 4. In this exercise. 2.". or resell this content.".com or by calling +1 800-785-3448. Call the alias Proseware and connect via named pipes.  Task 2: Create a 32-bit alias (Proseware) for the MKTG instance • Create a 32-bit alias for the MKTG instance. Use the servername ". Use the servername ". Call the alias AdventureWorks and connect via named pipes. The main tasks for this exercise are as follows: 1. connect also to the AdventureWorks alias.  Task 3: Create a 64-bit alias (AdventureWorks) for the default instance • Create a 64-bit alias for the default instance. 5. Create a 64-bit alias (AdventureWorks) for the default instance. guarantees or conditions.\MKTG". Please report any unauthorized use of this content to piracy@microsoft. Call the alias Proseware and connect via named pipes. you will configure aliases for both the default instance (AdventureWorks) and for the MKTG instance (Proseware).  Task 4: Create a 64-bit alias (Proseware) for the MKTG instance • Create a 64-bit alias for the MKTG instance.  Task 1: Create a 32-bit alias (AdventureWorks) for the default instance • Create a 32-bit alias for the default instance.  Task 5: Use SQL Server Management Studio to connect to both aliases to ensure they work as expected • Open SQL Server Management Studio. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Create a 64-bit alias (Proseware) for the MKTG instance. • In Object Explorer. It is illegal to reprint. 3. Use SQL Server Management Studio to connect to both aliases to ensure they work as expected. Results: After this exercise. Use the servername ".\MKTG"." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Both 32-bit and 64-bit aliases should be configured. . Create a 32-bit alias (AdventureWorks) for the default instance. You will use SQL Server Management Studio to test the aliases once they have been configured. Use the servername ". Create a 32-bit alias (Proseware) for the MKTG instance.

you will have configured a fixed TCP port for the MKTG database engine instance and disabled the SQLBrowser service. Corporate policy at AdventureWorks is that named instances should be accessed via fixed TCP ports and the SQLBrowser service should be disabled. The main tasks for this exercise are as follows: 1. • Set the Start Mode for the SQL Browser service to Disabled. Results: After this exercise. Please report any unauthorized use of this content to piracy@microsoft. for use with the MKTG database engine instance.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. the port used for connections cannot be configured as a dynamic port. • Ensure that the MKTG database engine instance has been restarted successfully. Configure the TCP port for the MKTG database engine instance to 51550. .  Task 2: Disable the SQLBrowser service • Stop the SQLBrowser service. • Disable the SQLBrowser service. configure the use of the fixed port 51550. (Make sure that you clear the dynamic port) • Restart the MKTG database engine instance. you will make configuration changes to comply with these requirements. The port number must not change. or resell this content. It is illegal to reprint.QuickStart Intelligence 1-42 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits) Scenario Client applications will need to connect to the MKTG database engine instance via the TCP/IP protocol." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In this exercise. A firewall exception has already been created for port 51550. The Licensed Content is licensed "as-is. guarantees or conditions.  Task 1: Configure the TCP port for the MKTG database engine instance to 51550 • Using the property page for the TCP/IP server protocol. and provided to you by QuickStart Intelligence. As their connections will need to traverse a firewall.

3. If using an offline version of Books Online.com or by calling +1 800-785-3448. What is the difference between a SQL Server version and an edition? What is the purpose of the Business Intelligence Development Studio? Does Visual Studio need to be installed before BIDS? Best Practices 1. 2. guarantees or conditions. to avoid accidentally building applications that will not run for standard users. Develop using the least privileges possible. redistribute. . and provided to you by QuickStart Intelligence. It is illegal to reprint. 3. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. Ensure that developer edition licenses are not used in production environments. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. ensure it is kept up to date. The Licensed Content is licensed "as-is.QuickStart Intelligence Introduction to SQL Server 2008 R2 and its Toolset 1-43 Module Review and Takeaways Review Questions 1. 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

QuickStart Intelligence 1-44 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. . and provided to you by QuickStart Intelligence. It is illegal to reprint. or resell this content. guarantees or conditions.

redistribute. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. or resell this content. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. It is illegal to reprint.QuickStart Intelligence Working with Data Types 2-1 Module 2 Working with Data Types Contents: Lesson 1: Using Data Types 2-3 Lesson 2: Working with Character Data 2-19 Lesson 3: Converting Data Types 2-27 Lesson 4: Specialized Data Types 2-34 Lab 2: Working with Data Types 2-40 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . guarantees or conditions.

A very common design error is to use inappropriate data types. The Licensed Content is licensed "as-is. or resell this content.QuickStart Intelligence 2-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview One of the most important decisions that will be taken when designing a database is the data types to be associated with the columns of every table in the database. Please report any unauthorized use of this content to piracy@microsoft. you will see the range of data types that are available within SQL Server and receive advice on where each should be used." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. doing so is rarely a good idea. In this module. As an example. redistribute. while you can store a date in a string column. and provided to you by QuickStart Intelligence. It is illegal to reprint. you will be able to: • • • • Work with data types Work with character data Convert between data types Use specialized data types This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Objectives After completing this lesson. Other objects in SQL Server such as variables and parameters also use these same data types. guarantees or conditions. The data type of a column determines the type and range of values that can be stored in the column. .com or by calling +1 800-785-3448.

com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. you will be able to: • • • • • • • Understand the role of data types Use exact numeric data types Use approximate numeric data types Work with IDENTITY columns Use date and time data types Work with unique identifiers Decide on appropriate nullability of data This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. dates. Please report any unauthorized use of this content to piracy@microsoft. Objectives After completing this lesson. You will also see how to determine if a data type should be nullable or not. There are a range of data types that can be used for each of these. redistribute.QuickStart Intelligence Working with Data Types 2-3 Lesson 1 Using Data Types The most basic types of data that get stored in database systems are numbers. In this lesson. and provided to you by QuickStart Intelligence. . you will see the available range of data types that can be used for numeric and date-related data. guarantees or conditions. you will see how to work with string data types. In the next lesson. It is illegal to reprint. or resell this content. and strings." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

Constraining Values Data types are a form of constraint that is placed on the values that can be stored in a location. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. Query Optimization When SQL Server knows that the value in a column is an integer. Self-Documenting Nature Choosing an appropriate data type provides a level of self-documentation. For example. a tinyint column can only store values from 0 to 255. or resell this content. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. you can only store values between -32768 and 32767. redistribute. If all values were stored in the sql_variant (which is a data type that can store any type of value) or xml data types. variables. it may be able to come up with an entirely different query plan to one where it knows the location is holding text values. Please report any unauthorized use of this content to piracy@microsoft. The data type also determines which sorts of operations are permitted on that data and how those operations work. .QuickStart Intelligence 2-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Introducing Data Types Key Points Data types determine what can be stored in locations within SQL Server such as columns. For example. it's likely that you would need to store documentation about what sort of values can be stored in the sql_variant locations. They also determine the types of values that can be returned from expressions. you will not be able to store text in the location. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and parameters. data types also constrain the range of values that can be stored. if you choose a numeric data type. As well as constraining the types of values that can be stored. For example.com or by calling +1 800-785-3448. if you choose a smallint data type.

Users can also define data types that provide alternate names for the system data types and potentially further constrain them. These are known as alias data types.QuickStart Intelligence Working with Data Types 2-5 Data Types There are three basic sets of data types: System Data Type .com or by calling +1 800-785-3448. Managed code is discussed later in Module 16. and provided to you by QuickStart Intelligence. redistribute. Question: Why would it be faster to compare two integer variables that are holding the values 3240 and 19704 than two varchar(10) variables that are holding the values "3240" and "19704"? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.With managed code via SQL Server CLR integration. or resell this content. varchar." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.SQL Server provides a large number of built-in (or intrinsic) data types. User-defined Data Type . Examples of these would be integer. It is illegal to reprint. The Licensed Content is licensed "as-is. entirely new data types can be created. . There are two categories of these CLR types: system CLR data types (such as the geometry and geography spatial data types) and user-defined CLR data types that allow users to create their own data types. An example of an alias data type would be to define the name PhoneNumber as being equivalent to nvarchar(16). Please report any unauthorized use of this content to piracy@microsoft. and date. Alias Data Type . guarantees or conditions. Alias data types can help provide consistency of data type usage across applications and databases.

SQL Server uses the full word "integer" as a synonym for "int". based upon the size of the storage location for each: • • • • tinyint is stored in a single byte (that is. bigint is stored in eight bytes (that is. 32 bits) and stores values from -2147483648 to 2147483647." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 8 bits) and can be used to store the values 0 to 255. While it is easy to refer to a 64-bit value. If you placed a value of zero in a 64-bit integer location and executed a loop to simply add one to the value. on most common servers currently available. It is illegal to reprint. it is hard to comprehend how large these values are.5) location can store up to 12 digits with up to 5 digits after the decimal point. or resell this content.com or by calling +1 800-785-3448. They were used to store currency values with a fixed precision of four decimal places. Exact data types are the most common data type used in business applications. 64 bits) and stores very large integer values. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. smallint is stored in two bytes (that is. Please report any unauthorized use of this content to piracy@microsoft. decimal is the data type that should be used for monetary or currency values in most systems and any exact fractional values such as sales quantities (where part quantities can be sold) or weights. Exact Fractional Data Types SQL Server provides a range of data types for storing exact numeric values that include decimal places: • • • decimal is an ANSI compatible data type that allows you to specify the number of digits of precision and the number of decimal places (referred to as the scale). Note that tinyint cannot store any negative values unlike the other integer data types. It is a very commonly used data type. redistribute. int is stored in four bytes (that is. 16 bits) and stores values from -32768 to 32767.QuickStart Intelligence 2-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Exact Numeric Data Types Key Points Numeric data types can be exact or approximate. . money and smallmoney are SQL Server specific data types that have been present since the early days of the platform. and provided to you by QuickStart Intelligence. you would not reach the maximum value for many months. Integer Data Types SQL Server offers a range of integer data types that are used for storing whole numbers. numeric is a data type that is functionally equivalent to decimal. A decimal(12.

and bigint). The storage of the bit data type is optimized. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. in general when working with bits in applications. If there are 8 or less bit columns in a table. is also nullable. test for false values via: IF (@InputValue = 0) but test for positive values via: IF (@InputValue <> 0) rather than testing for a value being equal to 1. In general. In 2's complement notation (which is the encoding used to store smallint. To avoid any chance of mismatch. That means that a bit location can be in three states: NULL. Some languages store true values as 1.com or by calling +1 800-785-3448. Another aspect that surprises new users is that bit. Higher level programming languages differ about how they store true values in Boolean columns. or 1. Question: What would be a suitable data type for storing the value of a check box that can be 0 for unchecked. int. they are stored in a single byte. 1 for checked. bit values are commonly used to store the equivalent of Boolean values in higher-level languages. use decimal for monetary values. bit Data Type bit is a data type that is stored in a single bit. Note that there is not literal string format for bits in SQL Server. The Licensed Content is licensed "as-is. as can the integer values 1 and 0. TRUE is converted to 1 and FALSE is converted to 0. a one bit value would range from -1 to 0. or resell this content. as this will provide more reliable code. along with other data types. . 0.QuickStart Intelligence Working with Data Types 2-7 This is often the wrong number of decimal places for many monetary applications and the data type is not a standard data type. others store true values as -1. redistribute. guarantees or conditions. or -1 for disabled? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The string values TRUE and FALSE can be converted to bit values.

or resell this content. The increment is how much the value goes up by each time.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. IDENTITY columns can be used to replace the functionality from those other database engines. The ability to insert into an IDENTITY column can be enabled temporarily using a connection option. . Having the IDENTITY property on a column does not in itself ensure that the column is unique. While not identical to these. It is illegal to reprint.QuickStart Intelligence 2-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Working with IDENTITY Key Points It is common to require a series of numbers to be automatically provided for an integer column. The seed is the starting value. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. SET IDENTITY_INSERT ON can be used to allow the user to insert values into the column with the IDENTITY property instead of having it auto-generated. You may be familiar with auto-numbering systems or sequences in other database engines. The system variable @@IDENTITY returns the last identity value used within the session. The IDENTITY property on a database column indicates that the value for the column will not be provided by an INSERT statement but should be automatically provided by SQL Server. Both seed and increment default to a value of 1 if they are not specified. you specify a seed and an increment. This can be a problem with triggers that perform inserts on another table with an IDENTITY column as part of an INSERT statement. redistribute. Although explicit inserts are not normally allowed to columns with an IDENTITY property. Retrieving the Inserted Identity Value After inserting a row into a table. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. it is common to need to know the value that was placed into the column with the IDENTITY property. IDENTITY IDENTITY is a property typically associated with integer or bigint columns that provide automated generation of values during insert operations. When specifying the IDENTITY property. and provided to you by QuickStart Intelligence. guarantees or conditions. in any scope. there is no guarantee that values in a column with the IDENTITY property will be unique. it is possible to explicitly insert values. Unless there is also a unique constraint on the column.

it would return the identity value from the customer table." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. rather than the one from the customer table. The Licensed Content is licensed "as-is. . the @@IDENTITY variable would return the identity value from the logging table.QuickStart Intelligence Working with Data Types 2-9 For example. To deal effectively with this. the SCOPE_IDENTITY() function was introduced. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. Typically. It provides the last identity value within the current scope only. These were introduced in SQL Server 2008. this would be implemented by the use of the OUTPUT clause on the INSERT statement. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Another complexity relates to multi-row inserts. the customer might be assigned a new identity value. redistribute. However. or resell this content. if you insert a row into a customer table. It is illegal to reprint. In this situation.com or by calling +1 800-785-3448. you may want to retrieve the IDENTITY column value for more than one row at a time. and provided to you by QuickStart Intelligence. In the previous example. if a trigger on the customer table caused an entry to be written into an audit logging table when inserts are performed.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the current SQL Server implementation of the float data type is that if the scale value is from 1 to 24. SET @Counter = 0. Please report any unauthorized use of this content to piracy@microsoft.1. The inappropriate use of numeric data types can cause processing errors. They are used more commonly in scientific applications than in business applications. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. and provided to you by QuickStart Intelligence. It is illegal to reprint. then the scale is implemented as 24. Look at the following code and decide how many times the PRINT statement would be executed: DECLARE @Counter float. Approximate Numeric Values The real data type is a 4 byte (that is 32 bit) numeric value that is encoded using ISO standard floating point encoding. WHILE (@Counter <> 1. Even though a range of values are provided for in the syntax.QuickStart Intelligence 2-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Approximate Numeric Data Types Key Points SQL Server provides two approximate numeric data types. It is common to have small rounding errors creep into calculations. A very common design error made by new developers is to use the float or real data types for storing business values such as monetary values. that is.com or by calling +1 800-785-3448. The float data type is a SQL Server specific data type that allows for the storage of approximate values with a defined scale. The scale values permitted are from 1 to 53 and the default scale is 53. Common Errors A very common error for new developers is to use approximate numeric data types to store values that need to be stored exactly. a total that is out by 1 cent in dollar or euro based currencies. PRINT @Counter. guarantees or conditions. redistribute. This causes rounding and processing errors.0) BEGIN SET @Counter += 0. a scale of 53 is used. . For any larger value. A "code smell" for picking new developers is to have columns of numbers that do not exactly add up to the displayed totals. The Licensed Content is licensed "as-is.

which does happen to be able to be stored precisely.8 0.4 0. .9 1 1.5 1. redistribute. 0. it's 0. The answer isn't 0. It might surprise you that this query would never stop running and would need to be cancelled. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.7 0. The Licensed Content is licensed "as-is.3.QuickStart Intelligence Working with Data Types 2-11 END.3 0." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.2 0.099999 recurring. After cancelling the query.1 each time. and provided to you by QuickStart Intelligence. if you look at the output you would see the following: 0.1 1. it just occurs at different values. Consider how you would write the answer to 1 / 3 in decimal. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.1 in decimal is a non-terminating fraction in binary.1 0.1 cannot be stored exactly in a float or real data type.7 … What has happened? The problem is that the value 0. So.3 1.4 1.3333333 recurring.com or by calling +1 800-785-3448. the value never exactly equals 1.5 0.0. The same problem occurs in binary fractions.6 0. There is no way in decimal to write 1 / 3 as an exact decimal fraction. 0.1 ends up being stored as the equivalent of 0. You have to eventually settle for an approximate value. It is illegal to reprint.2 1. when you put the system in a loop adding 0.6 1. or resell this content.

would cause the value '20110101 00:00:00. redistribute. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. The datetime2 data type is a combination of a date data type and a time data type. The time data type is aligned to the SQL standard form of hh:mm:ss with optional decimal places up to hh:mm:ss. The format that SQL Server uses is similar to the ISO 8601 definition for TIME. with the datetime data type. . datetime Data Type The datetime data type is an older data type that had a smaller range of allowed dates and a lower precision or accuracy. These are not supported in the SQL Server implementation. date and time Data Types The date data type complies with the ANSI SQL standard definition for the Gregorian calendar. The default string format is YYYY-MM-DD. or resell this content. For example. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. date has a range of values from 0001-01-01 to 9999-12-31 with an accuracy of one day.nnnnnnn. The ISO 8601 standard also allow using 24:00:00 to represent midnight and a leap second over 59. This format is the same as the ISO8601 definition for DATE.999'. Please report any unauthorized use of this content to piracy@microsoft. Note that you need to specify the number of decimal places when defining the data type such as time(4). A common error is to not allow for the 3ms accuracy of the data type. SQL Server also provides a large number of functions for working with dates and times. It is important to be very careful when working with string literal representations of these values and with their precision (or accuracy).and time-related values.com or by calling +1 800-785-3448.QuickStart Intelligence 2-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Date and Time Data Types Key Points SQL Server supports a rich set of data types for working with date.000' to actually be stored. executing the following code: DECLARE @When datetime. and provided to you by QuickStart Intelligence. SET @When = '20101231 23:59:59.

or resell this content. so a string that was in form 'YYYY-MM-DD' could be interpreted as two different dates by the date (and datetime2) data type and the datetime data type.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. A range of system functions has been provided for working with timezone values. A value in the form 'YYYYMMDD' will always be converted to the correct date but a value in the form 'YYYY-MM-DD' might end up being interpreted as 'YYYY-DD-MM' depending on the settings for the session. guarantees or conditions. It is illegal to reprint.QuickStart Intelligence Working with Data Types 2-13 Another problem with the datetime data type is that the way it converts strings to dates is based on language format settings. and provided to you by QuickStart Intelligence. It is important to understand that this behaviour does not happen with the new date data type. redistribute. Note that the timezone offset values extend for more than a full day (range of -14:00 to +14:00). Question: Why is the specification of a date range from the year 0000 to the year 9999 based on the Gregorian Calendar not entirely meaningful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Timezones The datetimeoffset data type is a combination of a datetime2 data type and a timezone offset. The Licensed Content is licensed "as-is. it is simply capable of storing and retrieving timezone values. Please report any unauthorized use of this content to piracy@microsoft. . Note that the data type is not timezone aware. as well as with all the date and time related data types.

or resell this content. >. guarantees or conditions. SQL Server 2005 introduced the NEWSEQUENTIALID() function to attempt to get around the randomness of the values generated by NEWID(). the function does so at the expense of some guarantee of uniqueness. GUIDs are 128-bit values. <> (or !=). They are calculated by calling system functions that generate a value for you. When discussing the bigint data type earlier. very large values. you learned that the 64-bit bigint values were really large. The magnitude of a 128-bit value is well beyond our capabilities of comprehension. GUIDs Numbering systems have traditionally depended on a central source for the next value in a sequence to make sure that no two processes use the same value. Standard arithmetic operators such as =. However. <. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. uniqueidentifier Data Type The uniqueidentifier data type in SQL Server is typically used to store globally unique identifiers. very high degree of probability. In SQL Server. <=.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. The random nature of GUIDs has also caused significant problems in current storage subsystems. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is achieved by using very. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence 2-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Unique Identifiers Key Points Globally unique identifiers (GUIDs) have become common in application development. this function is the NEWID() function. GUIDs were introduced to avoid the need for anyone to function as the "number allocator". and provided to you by QuickStart Intelligence. They are used to provide a mechanism where any process can generate a number at will and know that it will not clash with a number generated by any other process. and >= are supported along with NULL and NOT NULL checks. redistribute. New values are not calculated by code in your process. Any process (and on any system) can generate a value and know that it will not clash with a value generated by any process across time and space and on any system to a very. The IDENTITY property is not used with uniqueidentifier columns.

QuickStart Intelligence Working with Data Types 2-15 The usefulness of NEWSEQUENTIALID() is also quite limited as the main reason for using GUIDs is to allow other layers of code to generate the values and know they can just insert them into a database without clashes. The Licensed Content is licensed "as-is. Replication is an advanced topic beyond the scope of this course. you usually would have been better to use an IDENTITY column instead. . redistribute. What would be wrong with this? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Note: uniqueidentifier columns are also commonly used by replication systems. and provided to you by QuickStart Intelligence. If you need to request a value from the database via NEWSEQUENTIALID(). or resell this content. A very common development error is to store GUIDs in string values rather than in uniqueidentifier columns. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. Question: The slide mentions that a common error is to store GUIDs as strings.com or by calling +1 800-785-3448.

Careful consideration must be given to the nullability of a column. As well as specifying a data type for a column. you specify whether or not a value needs to be present. you write code that says: WHERE Color IS NULL. You do not write code that says: WHERE Color = NULL. zero-length strings. guarantees or conditions. Common Errors New developers will often confuse NULL values with zero. etc. Look at the NULL and NOT NULL declarations on the slide and decide why each decision might have been made. Instead. you say that a value is NULL. This is why in T-SQL." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is exasperated by other database engines that treat NULL and zero-length strings or zeroes as identical. Please report any unauthorized use of this content to piracy@microsoft. redistribute. and provided to you by QuickStart Intelligence. (Often this is referred to as whether or not a column is mandatory). NULL NULL is a state that a column is in. blank (or space). you do not check whether a value is NULL with the equality operator. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . It is illegal to reprint. or resell this content.QuickStart Intelligence 2-16 Implementing a Microsoft® SQL Server® 2008 R2 Database NULL or NOT NULL Columns Key Points Nullability determines if a value must be present or not. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. Assigning inappropriate nullability of columns is another very common design error. You do not say that a value equals NULL. NULL indicates the absence of a value. rather than a type of value that is stored in a column.

com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.QuickStart Intelligence Working with Data Types 2-17 Question: When should a value be nullable? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. It is illegal to reprint. redistribute. or resell this content. and provided to you by QuickStart Intelligence.

2. or resell this content. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. From the File menu. It is illegal to reprint. 5. 4.QuickStart Intelligence 2-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Working with Numeric Data Types Key Points In this demonstration you will see: • Work with IDENTITY values • Work with NULL • Insert GUIDs into a table Demonstration Steps 1. navigate to D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ. Open and execute the 00 – Setup.com or by calling +1 800-785-3448. click Start. click All Programs. guarantees or conditions. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. click SQL Server Management Studio.ssmssln and click Open. Open the 11 – Demonstration 1A. Follow the instructions contained within the comments of the script file. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 3. In the Connect to Server window. click Microsoft SQL Server 2008 R2. . and provided to you by QuickStart Intelligence.sql script file.sql script file from within Solution Explorer. click Open. redistribute. In the virtual machine. type Proseware in the Server name text box and click Connect. click Project/Solution." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will be able to: • • • Explain the role of Unicode encoding Use character data types Work with collations This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence.QuickStart Intelligence Working with Data Types 2-19 Lesson 2 Working with Character Data In the last lesson.com or by calling +1 800-785-3448. or resell this content. In this lesson. Collations define how string data is sorted. and strings. The Licensed Content is licensed "as-is. redistribute. You also looked at the available range of data types that can be used for numeric and date-related data. you will now look at the other very common category of data: the string-related data types. you will also see how collations are defined and used. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. guarantees or conditions. you saw that the most basic types of data that get stored in database systems today are numbers. . There are a range of data types that can be used for each of these. Another common class of design and implementation errors relates to collations. In this lesson. Objectives After completing this lesson. dates.

Please report any unauthorized use of this content to piracy@microsoft. Multi-byte Character Issues Consider Asian languages such as Chinese or Japanese that need to store thousands of characters. most computer systems stored one character per byte. This only allowed for 256 different character values. It is illegal to reprint.com or by calling +1 800-785-3448. One option is to have an English-like version of the language that can be used for entry. means "woman". Please note the third character in the screenshot above.QuickStart Intelligence 2-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Understanding Unicode Key Points Traditionally. If a Chinese writer enters a pinyin word like "ma" on a keyboard. It might not seem important to an English-speaking person but given that the first option means "horse". the following list of options appears: They can then enter the number beside the character to select the intended word. you see this list: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. select a group of characters based on what is known as a radical. which is not enough to store characters from many languages. 女. guarantees or conditions. If you select the woman radical. Chinese has a form called pinyin that is also somewhat English-like. Rather than entering Englishlike characters (that could be quite unfamiliar to the writers). redistribute. and provided to you by QuickStart Intelligence. Japanese does in fact have a language form called Romaji that uses English-like characters for representing words." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The left-hand part of that character. You may not have ever considered it but how would you type these characters on a keyboard? There are two basic ways that this is accomplished. The Licensed Content is licensed "as-is. the second option is like a question mark. and the third option means "mother". or resell this content. there is definitely a need to select the correct option! Character Groups An alternate way to enter the characters is via radical groupings. .

It is illegal to reprint. not just stored as one large sea of characters. or resell this content. guarantees or conditions. Unicode introduced a two-byte character set that attempts to fit the values from the three bytes into two bytes. When working with character strings. an N prefix on a string allows the entry of double-byte characters into the string rather than just single-byte characters. You can imagine that three was not an ideal number for computing and at the time users were mostly working with 2 byte (that is. For string literal values." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. trade-offs had to occur. The answer was three bytes.QuickStart Intelligence Working with Data Types 2-21 Please note that the character representing "mother" is the first character on the second line. An additional complexity is that the radicals themselves are also in groups. Inevitably then. and UTF-32. UTF-8. For this sort of keyboard entry to work. Please report any unauthorized use of this content to piracy@microsoft. (N stands for "National" in "National Character Set"). (UTF is universal text format). The Licensed Content is licensed "as-is. 16 bit) computer systems. You can see in the screenshot that the woman radical was part of the third group of radicals. the characters must be in appropriate groups. .com or by calling +1 800-785-3448. Question: Do you recognize either of the phrases on the slide? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. UTF-16. redistribute. Unicode In the 1980s. There are multiple encodings for Unicode with UTF-7. Unicode allows any combination of characters that are drawn from any combination of languages to exist in a single document. work was done to determine how many bytes are required to be able to hold all characters from all languages but also store them in their correct groupings. and provided to you by QuickStart Intelligence. the LEN function returns the number of characters (Unicode or not) whereas DATALENGTH returns the number of bytes. SQL Server currently implements double-byte characters for its Unicode implementation.

The char and nchar data types are not very useful for data that varies in length but are ideal for short strings that are always the same length. it is common to need to trim the trailing characters. They are used for strings where a maximum length is specified but where the length varies. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. it returns: "Hello There " Note the trailing spaces. Look at the following code: DECLARE @String1 char(10). When retrieving values from char and nchar data. This is This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. When executed. By default. DECLARE @String2 char(10). SET @String2 = 'There'. They differ by length and by character encoding. and provided to you by QuickStart Intelligence. It is important to realize that if you specify char(50) then 50 characters will be stored and retrieved. char and nchar Data Types The char and nchar data types are data types that allow you to specify the number of characters that will be stored.QuickStart Intelligence 2-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Character Data Types Key Points SQL Server provides a range of string data types for storing characters. for example. . SELECT @String1 + @String2. state codes in the U. these characters will be spaces (or blanks). SET @String1 = 'Hello'.S. guarantees or conditions.A. char is for single-byte character sets and nchar is designed for double-byte Unicode characters. varchar and nvarchar Data Types The varchar and nvarchar data types are the "varying" equivalents of the char and nchar data types. these data types incur the overhead of storing the length of the string separately to the string itself. Rather than allocating a location of a fixed size and allocating the whole location regardless of the length of the string. The Licensed Content is licensed "as-is. redistribute.com or by calling +1 800-785-3448.

text and ntext Data Types The text and ntext data types are older data types that are now deprecated and should not be used for new work. The varchar(max) and nvarchar(max) data types should be used instead.QuickStart Intelligence Working with Data Types 2-23 of great benefit when the length of the strings being stored varies and it also avoids the need to trim the right-hand-side of the string in most applications. respectively. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. sysname is an alias data type that is currently mapped to nvarchar(128). or resell this content. sysname Data Type You will often see object names in SQL Server referred to as being of sysname data type. Question: Why would you use the sysname data type rather than the nvarchar(128) data type? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. varchar(max) and nvarchar(max) Data Types It has become common to store even longer string values. Please report any unauthorized use of this content to piracy@microsoft. This is roughly what fits in a data page in a SQL Server database. guarantees or conditions. redistribute. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. The varchar and nvarchar data types are limited to 8000 and 4000 characters. The varchar(max) and nvarchar(max) data types are used for this. It is illegal to reprint. They each allow up to around 2GB of data to be stored.

guarantees or conditions. redistribute. as the screen and the printer were using different characters in the values above 127. (As an example." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. For values above 127 though.com or by calling +1 800-785-3448. The values from 0 to 31 were reserved for "control characters" such as backspace (character 8) and tab (character 9). Problems did arise when different vendors used the upper characters for different purposes. Both the operating systems and SQL Server support a range of code pages. The MSDOS operating system categorized these as "code pages". This allowed for 256 possible values. Character 32 was allocated for a space and so on. with a range from 0 to 255. the DEC10 system from Digital Equipment Corporation stored 5 characters of 7 bits each per 36bit computer "word". up to the Delete character which was assigned the value 127. standards were initially not very clear. A number of standard character sets that described what should be in the upper code values did appear. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence 2-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Understanding Collations Key Points Collations in SQL Server are used to control the code page that is used to store non-Unicode data and the rules that govern how SQL Server sorts and compares character values. In the 1970's. The Licensed Content is licensed "as-is. or resell this content. . It was common to store characters such as line drawing characters or European characters with accents or graves in these codes. a number of computer systems only used 7 bits to store characters instead of 8 bits. What a code page really defines is which characters are used for the values from 128 to 255. In fact. It is illegal to reprint. Code Pages It was mentioned earlier that computer systems traditionally stored one byte per character. it was not uncommon to type a character on your screen and see a different character when that document was printed. It used the final bit as a parity check bit).

ComparisonStyle Either BIN for binary or a combination of case and accent sensitivity. If the column contained 'Ball'. Another use of this is as shown in the example in the slide. It is illegal to reprint. which is greater or less than the other when you sort them? SQL Server Collations SQL Server provides a concept of "collations" for dealing with these issues. . AI is accent-insensitive. SQL Server collations are retained for backward compatibility but you are encouraged to make use of Windows collations instead. There are two types of collations: SQL Server collations and Windows collations. AS is accent-sensitive. Windows collation Latin1_General_CI_AS refers to Latin1_General as the alphabet being used." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. Latin1_General is the alphabet being used. CS is case-sensitive. When comparing values from different collations. databases. Please report any unauthorized use of this content to piracy@microsoft. case-insensitive and accentsensitive. and even columns. it would not then match. you need to then specify which collation (which could yet another collation) will be used for the comparison. you are forcing the query to perform a case-sensitive comparison between the string '%ball%' and the value in the column. Windows collations have similar naming but with less fields. for example. the code page is 850. and provided to you by QuickStart Intelligence. In this case. is the value "mcdonald" equal to the value "McDonald"? Does the letter "á" (that is. or resell this content. the collation SQL_Latin1_General_Pref_CP850_CI_AS indicates that it is a SQL collation. SQL Server collations have names that are in the form: SQL_SortRules[_Pref]_CPCodePage_ComparisonStyle The elements of this are: SQL The actual string "SQL" SortRules A string identifying the alphabet or language that are applied when dictionary sorting is specified Pref An optional string that indicates an uppercase preference CodePage One to four digits that define the code page used by the collation. there is a preference for upper-case. For example. and sorting is performed case-insensitive and accent-sensitive. As an example. Question: What are the code page and sensitivity values for the collation QL_Scandinavian_Cp850_CI_AS? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. with an accent) equal the letter "a" (without an accent)? If they are not equal. CI is caseinsensitive.QuickStart Intelligence Working with Data Types 2-25 Sorting and Comparing Another issue that arises with character sets deals with how string values are sorted or compared. guarantees or conditions. CP850 specifies code page 850. For curious historic reasons. For example. Collation Issues The main issues with collations occur when you try to compare values that are stored with different collations. The Licensed Content is licensed "as-is. CP1 specifies code page 1252 but for all others the number indicates the code page.com or by calling +1 800-785-3448. It is possible to set default collations for servers.

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. Open the 21 – Demonstration 2A. click Open." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 3. Follow the instructions contained within the comments of the script file. click Start. click Microsoft SQL Server 2008 R2. click All Programs. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. The Licensed Content is licensed "as-is.sql script file from within Solution Explorer. redistribute. or resell this content. . In the Connect to Server window. type Proseware in the Server name text box and click Connect. click SQL Server Management Studio. and provided to you by QuickStart Intelligence. navigate to D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ.sql script file. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 2-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: Working with Character Data Key Points In this demonstration you will see how to: • How to work with Unicode and non-Unicode data • How to work with collations Demonstration Steps 1. • Open and execute the 00 – Setup. From the File menu. click Project/Solution. It is illegal to reprint.com or by calling +1 800-785-3448.ssmssln and click Open.

There are a number of issues that can arise when making conversions between data types. Objectives After completing this lesson.QuickStart Intelligence Working with Data Types 2-27 Lesson 3 Converting Data Types Now that you have learned about the most common data types." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. It is illegal to reprint. you will be able to: • • • • Use the CAST function Use the CONVERT function Allow implicit data conversion to occur Describe some common issues that arise during conversion This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. you need to consider that data is not always already in an appropriate data type. You will learn about these issues in this lesson. . and provided to you by QuickStart Intelligence. guarantees or conditions. For example. Please report any unauthorized use of this content to piracy@microsoft. redistribute. You can control how this is done or you can try to let SQL Server do the conversions implicitly. you may have received data from another system and you may need to convert the data from one data type to another.

guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Look at the expression: CAST(ListPrice AS varchar(12)) This expression takes the ListPrice column (likely to be a decimal value) and casts it as a string value. Note that you are not exhibiting control over how the decimal value will be formatted as a string." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Question: Give an example of a situation where you would need to cast a number as a string. For example. CAST You can use the CAST function to explicitly convert data from one type to another. The Licensed Content is licensed "as-is. you may need to return a number as a string value.QuickStart Intelligence 2-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Using CAST Key Points Available data is not always in the data type that it is needed in. CAST is based on the SQL standards. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. The CAST function is used to convert data. redistribute. only that it will be converted to a string. An error is returned if the cast is not possible or is not supported. This requires converting the data from one data type to another. It is illegal to reprint.

com or by calling +1 800-785-3448. or resell this content. the expression: CONVERT(varchar(8). redistribute. at times more control is needed on how a conversion is carried out than what CAST allows for. The Licensed Content is licensed "as-is. .112) would return the current date formatted as YYYYMMDD. CONVERT is a SQL Server extension to the SQL language that is more powerful than CAST.12) would return the current date formatted as YYMMDD. Note: The style value is often assumed to just relate to character-based output but it can also be used for determining how an incoming string is parsed. CONVERT While CAST is a good option wherever it can be used as it is a SQL standard option." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. Note that for date-related styles. For example.SYSDATETIME().QuickStart Intelligence Working with Data Types 2-29 Using CONVERT Key Points CAST performs basic type casting but does not allow control over how the type cast will be performed. guarantees or conditions. removing 100 from the value will give you the equivalent style without the century.SYSDATETIME(). CONVERT allows you to specify the target data type and the source data element but also allows you to specify a style for the conversion. Style 112 specifies the format YYYYMMDD. So the expression: CONVERT(varchar(6). This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence.

SQL Server has no need to convert the values here as they are both int values and division is defined for int values. For example. guarantees or conditions. implicit type conversions should be avoided wherever possible as they can lead to unexpected consequences. what would you expect the output of the following code to be? SELECT 1 / 2. It is illegal to reprint. Question: Look at the slide examples. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. redistribute. . and provided to you by QuickStart Intelligence. In general. The Licensed Content is licensed "as-is. Suggest where implicit conversions are happening and from which data types to which other data types. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. implicit data conversion is attempted by SQL Server automatically.com or by calling +1 800-785-3448.QuickStart Intelligence 2-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Implicit Data Conversion Key Points When data isn't explicitly converted between types." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Implicit Data Conversion Not all types can be converted implicitly to all other types and errors will occur when this is not possible. The conversion is based on data type preference.

Style 112 suggest returning an 8 character string. target data type Value is truncated while being converted (sometimes silently) As an example.000'. execute the code "SELECT 5ee" and note the output. the datetime value '20051231 23:59:59. Value is changed while being converted (sometimes silently) As an example.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. Value is rounded while being converted (sometimes silently) As an example.999' is silently rounded to the value '20060101 00:00:00." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. . you cannot store the value 2340280923 in an int location. When you convert it to a 6 character string. It is illegal to reprint.112). Value is out of range for the Each data type has a range of values that can be stored. and provided to you by QuickStart Intelligence. Example Issues Issue Comment Inappropriate values for the If the data type target is integer. It is important to be aware of common situations that give rise to such errors. Assumptions are made Even though you might know the internal binary format of a data type This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Working with Data Types 2-31 Common Conversion Issues Key Points Data type conversion errors are commonplace. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. consider the expression CONVERT(varchar(6). or resell this content. For example.SYSDATETIME(). you are not going to be able to convert target data type most text strings to it. it is silently truncated.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. Some parsing issues are hard to understand. Attempt to control how conversions occur by making explicit conversions.com or by calling +1 800-785-3448. when working with the depend on language datetime data type. it is very dangerous to write code that depends on that knowledge. For this and other reasons. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. and provided to you by QuickStart Intelligence. The SELECT example given for 5ee is also a good example of this. redistribute. Note that the worst of these issues tend to occur during implicit type conversions. Some datetime conversions The string "2010-05-04" could be interpreted as 4th May 2010 or 5th April are deterministic and 2010 depending upon the language settings. The internal representation could change over time. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. settings.QuickStart Intelligence 2-32 Implementing a Microsoft® SQL Server® 2008 R2 Database about internal storage formats for data types (such as datetime). or resell this content. implicit type conversions should be avoided. guarantees or conditions.

guarantees or conditions. click Microsoft SQL Server 2008 R2. From the File menu.ssmssln and click Open. or resell this content. If Demonstration 1A was not performed: • • • 2.com or by calling +1 800-785-3448. click Open. In the Connect to Server window. Open and execute the 00 – Setup. click Project/Solution. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. navigate to D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ.sql script file from within Solution Explorer.sql script file. and provided to you by QuickStart Intelligence. It is illegal to reprint. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. type Proseware in the Server name text box and click Connect. In the virtual machine. click Start. The Licensed Content is licensed "as-is. redistribute. Follow the instructions contained within the comments of the script file. click All Programs. click SQL Server Management Studio.QuickStart Intelligence Working with Data Types 2-33 Demonstration 3A: Common Conversion Issues Key Points In this demonstration you will see: • How to convert date data types explicitly • How language settings can affect date conversions • How data can be truncated during data type conversion • Issues that can arise with implicit conversion Demonstration Steps 1. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 3. Open the 31 – Demonstration 3A.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. . guarantees or conditions. you will be able to: • • • Work with the timestamp and rowversion data types Work with alias data types Describe other SQL Server data types This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. These data types are not used as commonly as the data types that have been described earlier in the module but they fill important roles in development. or resell this content. redistribute.com or by calling +1 800-785-3448.QuickStart Intelligence 2-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 4 Specialized Data Types You have now covered the common SQL Server data types but SQL Server also includes a number of more specialized data types that it is useful to be aware of. Objectives After completing this lesson. The Licensed Content is licensed "as-is. It is illegal to reprint. and provided to you by QuickStart Intelligence.

a synonym was introduced for the timestamp data type. You modified your local copy and wanted to write the changes back to the database. SQL standards made use of a value called TIMESTAMP that was time-related. The rowversion should be used for all new work and the timestamp data type is now deprecated. This could lead to a race condition where the data could be modified between checking the value and writing the changes. rowversion Data Type Early versions of SQL Server provided the timestamp data type. you can include a predicate checking the rowversion in the WHERE clause. . and provided to you by QuickStart Intelligence. The naming of this data type was unfortunate as it suggested that the data type had something to do with time. How do you know if the underlying data had already been changed by someone else? You can do this by reading the rowversion value along with the customer's data. then you know that someone else had modified the value and you roll back the database change. For these reasons. Consider that you are reading a customer's details from your client application. The timestamp data type has been deprecated and replaced by rowversion. or resell this content. Implementing Optimistic Concurrency with rowversion The rowversion data type is a special data type that automatically changes to a different value whenever the row that contains a column of this data type is modified.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Then. called rowversion. Adding to the confusion. If no rows are updated. Please report any unauthorized use of this content to piracy@microsoft. when you write the data back.QuickStart Intelligence Working with Data Types 2-35 timestamp and rowversion Key Points The rowversion data type assists in creating systems that are based on optimistic concurrency." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. redistribute. The Licensed Content is licensed "as-is. It is illegal to reprint. which was not the case. Note that it isn't enough for you to read the rowversion value and check it before writing your changes.

It is illegal to reprint. or resell this content.com or by calling +1 800-785-3448. . redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.QuickStart Intelligence 2-36 Implementing a Microsoft® SQL Server® 2008 R2 Database Internal Storage rowversion holds a counter that increments across all changes in the entire database. The current rowversion value for a database can be returned from the system variable @@DBTS. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Another less-obvious advantage of using alias data types is that they can be very useful in automated code-generation. Please report any unauthorized use of this content to piracy@microsoft. an automated code generator that is constructing a default user interface for an application could know that the columns using this data type should be shown in a specific way within the user interface. or resell this content. . For example. For example. The Licensed Content is licensed "as-is. Alias Data Types In earlier versions of SQL Server. It is illegal to reprint. It avoids product numbers being created as nvarchar(20) in one part of an application and nvarchar(22) in another part of the application. In the example shown in the slide.QuickStart Intelligence Working with Data Types 2-37 Alias Data Types Key Points Alias data types are names given to subtypes of existing system built-in (or intrinsic) types. Note that this is not the case for other types created by CREATE TYPE. The use of alias types can help promote consistency in database designs.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. redistribute. code could be autogenerated to allow auto-dialling of any phone number. guarantees or conditions. a data type called ProductNumber has been created as equivalent to nvarchar(20) and NOT NULL. if a PhoneNumber data type is defined as nvarchar(16). The key advantage of doing this is consistency. The public database role is automatically granted REFERENCES permission on alias types created this way. an alias type was created by calling sp_addtype. Code that uses sp_addtype should be replaced by code using the CREATE TYPE statement. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

or resell this content. The xml data type is used to store semi-structured textual data.com or by calling +1 800-785-3448. The cursor data type is used to hold a reference to a cursor when constructing cursor-based code. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The image data type is an older SQL Server data type and is now deprecated." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The geometry and geography data types are used to store spatial data elements and are discussed in Module 19. It is implemented in managed code (like the geometry and geography spatial data types that will be discussed later in the course). It will be discussed further in Module 10. or a photo.QuickStart Intelligence 2-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Other Data Types Key Points SQL Server also offers a number of special data types. you may wish to store a music clip. For example. (It should be rarely used). . The Licensed Content is licensed "as-is. Other Data Types The binary. The xml data type will be covered in Modules 17 and 18. The table data type is used to hold an entire rowset. redistribute. These are important but less commonly used data types. The sql_variant data type is used to store data of an unknown data type. and provided to you by QuickStart Intelligence. guarantees or conditions. The hierarchyid data type was added in SQL Server 2008. It is illegal to reprint. It is used to represent a node in a tree. varbinary. a video clip. A number of other data types are shown in the table on the slide. Please report any unauthorized use of this content to piracy@microsoft. You should use the varbinary(max) data type in most cases where you would have used the image data type. and varbinary(max) data types are used for storing arbitrary binary large objects (blobs) in the database.

In the Connect to Server window. redistribute. navigate to D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ. guarantees or conditions. • Open and execute the 00 – Setup.ssmssln and click Open. click SQL Server Management Studio. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. click Start. click Project/Solution. Follow the instructions contained within the comments of the script file. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click All Programs.sql script file. • In the virtual machine.com or by calling +1 800-785-3448. type Proseware in the Server name text box and click Connect. From the File menu. 2. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Open.sql script file from within Solution Explorer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Open the 41 – Demonstration 4A. The Licensed Content is licensed "as-is. . click Microsoft SQL Server 2008 R2. 3.QuickStart Intelligence Working with Data Types 2-39 Demonstration 4A: rowversion Data Type Key Points In this demonstration you will see how: • How to use the rowversion data type Demonstration Steps 1.

point to Administrative Tools. • In the Virtual Machine Connection window. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. Please report any unauthorized use of this content to piracy@microsoft. • Right-click 623XB-MIA-SQL and click Connect. Wait for the revert action to complete. • In the Virtual Machine Connection window. click on the Revert toolbar icon.QuickStart Intelligence 2-40 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 2: Working with Data Types Lab Setup For this lab. The Licensed Content is licensed "as-is. In the Virtual Machines list. guarantees or conditions. In Virtual Machine Connection window. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 5. and provided to you by QuickStart Intelligence. redistribute. you must complete the following steps: 1. . 7. 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. if the virtual machine 623XB-MIA-DC is not started: 4. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. wait until the Press CTRL+ALT+DELETE to log on message appears. • Right-click 623XB-MIA-DC and click Start. • Right-click 623XB-MIA-DC and click Connect. It is illegal to reprint. On the host computer. and then click Hyper-V Manager. 2. 6. wait until the Press CTRL+ALT+DELETE to log on message appears. click the Ctrl-Alt-Delete menu item. Maximize the Hyper-V Manager window. Before you begin the lab. if the user is not already logged on: • On the Action menu. click Revert. If you are prompted to confirm that you want to revert.com or by calling +1 800-785-3448. 3. click Start.

in the Virtual Machine Connection window. select Windows Authentication and click Connect. check the Do not show me this console at logon check box and close the Server Manager window. In the Authentication drop-down list box. some of the columns need to be converted to alternate data types. she is concerned about email addresses and phone numbers. In the File menu. User name: AdventureWorks\Administrator ii.QuickStart Intelligence Working with Data Types • Click Switch User. From the View menu. Password: Pa$$w0rd 8. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. • Log on using the following credentials: i. In the Open Project window. The prospect that was contacted. and provided to you by QuickStart Intelligence. It is illegal to reprint. Supporting Documentation Table 1: PhoneCampaign Description Which campaign this relates to. If the Server Manager window appears. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In Solution Explorer. In Connect to Server window. She presents you with a list of organizational data requirements for each table. 2-41 10. The Licensed Content is licensed "as-is. 15. Comments related to the contact that was made." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 12. If you have time. there is another issue that your manager would like you to address. When the query window opens. and click Project/Solution. She is concerned about a lack of consistency in the use of data types across the organization. to avoid this inconsistency.ssmssln. if it was made. type Proseware in the Server name text box. You need to review the existing data types being used in the MarketDev database for this and create new data types that can be used in applications. and then click Other User. 11. Lab Scenario A new developer has sought your assistance in deciding which data types to use for three new tables she is designing. At present.com or by calling +1 800-785-3448. 9.sql. click Open. click Microsoft SQL Server 2008 R2. When contact was first attempted with the prospect. click All Programs. click Execute on the toolbar. In the virtual machine. redistribute. . click Full Screen Mode. double-click the query 00-Setup. open the project D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ. click Start. You need to decide on appropriate data types for each item. You also need to export some data from your existing system but while being exported. 13. and click SQL Server Management Studio. 14. guarantees or conditions.

Please report any unauthorized use of this content to piracy@microsoft. 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. Outcome of the contact: sale. Proposal Development. Complete. some are fractional with up to three decimal places) Date of order Promised delivery date This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Hot Estimated closing date Estimated revenue Delivery address Table 3: SpecialOrder Description Which prospect this order is for External supplier of the item Description of the item Quantity Required (some quantities are whole numbers. Contract Negotiations. redistribute. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. later follow-up. The Licensed Content is licensed "as-is. Qualification.com or by calling +1 800-785-3448. It is illegal to reprint.QuickStart Intelligence 2-42 Implementing a Microsoft® SQL Server® 2008 R2 Database When contact was actually made with the prospect. . or resell this content. Warm. Lost Date that the opportunity was raised Probability of success Rating: Cold.

guarantees or conditions. The output should show ProductID. redistribute.Product table that have demographic information. that is they have a SellEndDate. ProductName. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. and SellEndDate formatted as a string based on the following format: YYYYMMDD. The output should appear similar to: Query Requirement 2: A list of products from the Marketing. ProductName.QuickStart Intelligence Working with Data Types 2-43 Actual delivery date Special requirements (any comments related to the special order) Quoted price per unit (up to two decimal places) Query Requirement 1: A list of products from the Marketing. and provided to you by QuickStart Intelligence. The output should show ProductID.Product table that are no longer sold. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. The output should appear similar to: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and Demographics formatted as nvarchar(1000) instead of XML.

and SpecialOrder tables and determine column names and data types for each data item in the design. . Results: After this exercise. and provided to you by QuickStart Intelligence. Opportunity. She presents you with a list of organizational data requirements for each table. guarantees or conditions. Opportunity. It is illegal to reprint. You need to decide on appropriate data types for each item. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 2-44 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Choosing Appropriate Data Types Scenario In this exercise. a new developer has sought your assistance in deciding which data types to use for three new tables she is designing. you should have determined the columns names and data types for the following tables: PhoneCampaign.com or by calling +1 800-785-3448. or resell this content. The main tasks for this exercise are as follows: 1. and SpecialOrder. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Determine column names and data types  Task 1: Determine column names and data types • Review the supporting documentation for details of the PhoneCampaign. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is.

Review the second query requirement and write a SELECT statement to meet the requirement. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Review the first query requirement and write a SELECT statement to meet the requirement. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The output should look similar to the supplied sample.QuickStart Intelligence Working with Data Types 2-45 Exercise 2: Writing Queries With Data Type Conversions Scenario In this exercise. Results: After this exercise. guarantees or conditions. you need to export some data from your existing system. some of the columns need to be converted to alternate data types. you should have created two new SELECT statements as per the design requirements.  Task 3: Review the second query requirement and write a SELECT statement to meet the requirement • Review the supporting documentation for details for the second query requirement. .  Task 2: Review the first query requirement and write a SELECT statement to meet the requirement • Review the supporting documentation for details for the first query requirement. • Write a SELECT statement that returns the required data. The Licensed Content is licensed "as-is. redistribute. The output should look similar to the supplied sample.  Task 1: Connect to the MarketDev Database • Open a new query window against the MarketDev database. • Write a SELECT statement that returns the required data.com or by calling +1 800-785-3448. It is illegal to reprint. and provided to you by QuickStart Intelligence. 3. The main tasks for this exercise are as follows: 1. While being exported. Connect to the MarketDev Database 2. or resell this content.

The Licensed Content is licensed "as-is. . Please report any unauthorized use of this content to piracy@microsoft. The main tasks for this exercise are as follows: 1. she is concerned about email addresses and phone numbers. or resell this content. and provided to you by QuickStart Intelligence. It is illegal to reprint.QuickStart Intelligence 2-46 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits) Scenario In this exercise.  Task 2: Create a data type that stores phone numbers • Create a data type to be used to store phone numbers. Create a data type to be used to store phone numbers 3.  Task 3: Create a data type that stores email addresses • Create a data type to be used to stored email addresses. At present. you should have created two new data types that store phone numbers and email addresses. You need to review the existing data types being used in the MarketDev database for this and create new data types that can be used in applications.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. redistribute. Create a data type to be used to stored email addresses  Task 1: Investigate the storage of phone numbers and email addresses • Investigate how phone numbers and email addresses have been stored in the MarketDev database. Results: After this exercise. your manager is concerned about a lack of consistency in the use of data types across the organization. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Investigate the storage of phone numbers and email addresses 2. to avoid this inconsistency.

Avoid the use of any of the deprecated data types. It is illegal to reprint. redistribute. . 2. 3. Always choose an appropriate data type for columns and variables rather than using generic data types such as string or xml except where they are necessary. and provided to you by QuickStart Intelligence. What is the uniqueidentifier data type commonly used for? What are common errors that can occur during data type conversion? What date is present in a datetime data type if a value is assigned to it that only contains a time? Best Practices 1.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. always specify the nullability rather than leaving it to the system default settings. 2. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. Use sysname data type in administrative scripts involving database objects rather than nvarchar(128). In the majority of situations." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. 5. When defining columns. 6. do not store currency values in approximate numeric data types such as real or float. The Licensed Content is licensed "as-is. Use the unicode-based data types where there is any chance of needing to store non-English characters. 4. 3.QuickStart Intelligence Working with Data Types 2-47 Module Review and Takeaways Review Questions 1.

com or by calling +1 800-785-3448. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. guarantees or conditions. or resell this content. . redistribute. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence.QuickStart Intelligence 2-48 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

It is illegal to reprint. and provided to you by QuickStart Intelligence. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .com or by calling +1 800-785-3448. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.QuickStart Intelligence Designing and Implementing Tables 3-1 Module 3 Designing and Implementing Tables Contents: Lesson 1: Designing Tables 3-3 Lesson 2: Working with Schemas 3-15 Lesson 3: Creating and Altering Tables 3-21 Lab 3: Designing and Implementing Tables 3-32 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is.

." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. Once an appropriate design has been created. or resell this content. a Customer table would have columns such as CustomerName and CreditLimit and a row for each customer. Designing tables is often one of the most important roles undertaken by a database developer because incorrect table design leads to the inability to query the data efficiently. Please report any unauthorized use of this content to piracy@microsoft. it is then important to know how to correctly implement the design. and provided to you by QuickStart Intelligence. It is illegal to reprint. guarantees or conditions. Each table comprises a set of rows that describe entities and a set of columns that hold the attributes of an entity.com or by calling +1 800-785-3448.QuickStart Intelligence 3-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview In relational database management systems (RDBMS). For example. user and system data is stored in tables. In SQL Server. The Licensed Content is licensed "as-is. you will be able to: • • • Design Tables Work with Schemas Create and Alter Tables This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. tables are contained within schemas that are very similar in concept to folders that contain files in the operating system. Objectives After completing this module.

com or by calling +1 800-785-3448. . you will learn to work with the system tables that are supplied when SQL Server is installed." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. In addition. As all organizational data is held within database tables. Objectives After completing this lesson. you will learn the most important aspects of normalized table design along with the appropriate use of primary and foreign keys. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. you will be able to: • • • • • • Describe what a table is Normalize data Describe common Normalization Forms Explain the role of Primary Keys Explain the role of Foreign Keys Work with System tables This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. guarantees or conditions.QuickStart Intelligence Designing and Implementing Tables 3-3 Lesson 1 Designing Tables The most important aspect of designing tables involves determining what data each column will hold. In this lesson. it is critical to store the data with an appropriate structure. redistribute. The best practices for table and column design are often represented by a set of rules known as "normalization" rules.

Rows represent entities and columns define the attributes of the entities. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. or resell this content. tables are referred to as "relations". Each of these columns is defined with a specific data type. In formal relational database management system terminology. Naming Conventions Strong disagreement exists in the industry over naming conventions for tables. The main reason for this is that names should represent the entities. or sale. Tables Relational database management systems are not the only type of database system available but they are the most commonly deployed type of database management system at present. Please report any unauthorized use of this content to piracy@microsoft. . and sales. For example.QuickStart Intelligence 3-4 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a Table? Key Points Relational databases store data about entities in tables that are defined by columns and rows. it might become necessary to replace a table with a view or vice-versa." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. orders. supplier. For example. Each row of a table represents the details of a single entity. Prefixes were widely used in higher-level programming languages before the advent of strong typing (that is the use of strict data types) but are now rare. suppliers. product. The use of prefixes (such as tblCustomer or tblProduct) is widely discouraged. for example a single customer. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. not how they are stored. Tables store data about entities such as customers. For example. It is illegal to reprint. Name. order. redistribute. This could lead to views named tblProduct or tblCustomer. The Licensed Content is licensed "as-is. when trying to avoid breaking existing code. guarantees or conditions. the UnitWeight of a product might be allocated a decimal(18. and UnitWeight. Size. Columns define the information that is being held about each entity. during a maintenance operation.3) data type. Tables have no predefined order and can be used as a security boundary. a Product table might have columns such as ProductID. products.

an array of customers in a higher-level language could sensibly be called "Customers" yet referring to a single customer via "Customers[49]" seems awkward. redistribute. and/or triggers. Please report any unauthorized use of this content to piracy@microsoft. should a table that holds the details of a customer be called Customer or Customers? Proponents of plural naming argue that the table holds the details of many customers whereas proponents of singular naming argue that it is common to expose these tables via object models in higher-level languages and that the use of plural names complicates this process. Note also though that SQL Server supports the assignment of permissions at the column level as well as at the table level. When selecting rows from a table. stored procedures. . Row-level security is not available for tables but can be implemented via a combination of views. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The argument is not likely to ever be resolved either way and is not a SQL language-specific problem. The Licensed Content is licensed "as-is. It is illegal to reprint. For example.QuickStart Intelligence Designing and Implementing Tables 3-5 Another area of strong disagreement relates to whether table names should be singular or plural. Row Order Tables are containers for rows but they do not define any order for the rows that they contain. The most important aspect of naming conventions is that you should adopt a naming convention that you can work with and apply it consistently. but only if the output order matters. SQL Server may have to expend additional sorting effort to return rows in a given order and it is important that this effort is only expended when necessary. Security Tables can be used as security boundaries in that users can be assigned permissions at the table level. or resell this content. For example. and provided to you by QuickStart Intelligence. guarantees or conditions. SQL Server system tables (and views) have plural names." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. a user should specify the order that the rows should be returned in.

and then 3rd normal form in 1971. Intentional Denormalization Not all databases should be normalized. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. followed by 2nd normal form. The Licensed Content is licensed "as-is. Codd (August 23. As an example. 2003) was a British scientist who is widely regarded as having invented the Relational Model. It is common to intentionally denormalize databases for performance reasons or for ease of end-user analysis. Normalization Edgar F.QuickStart Intelligence 3-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Normalizing Data Key Points Normalization is a systematic process that is used to improve the design of databases. Codd introduced 1st normal form in 1970. redistribute. through a series of "normal forms". This model underpins the development of relational database management systems. higher forms of normalization have been introduced by theorists but most database designs today are considered to be "normalized" if they are in 3rd normal form. guarantees or conditions.com or by calling +1 800-785-3448. Codd introduced the concept of normalization and helped the concept evolve over many years. Tables might also be denormalized to avoid the need for time-consuming calculations or to minimize physical database design constraints such as locking. and provided to you by QuickStart Intelligence. dimensional models that are widely used in data warehouses (such as the data warehouses commonly used with SQL Server Analysis Services) are intentionally designed to not be normalized. Since that time." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . 1923 – April 18. It is illegal to reprint.

A more controversial reading of 1st Normal Form rules would disallow the use of nullable columns. guarantees or conditions. Most common table design errors in database systems can be avoided by applying normalization rules. For example. Duplicate rows should not exist in tables. The Licensed Content is licensed "as-is. normalizing a database design leads to an improved design. Supplier2. If unique keys are not present. Tables should have unique keys. or resell this content. No repeating groups should exist." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a column should not contain a comma-separated list of suppliers. Column values should not include repeating groups. Please report any unauthorized use of this content to piracy@microsoft. A candidate key is a column or set of columns that can be used to uniquely identify a row in a table. Create a separate table for each set of related data. duplicate rows could exist. a product table should not include columns such as Supplier1.QuickStart Intelligence Designing and Implementing Tables 3-7 Common Normalization Forms Key Points In general. general agreement exists on most common symptoms of violating the rules. redistribute. For example.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and Supplier3. . Identify each set of related data with a primary key. Normalization Normalization is used to: • free the database of modification anomalies • minimize redesign when the structure of the database needs to be changed • ensure the data model is intuitive to users • avoid any bias towards particular forms of querying While there is disagreement on the interpretation of these rules. It is illegal to reprint. 1st Normal Form Eliminate repeating groups in individual tables. and provided to you by QuickStart Intelligence.

. 3rd Normal Form Eliminate fields that do not depend on the key. you will see examples of common normalization errors.QuickStart Intelligence 3-8 Implementing a Microsoft® SQL Server® 2008 R2 Database 2nd Normal Form Create separate tables for sets of values that apply to multiple records. Formal database terminology is precise but can be hard to follow when first encountered. and not on the candidate key. and provided to you by QuickStart Intelligence. It is illegal to reprint. and SalesDate. SalesAmount. The ProductName column only depends on the ProductID column. In the next demonstration. Imagine a Sales table with columns OrderNumber. This table would not be in 3rd Normal Form. guarantees or conditions. ProductName.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. The Sales table should be separated from a Product table and likely linked to it by ProductID. ProductID. A candidate key for the table might be the OrderNumber column. These values should be stored separately. Relate these tables with a foreign key. The Licensed Content is licensed "as-is. A common error with 2nd Normal Form would be to hold the details of products that a supplier provides in the same table as the details of the supplier's credit history. redistribute. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Open the 11 – Demonstration 1A. navigate to D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ. click SQL Server Management Studio. or resell this content. The Licensed Content is licensed "as-is.sql script file from within Solution Explorer.sql script file. type Proseware in the Server name text box and click Connect. redistribute. 3.ssmssln and click Open. Open and execute the 00 – Setup. click Microsoft SQL Server 2008 R2. Please report any unauthorized use of this content to piracy@microsoft. In the virtual machine. guarantees or conditions. click All Programs. It is illegal to reprint. . and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Designing and Implementing Tables 3-9 Demonstration 1A: Normalization Key Points In this demonstration you will see common normalization errors Demonstration Steps 1. In the Connect to Server window. 5. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. From the File menu. click Open. click Project/Solution. 2. 4. click Start. Follow the instructions contained within the comments of the script file.com or by calling +1 800-785-3448.

. guarantees or conditions. Natural vs. The use of surrogate keys is another topic that can lead to strong debate between database professionals. Natural keys are formed from data within the table. In formal database terminology. no candidate key is more important than any other candidate key. or resell this content. Primary Key A primary key must be unique and cannot be NULL. The surrogate key would not be related to the other attributes of a customer. globally unique identifier (GUID).QuickStart Intelligence 3-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Primary Keys Key Points A primary key is a form of constraint applied to a table. keys used as primary keys should not change over time. Primary keys are a form of constraint. When tables are correctly normalized though. and provided to you by QuickStart Intelligence. It is illegal to reprint. along with the employee's name and personal details. (Constraints are discussed later in this course). Please report any unauthorized use of this content to piracy@microsoft. Surrogate Keys A surrogate key is another form of key that is used as a unique identifier within a table but one which is not derived from "real" data. A primary key is chosen from any potential candidate keys. In this case. they will usually have only a single candidate key that could be used as a primary key. this is not always the case. a Customer table may have a CustomerID or a CustomerCode column containing numeric." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Consider a table that holds an EmployeeID and a NationalIDNumber. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. The Licensed Content is licensed "as-is. However.com or by calling +1 800-785-3448. the EmployeeID column would be the primary key. It may be necessary to combine multiple columns into a key before it can be used to uniquely identify a row. The EmployeeID and the NationalIDNumber are likely to both be possible candidate keys. For example. or alphanumeric codes. Ideally. A candidate key is used to identify a column or set of columns that can be used to uniquely identify a row.

com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Designing and Implementing Tables 3-11 Question: What is an advantage of using a natural key? Question: What is a disadvantage of using a natural key? Question: What might be an appropriate primary key for the Owner table mentioned in the previous demonstration? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . redistribute. and provided to you by QuickStart Intelligence. guarantees or conditions. or resell this content.

For example. the reference is only checked if the column holding the foreign key value is not NULL. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Self-Referencing Tables A table can hold a foreign key reference to itself. It is illegal to reprint.com or by calling +1 800-785-3448. Tables might also include multiple foreign key references. An employee's manager is also an employee. A foreign key reference can be made from the ManagerID column of the Employees table to the EmployeeID column in the same table. you cannot change the ID for a customer when there are orders in a CustomerOrders table that reference that customer's ID. Reference Checking Referenced keys cannot be updated or deleted unless options that cascade the changes to related tables are used. A foreign key reference is used to ensure that any CustomerID entered into the CustomerOrders table does in fact exist in the Customers table. Please report any unauthorized use of this content to piracy@microsoft. a CustomerOrders table might include a CustomerID column. For example. For example. Foreign Keys It is a requirement to hold the details of the primary key (or another unique key) from one table as a column in another table. at the time you define the foreign key constraint. For example. . or resell this content.QuickStart Intelligence 3-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Foreign Keys Key Points A Foreign Key is used to establish references or relationships between tables." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. you can specify that changes to the referenced value are permitted and will cascade. In SQL Server. The Licensed Content is licensed "as-is. guarantees or conditions. and provided to you by QuickStart Intelligence. However. an Orders table might refer to a Customers table and a Products table. This means that the ID for the customer would be changed in both the Customers table and in the CustomerOrders table. an Employees table might contain a ManagerID column.

It is illegal to reprint. . redistribute. or resell this content. Foreign keys are a form of constraint and will be covered in more detail in a later module. Question: What would be an example of multiple foreign keys in a table referencing the same table? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Designing and Implementing Tables 3-13 Terminology Foreign keys are referred to as being used to "enforce referential integrity"." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. guarantees or conditions. The ANSI SQL 2003 definition refers to self-referencing tables as having "recursive foreign keys".

Users also often took dependencies on the format of these system tables. The Licensed Content is licensed "as-is. In SQL Server 2005. a new sysxlogins table was added instead of changing the existing table. you might be expecting databases to contain a large number of system tables. Worse. guarantees or conditions. . while it is acceptable to query these tables. System Tables in the msdb Database msdb is the database used by SQL Server Agent. Again.com or by calling +1 800-785-3448. Users often modified these system tables (sometimes by accident) and this caused issues when applying service packs and updates." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. That made it difficult for new versions of SQL Server to have improved designs for these tables while avoiding the chance of breaking existing applications. They should not be directly modified. As an example. it could have led to unexpected behavior or failures if the data was not changed correctly. It is illegal to reprint. no dependency on its format should be taken when designing applications. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. A large number of system tables are still present in the msdb database. These views are permission-based and would display data to a user only if the user has appropriate permission to view the data. Please report any unauthorized use of this content to piracy@microsoft. they should not be directly modified. redistribute. Unless the table is documented. or resell this content.QuickStart Intelligence 3-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Working with System Tables Key Points System Tables are the tables that are provided directly by the SQL Server database engine. these tables were hidden and replaced by a set of system views that show the contents of the system tables. when the syslogins table needed to be expanded. System Tables in Earlier Versions If you have worked with SQL Server 2000 and earlier versions. primarily for organizing scheduled background tasks that are known as "jobs".

Since that version. and stored procedures. Objectives After completing this lesson. guarantees or conditions. redistribute. views.QuickStart Intelligence Designing and Implementing Tables 3-15 Lesson 2 Working with Schemas SQL Server 2005 introduced a change to how schemas are used. or resell this content. you will be able to: • Describe the role of a Schema • Describe the role of Object Name Resolution • Create Schemas This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. Doing this can greatly simplify the design of system security requirements. schemas are used as containers for objects such as tables. Security permissions can also be assigned at the schema level rather than individually on the objects contained within the schemas. Schemas can be particularly helpful in providing a level of organization and structure when large numbers of objects are present in a database. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.

etc. Schemas form a part of the multi-part naming convention for objects. . The user could then execute all stored procedures within the schema. it is important to understand that the naming convention changed when schemas were introduced. schemas can be used to contain objects such as tables." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In SQL Server. and provided to you by QuickStart Intelligence. Previously. Please report any unauthorized use of this content to piracy@microsoft. somewhat like a folder is used to hold files at the operating system level. views. types. SQL Server will This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Since their introduction in SQL Server 2005.Schema. The Licensed Content is licensed "as-is.QuickStart Intelligence 3-16 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a Schema? Key Points Schemas are used to contain objects and to provide a security boundary for the assignment of permissions.com or by calling +1 800-785-3448. stored procedures. This simplifies the granting of permissions as there is no need to set up individual permissions on each stored procedure.Object Objects still have owners but the owner's name does not form a part of the multi-part naming convention from SQL Server 2005 onwards. guarantees or conditions. an object is formerly referred to by a name of the form: Server. names were of the form: Server. schemas are essentially used as containers for objects.Owner. An example of applying permissions at the schema level would be to assign the EXECUTE permission on a schema to a user. It is illegal to reprint.Database.Database. When upgrading databases from earlier versions. redistribute. Schemas In SQL Server. functions.Object Security Boundary Schemas can be used to simplify the assignment of permissions. Upgrading Older Applications If you are upgrading applications from SQL Server 2000 and earlier versions. or resell this content.

com or by calling +1 800-785-3448. redistribute. It is illegal to reprint. or resell this content. . so that applications that use multi-part names will continue to work. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.QuickStart Intelligence Designing and Implementing Tables 3-17 automatically create a schema with the same name as existing object owners. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.

. such as in this modified version of the previous statement: SELECT ProductID. More than one Product table could exist in separate schemas. When single part names are used. and views. Most users have default schemas assigned but not all users have these. guarantees or conditions. Apart from rare situations. If the object is not found.com or by calling +1 800-785-3448. For example." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. using multi-part names leads to more reliable code that does not depend upon default schema settings. Please report any unauthorized use of this content to piracy@microsoft. SQL Server will first check the user's default schema. consider the following statement: SELECT ProductID. Users without default schemas are considered to have the dbo schema as their default schema. Name. functions. The Licensed Content is licensed "as-is. SQL Server must determine which underlying objects are being referred to. Object Name Resolution When object names are referred to in the code. Name. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Size FROM Production.QuickStart Intelligence 3-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Object Name Resolution Key Points It is important to use at least two-part names when referring to objects in SQL Server code such as stored procedures. SQL Server must then determine which Product table is being referred to.Product. It is illegal to reprint. Default schemas are not assigned to Windows groups or to users based on certificates but they do apply to users created from standard Windows and SQL Server logins. It is important to include schema names when referring to objects instead of depending upon schema name resolution. and provided to you by QuickStart Intelligence. SQL Server will then check the dbo schema to try to locate the object. When locating an object. Size FROM Product.

the Article table is being created and the SELECT permission on the schema is being granted to Salespeople. a schema named Reporting is being created. . The Licensed Content is licensed "as-is. CREATE SCHEMA Schemas have both names and owners. the CREATE SCHEMA statement can include options for object creation. While both schemas and the objects contained in the schemas have owners and the owners do not have to be the same. redistribute. guarantees or conditions. Object Creation at Schema Creation Time Besides creating schemas. Both CREATE TABLE and GRANT are options that are being applied to the CREATE SCHEMA statement. Statements such as the second CREATE SCHEMA example on the slide can lead to issues if the entire statement is not executed together." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. it is in fact a single statement. and GRANT). Question: What would be different about the outcome of the 2nd statement if the CREATE SCHEMA and the CREATE TABLE parts of the statement were executed separately? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. In the first example shown in the slide. This command can also include the definition of objects to be created within the schema at the time the schema is created. having different owners for schemas and the objects contained within them can lead to complex security issues. and provided to you by QuickStart Intelligence. It is owned by the user Terry. CREATE TABLE. While the second example in the slide might appear to be three statements (CREATE SCHEMA. or resell this content. Within the newly created KnowledgeBase schema.QuickStart Intelligence Designing and Implementing Tables 3-19 Creating Schemas Key Points Schemas are created with the CREATE SCHEMA command. Please report any unauthorized use of this content to piracy@microsoft.

click Microsoft SQL Server 2008 R2. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. Open the 21 – Demonstration 2A.com or by calling +1 800-785-3448.sql script file from within Solution Explorer. 2. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.ssmssln and click Open. navigate to D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ. click SQL Server Management Studio. or resell this content. From the File menu. It is illegal to reprint.QuickStart Intelligence 3-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: Schemas Key Points In this demonstration you will see how to: • Create a schema • Create a schema with an included object • Drop a schema Demonstration Steps 1. click Project/Solution. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In the Connect to Server window. . 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. click Start. • Open and execute the 00 – Setup. and provided to you by QuickStart Intelligence. • In the virtual machine. 3. redistribute. click All Programs.sql script file. Follow the instructions contained within the comments of the script file. click Open.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. either from expressions involving other columns from the table or from the execution of functions. modifying. . Temporary tables are a special form of tables that can be used to hold temporary result sets. you will be able to: • Create Tables • Drop Tables • Alter Tables • Use Temporary Tables • Work with Computed Columns This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. It is illegal to reprint. and provided to you by QuickStart Intelligence. guarantees or conditions.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.QuickStart Intelligence Designing and Implementing Tables 3-21 Lesson 3 Creating and Altering Tables Now that you understand the core concepts surrounding the design of tables. this lesson introduces you to the T-SQL syntax used when defining. Computed columns are used to create columns where the value held in the column is automatically calculated. or resell this content. or dropping tables. Objectives After completing this lesson. Please report any unauthorized use of this content to piracy@microsoft.

redistribute. or after the list of columns. . The Licensed Content is licensed "as-is. make sure that you supply both a schema name and a table name. guarantees or conditions. the table will be created in the default schema of the user executing the statement.com or by calling +1 800-785-3448.SalesReceipt ( SalesRegisterID int NOT NULL. and provided to you by QuickStart Intelligence. SQL Server has defaults for this and they can be changed via the ANSI_NULL_DEFAULT setting.QuickStart Intelligence 3-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Creating Tables Key Points Tables are created with the CREATE TABLE statement. CREATE TABLE When creating tables with the CREATE TABLE statement. It is illegal to reprint. CustomerID int NOT NULL. Scripts should always be designed to be as reliable as possible and specifying nullability in DDL scripts helps improve script reliability. Please report any unauthorized use of this content to piracy@microsoft. It must be included after the list of columns when more than one column is included in the key as shown in the following example where the SalesID is only unique for each SalesRegisterID: CREATE TABLE PetStore. PRIMARY KEY (SalesRegisterID. Primary Key A primary key constraint can be specified beside the name of a column if only a single column is included in the key. SalesAmount decimal(18." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SalesID int NOT NULL. or resell this content. This could lead to the creation of scripts that are not robust in that they could generate different schema designs when executed by different users. Nullability You should specify NULL or NOT NULL for each column in the table. This statement is also used to define the columns associated with the table and identify constraints such as primary and secondary keys. SalesID) This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. If the schema name is not specified.2) NOT NULL.

guarantees or conditions.QuickStart Intelligence Designing and Implementing Tables 3-23 ). It is illegal to reprint. or resell this content.com or by calling +1 800-785-3448. could the OwnerName column have been used as the primary key instead of a surrogate key? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Primary keys are constraints and are more fully described along with other constraints in a later module. Question: In the example shown. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. redistribute.

indexes. . Please report any unauthorized use of this content to piracy@microsoft. This can lead to "orphaned" code that refers to non-existent objects. all permissions. Referenced and referencing entities are also available separately from the sys. or resell this content. functions. If a table is referenced by a foreign key constraint. The Licensed Content is licensed "as-is.dm_sql_referenced_entities and sys. SQL Server 2008 introduced a set of dependency views that can be used to locate code that references non-existent objects. Question: Why would a reference to a table stop it from being dropped? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.sql_expression_dependencies view. redistribute. and triggers that are related to the table are also dropped.com or by calling +1 800-785-3448. Code that references the table (such as code contained within stored procedures. DROP TABLE When dropping a table." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. it cannot be dropped. constraints. It is illegal to reprint. guarantees or conditions. and provided to you by QuickStart Intelligence.dm_sql_referencing_entities dynamic management views. The details of both referenced and referencing entities are available from the sys.QuickStart Intelligence 3-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Dropping Tables Key Points The DROP TABLE statement is used to drop tables from a database. (Views are discussed later in the course). and views) is not dropped.

it can be altered. ALTER TABLE Tables are modified using the ALTER TABLE statement. If you drop and recreate the table. In fact.QuickStart Intelligence Designing and Implementing Tables 3-25 Altering Tables Key Points Altering a table is useful as permissions on the table are retained along with the data in the table.Owner table. This statement can be used to add or drop columns and constraints or to enable or disable constraints and triggers." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the PreferredName column is being dropped from the PetStore. If the word COLUMN is omitted in a DROP.Owner table. Note the difference in syntax regarding the word COLUMN. Please report any unauthorized use of this content to piracy@microsoft. However. The Licensed Content is licensed "as-is. redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. The word COLUMN is required for DROP but not for ADD. If the table is referenced by a foreign key. Note that the syntax for adding and dropping columns is inconsistent. it cannot be dropped. Later. (Constraints and triggers are discussed in later modules). SQL Server assumes that it is a constraint being dropped. and provided to you by QuickStart Intelligence. In the slide example. the PreferredName column is being added to the PetStore. . it is not an optional keyword for ADD either.com or by calling +1 800-785-3448. or resell this content. both the permissions on the table and the data in the table are lost. guarantees or conditions.

or resell this content. and provided to you by QuickStart Intelligence. 2. The Licensed Content is licensed "as-is.sql script file from within Solution Explorer. click Project/Solution. click All Programs. From the File menu. Follow the instructions contained within the comments of the script file.ssmssln and click Open.QuickStart Intelligence 3-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Working with Tables Key Points In this demonstration you will see how to: • Create tables • Alter tables • Drop tables Demonstration Steps 1.com or by calling +1 800-785-3448. Question: Why should you ensure that you specify the nullability of a column when designing a table? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. type Proseware in the Server name text box and click Connect. click Start. navigate to D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click SQL Server Management Studio. Open the 31 – Demonstration 3A. . redistribute. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. 3. • Open and execute the 00 – Setup." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. In the Connect to Server window. click Microsoft SQL Server 2008 R2. • In the virtual machine. click Open.sql script file.

It is illegal to reprint. A global temporary table is created if the name has a double-pound (##) prefix.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. While temporary tables will be deleted when they go out of scope. SQL Server 2008 introduced table-valued parameters (TVPs) that can provide an alternate mechanism for passing tables to stored procedures or functions. guarantees or conditions. Temporary tables are often created in code using the SELECT INTO statement. Global temporary tables are visible to all users and are not commonly used. A table is created as a temporary table if its name has a pound (#) prefix. except that they are only visible to the creator and in the same scope (and sub-scopes) within the session. or resell this content. it is not considered a good practice in general. a temporary table created in a stored procedure is visible to other stored procedures executed from within the first procedure. While this use is possible. . redistribute. They are automatically deleted when a session ends or when they go out of scope. The Licensed Content is licensed "as-is. they should be explicitly deleted when no longer required. Passing Temporary Tables Temporary tables are also often used to pass rowsets between stored procedures.QuickStart Intelligence Designing and Implementing Tables 3-27 Temporary Tables Key Points Temporary tables are used to hold temporary result sets within a user's session. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. Temporary Tables Temporary tables are very similar to other tables. completes or aborts. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. They are deleted automatically when they go out of scope. This typically occurs when the code that they were created within. (TVPs are discussed later in this course). This breaks common rules of abstraction for coding and also makes it more difficult to debug or troubleshoot the nested procedures. For example.

and provided to you by QuickStart Intelligence. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. often due to a lack of set-based logic design. The Licensed Content is licensed "as-is. It is illegal to reprint. Extensive use of temporary tables is often an indicator of poor coding techniques. redistribute. . guarantees or conditions.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 3-28 Implementing a Microsoft® SQL Server® 2008 R2 Database The overuse of temporary tables is a common T-SQL coding error that often leads to performance and resource issues.

Follow the instructions contained within the comments of the script file. guarantees or conditions. redistribute. 2. Please report any unauthorized use of this content to piracy@microsoft. click Project/Solution. It is illegal to reprint. From the File menu. click Open.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. click All Programs. navigate to D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ. click Microsoft SQL Server 2008 R2. 3. The Licensed Content is licensed "as-is. or resell this content. • In the virtual machine. In the Connect to Server window.sql script file from within Solution Explorer. click SQL Server Management Studio. • Open and execute the 00 – Setup. 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 32 – Demonstration 3B." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.sql script file. type Proseware in the Server name text box and click Connect.QuickStart Intelligence Designing and Implementing Tables 3-29 Demonstration 3B: Temporary Tables Key Points In this demonstration you will see how to: • Work with temporary tables Demonstration Steps 1. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. .ssmssln and click Open.

QuickStart Intelligence

3-30

Implementing a Microsoft® SQL Server® 2008 R2 Database

Computed Columns

Key Points
Computed columns are columns that are derived from other columns or from the result of executing
functions.

Computed Columns
Computed columns were introduced in SQL Server 2000. In the example shown in the slide, the
YearOfBirth column is calculated by executing the DATEPART function to extract the year from the
DateOfBirth column in the same table.
In the example shown, you can also see the word PERSISTED added to the definition of the computed
column. Persisted computed columns were introduced in SQL Server 2005.
A non-persisted computed column is calculated every time a SELECT operation occurs on the column. A
persisted computed column is calculated when the data in the row is inserted or updated. The data in the
column is then selected like the data in any other column.
The core difference between persisted and non-persisted computed columns relates to when the
computational performance impact is exerted. Non-persisted computed columns work best for data that
is modified regularly but selected rarely. Persisted computed columns work best for data that is modified
rarely but selected regularly. In most business systems, data is read much more regularly than it is
updated. For this reason, most computed columns would perform best as persisted computed columns.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Designing and Implementing Tables

3-31

Demonstration 3C: Computed Columns

Key Points
In this demonstration you will see how to work with computed columns.

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, 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_03_PRJ\6232B_03_PRJ.ssmssln and click
Open.

Open and execute the 00 – Setup.sql script file from within Solution Explorer.

2.

Open the 33 – Demonstration 3C.sql script file.

3.

Follow the instructions contained within the comments of the script file.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-32

Implementing a Microsoft® SQL Server® 2008 R2 Database

Lab 3: Designing and Implementing Tables

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.

On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager.

2.

Maximize the Hyper-V Manager window.

3.

In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

4.

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.

5.

In Virtual Machine Connection window, click on the Revert toolbar icon.

6.

If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to
complete.

7.

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.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Designing and Implementing Tables

Click Switch User, and then click Other User.

Log on using the following credentials:
i.
ii.

3-33

User name: AdventureWorks\Administrator
Password: Pa$$w0rd

8.

From the View menu, in the Virtual Machine Connection window, click Full Screen Mode.

9.

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.
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_03_PRJ\6232B_03_PRJ.ssmssln.
15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click
Execute on the toolbar.

Lab Scenario
A business analyst from your organization has provided you with a first-pass at a schema design for some
new tables being added to the MarketDev database. You need to provide an improved schema design
based on good design practices and an appropriate level of normalization. The business analyst was also
confused about when data should be nullable. You need to decide about nullability for each column in
your improved design.
The new tables need to be isolated in their own schema. You need to create the required schema
DirectMarketing. The owner of the schema should be dbo.
When the schema has been created, if you have available time, you need to create the tables that have
been designed.

Supporting Documentation
Proposed Schema
Table1: Competitor
Name

Data Type

CompetitorCode

nvarchar(6)

Name

varchar(30)

Address

varchar(max)

Date_Entered

varchar(10)

Strength_of_competition

varchar(8)

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-34

Implementing a Microsoft® SQL Server® 2008 R2 Database

Name

Data Type

Comments

varchar(max)

Table2: TVAdvertisement
Name

Data Type

TV_Station

nvarchar(15)

City

nvarchar(25)

CostPerAdvertisement

float

TotalCostOfAllAdvertisements

float

NumberOfAdvertisements

varchar(4)

Date_Of_Advertisement_1

varchar(12)

Time_Of_Advertisement_1

int

Date_Of_Advertisement_2

varchar(12)

Time_Of_Advertisement_2

int

Date_Of_Advertisement_3

varchar(12)

Time_Of_Advertisement_3

int

Date_Of_Advertisement_4

varchar(12)

Time_Of_Advertisement_4

int

Date_Of_Advertisement_5

varchar(12)

Time_Of_Advertisement_5

int

Table3: Campaign_Response
Name

Data Type

ResponseOccurredWhen

datetime

RelevantProspect

int

RespondedHow

varchar(8) (phone, email, fax, letter)

ChargeFromReferrer

float

RevenueFromResponse

float

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Designing and Implementing Tables

Name

Data Type

ResponseProfit

float (revenue less charge)

3-35

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-36

Implementing a Microsoft® SQL Server® 2008 R2 Database

Exercise 1: Improve the Design of Tables
Scenario
A business analyst from your organization has provided you with a first-pass at a schema design for some
new tables being added to the MarketDev database. You need to provide an improved schema design
based on good design practices and an appropriate level of normalization. The business analyst was also
confused about when data should be nullable. You need to decide about nullability for each column in
your improved design.
The main tasks for this exercise are as follows:
1.
2.

Review the supplied design
Suggest an improved design

 Task 1: Review the supplied design

Review the supplied design in the supporting documentation for the exercise

 Task 2: Suggest an improved design

Provide recommendations on how to improve the schema design
Results: After this exercise, you have provided an improved schema design based on good design
practices.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Designing and Implementing Tables

3-37

Exercise 2: Create a Schema
Scenario
The new tables need to be isolated in their own schema. You need to create the required schema
DirectMarketing. The owner of the schema should be dbo.
The main tasks for this exercise are as follows:
1.
2.

Connect to the MarketDev Database
Create a schema named DirectMarketing

 Task 1: Connect to the MarketDev Database

Connect to the MarketDev Database

 Task 2: Create a schema named DirectMarketing

Create a schema named DirectMarketing with dbo as the owner
Results: After this exercise, you should have created a new Direct Marketing schema.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-38

Implementing a Microsoft® SQL Server® 2008 R2 Database

Challenge Exercise 3: Create the Tables (Only if time permits)
Scenario
You need to create the tables that have been designed.
The main tasks for this exercise are as follows:

1.

Create the tables that you designed in Exercise 1.

 Task 1: Create the tables

Create the tables that were designed in Exercise 1. Take into consideration the nullability of each
column and each table should have a primary key. At this point there is no need to create CHECK or
FOREIGN KEY constraints.
Results: After this exercise, you should have created the tables that were designed in Exercise 1.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

2.QuickStart Intelligence Designing and Implementing Tables 3-39 Module Review and Takeaways Review Questions 1. Often developers will suggest that the application will ensure referential integrity. Bugs are also easy to miss when they first start to occur. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. What is a foreign key? 3. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. redistribute. What is a primary key? 2. What is meant by the term "referential integrity"? Best Practices 1. . and provided to you by QuickStart Intelligence. guarantees or conditions. All tables should have primary keys. It is illegal to reprint. Experience shows that this is a poor option. Databases are often accessed by multiple applications." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Foreign keys should be declared within the database in almost all circumstances.

QuickStart Intelligence 3-40 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. or resell this content. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.com or by calling +1 800-785-3448. It is illegal to reprint. .

. The Licensed Content is licensed "as-is. redistribute. It is illegal to reprint.com or by calling +1 800-785-3448. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. and provided to you by QuickStart Intelligence.QuickStart Intelligence Designing and Implementing Views 4-1 Module 4 Designing and Implementing Views Contents: Lesson 1: Introduction to Views 4-3 Lesson 2: Creating and Managing Views 4-13 Lesson 3: Performance Considerations for Views 4-22 Lab 4: Designing and Implementing Views 4-27 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

Views can also provide a layer of security. redistribute. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. The Licensed Content is licensed "as-is. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Objectives After completing this lesson. Views can simplify the design of database applications by abstracting the complexity of the underlying objects. It is illegal to reprint. Users can be given permission to access a view without permission to access the objects that the view is constructed on.QuickStart Intelligence 4-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Views are a type of virtual table because the result set of a view is not usually saved in the database. . you will be able to: • Explain the role of views in database development • Implement views • Describe the performance related impacts of views This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence.

In this module you will learn about views. the different types of views.QuickStart Intelligence Designing and Implementing Views 4-3 Lesson 1 Introduction to Views In this lesson. or resell this content.com or by calling +1 800-785-3448. you will gain an understanding of views and how they are used. you will be able to: • Describe views • Describe the different types of view provided by SQL Server • Explain the advantages offered by views • Work with system views • Work with dynamic management views This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. Unlike ordinary tables (base tables) in a relational database. It is illegal to reprint. . virtual table computed or collated from data in the database. guarantees or conditions. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. and how to use them. redistribute. You will also investigate the system views that are supplied by the SQL Server engine. A view is effectively a named SELECT query. a view is not part of the physical schema — it is a dynamic." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Effective use of views in database system design helps improve performance and manageability. Objectives After completing this lesson.

What is stored in the database is the SELECT statement. . why did you use them? Views The data accessible through a view is not stored in the database as a distinct object." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. To an application. views can reference other views. and provided to you by QuickStart Intelligence. (Indexed views are described later in this module). For example. An EmployeeLookup view could be provided to return only the columns that general users are permitted to view. or resell this content. except in the case of indexed views. a Sales table might hold details of the sales for the entire organization. For example. Horiztonal filtering is used to limit the rows returned by the view. guarantees or conditions. horizontally or in both ways. a view behaves very similarly to a table. The Licensed Content is licensed "as-is. many of the columns in the Employee table might be private and should not be returned to all users. Please report any unauthorized use of this content to piracy@microsoft. consider a drop-down list of employee names that is displayed in the user interface of an application. The data tables referenced by the SELECT statement are known as the base tables for the view. Vertical filtering is used to limit the columns returned by the view. While this data could be retrieved from the Employee table. It is illegal to reprint.com or by calling +1 800-785-3448.QuickStart Intelligence 4-4 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a View? Key Points A view can be thought of as a named virtual table that is defined through a SELECT statement. Question: Have you ever used views in designing Microsoft® SQL Server® database systems? If so. As well as being based on tables. Queries against views are written the same way that queries are written against tables. Filtering Via Views Views can filter the base tables vertically. redistribute. Sales staff might only be permitted to view sales for their This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

Please report any unauthorized use of this content to piracy@microsoft. A view could be created that limits the rows returned to those for a particular state or region." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.QuickStart Intelligence Designing and Implementing Views 4-5 own region or state. .com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. Question: Why would you limit which columns are returned by a view? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. The Licensed Content is licensed "as-is. or resell this content. It is illegal to reprint.

or resell this content. if the view is not indexed. From the base tables (or views). . guarantees or conditions. Dynamic Management Views (DMVs) were introduced in SQL Server 2005 and enhanced in every edition since. system views (including dynamic management views). DMVs provide dynamic information about the state of SQL Server such as information about the current sessions or the queries those sessions are executing. Indexed Views Indexed views materialize the view through the creation of a clustered index on the view." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Standard Views Standard views combine data from one or more base tables (or views) into a new virtual table. It is illegal to reprint. redistribute. Indexed views are discussed in Module 6. System Views System views are provided with SQL Server and show details of the system catalog or aspects of the state of SQL Server. Partitioned Views This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. such as joins or aggregations. indexed views and partitioned views (including distributed partitioned views). Complex joins or lengthy aggregations can be avoided at execution time by pre-calculating the results.QuickStart Intelligence 4-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of Views Key Points There are four basic types of view: standard views. are done during query execution for each query referencing the view. Any computations. Please report any unauthorized use of this content to piracy@microsoft. particular columns and rows can be returned. and provided to you by QuickStart Intelligence. This is usually done to improve query performance.

Question: What advantages would you assume that views would provide? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Designing and Implementing Views 4-7 Partitioned views form a union of data from multiple tables into a single view. . Please report any unauthorized use of this content to piracy@microsoft. are located on separate instances of SQL Server. Distributed partitioned views are formed when the tables that are being combined by a union operation. redistribute.com or by calling +1 800-785-3448. or resell this content. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. Note: Indexed views and Partitioned views are described later in this module.

Question: If tables can be replaced by views (and vice-versa) during maintenance. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Many external applications are unable to execute stored procedures or T-SQL code but can select data from tables or views. For example. Views can be used as security mechanisms by allowing users to access data through the view. Creating a view allows isolating the data that is needed for these export functions. Advantages of Views Views can provide a layer of abstraction in database development. in a much simpler format. It is illegal to reprint. Views can be used to provide a backward compatible interface to emulate a table that previously existed but whose schema has changed. Rather than embedding this logic in the reporting application. and customize the perception each user has of the database. Please report any unauthorized use of this content to piracy@microsoft. .com or by calling +1 800-785-3448. without granting the users permissions to directly access the underlying base tables of the view. Users do not need to deal with the complex queries that might be involved within the view. Reporting applications often need to execute complex queries to retrieve the report data. or that they are permitted to work with. and provided to you by QuickStart Intelligence. guarantees or conditions. if an Customer table has been split into two tables: CustomerGeneral and CustomerCredit. a Customer view could be created over the two new tables to allow existing applications to query the data without requiring the applications to be altered.QuickStart Intelligence 4-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Advantages of Views Key Points Views are generally used to focus. They are able to query the view as they would query a table. what does that suggest to you about the naming of views and tables? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. simplify. The Licensed Content is licensed "as-is. They can allow a user to focus on a subset of data that is relevant to them. a view could be created to supply the data required by the reporting application.

While it would be possible to retrieve much of this information directly from system tables. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Designing and Implementing Views 4-9 Working with System Views Key Points SQL Server provides information about its configuration via a series of system views.TABLES INFORMATION_SCHEMA. however. The Licensed Content is licensed "as-is. the use of catalog views is the supported mechanism for doing this. These views. are deprecated and should not be used for new development work. guarantees or conditions. System Views Catalog views are primarily used to retrieve metadata about tables and other objects in databases.ROUTINES INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS INFORMATION_SCHEMA.TABLE_PRIVILEGES INFORMATION_SCHEMA. a standard mechanism was designed. It is illegal to reprint.CHECK_CONSTRAINTS INFORMATION_SCHEMA. or resell this content. For backwards compatibility.VIEW_COLUMN_USAGE This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The most commonly used INFORMATION_SCHEMA views are shown in the following table: Common INFORMATION_SCHEMA Views INFORMATION_SCHEMA. As each database engine vendor uses different methods of storing and accessing metadata.ROUTINE_COLUMNS INFORMATION_SCHEMA. This interface is provided by the views in the INFORMATION_SCHEMA schema. Earlier versions of SQL Server provided a set of virtual tables that were exposed as system views.TABLE_CONSTRAINTS INFORMATION_SCHEMA. . redistribute. These views also provide metadata describing both the objects you create in the database and those provided by SQL Server.COLUMNS INFORMATION_SCHEMA. The International Standards Organization (ISO) has standards for the SQL language.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a set of "compatibility" views have been provided.PARAMETERS INFORMATION_SCHEMA.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. .VIEW_TABLE_USAGE INFORMATION_SCHEMA." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 4-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Common INFORMATION_SCHEMA Views INFORMATION_SCHEMA.VIEWS Question: Give an example of why you would want to interrogate a catalog view. redistribute. It is illegal to reprint. guarantees or conditions. and provided to you by QuickStart Intelligence.

The difference between the DMVs and the DMFs is that DMFs have parameters passed to them. These views provide a relational method for querying the internal state of a SQL Server instance. or resell this content. guarantees or conditions.dm_*. Similarly. It is illegal to reprint. . redistribute. Each of the objects is used to return internal state information from SQL Server. Please report any unauthorized use of this content to piracy@microsoft. You can see the list of current DMVs by looking down the list of System Views within Object Explorer in SQL Server Management Studio." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you can see the list of current DMFs by looking down the list of System Functions within Object Explorer. DOMs are prefixed by sys. DMOs can be used to view and monitor the internal health and performance of a server along with aspects of its configuration. The Licensed Content is licensed "as-is. Many of the objects provide very detailed information about the internal operation of SQL Server.QuickStart Intelligence Designing and Implementing Views 4-11 Dynamic Management Views Key Points Dynamic Management Views are commonly just called DMVs. and provided to you by QuickStart Intelligence. Question: What sort of information about how SQL Server is performing and its health would it be useful to have easy access to? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. They also have an important role in assisting with troubleshooting problems (such as blocking issues) and with performance tuning. These objects include Dynamic Management Views (DMVs) and Dynamic Management Functions (DMFs). Dynamic Management Views SQL Server 2005 introduced the concept of Dynamic Management Objects (DMOs).com or by calling +1 800-785-3448.

In the Connect to Server window.sql script file from within Solution Explorer. 3.QuickStart Intelligence 4-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: System and Dynamic Management Views Key Points In this demonstration you will see how to: • Query system views • Query dynamic management views Demonstration Steps 1. navigate to D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ. or resell this content. 4. click Start. In the virtual machine. type Proseware and click Connect. redistribute. Open and execute the 00 – Setup. 2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click SQL Server Management Studio. click All Programs. Question: When are the values returned by most dynamic management views reset? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Open the 11 – Demonstration 1A. click Project/Solution. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. click Microsoft SQL Server 2008 R2. Follow the instructions contained within the comments of the script file. 5. . It is illegal to reprint.sql script file. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. From the File menu.ssmssln and click Open.com or by calling +1 800-785-3448. click Open." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

you will be able to: • Create views • Drop views • Alter views • Explain the concept of ownership chaining and how it applies to views • List the available sources of information about views • Work with updatable views • Obfuscate view definitions This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. or resell this content. In this lesson you will learn how to create. You will see how to find information about existing views and how to obfuscate the definitions of views.com or by calling +1 800-785-3448. You will also learn how views and the objects that they are based on have owners and how this can impact the use of views. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Designing and Implementing Views 4-13 Lesson 2 Creating and Managing Views In the previous lesson. and provided to you by QuickStart Intelligence. drop and alter views. . guarantees or conditions. you learned about the role of views. It is illegal to reprint. Objectives After completing this lesson. Please report any unauthorized use of this content to piracy@microsoft.

You can see this in the following code example: CREATE VIEW HumanResources. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. GivenName) AS SELECT EmployeeID. Views have no natural output order. If you later decide to index the view. Question: Why is the ORDER BY clause ever permitted in a view definition if it doesn’t impact the output order of the rows? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is also common to define column aliases in the SELECT statement within the view definition but a column list can also be provided after the name of the view. the underlying tables cannot be changed in a way that would affect the view definition. CREATE VIEW If you specify the option WITH SCHEMABINDING. Please report any unauthorized use of this content to piracy@microsoft. Expressions that are returned as columns need to be aliased. LastName. It is illegal to reprint. Creating a view involves associating a name with a SELECT statement.Employee. redistribute.QuickStart Intelligence 4-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Creating Views Key Points To create a view you must be granted permission to do so by the database owner. and provided to you by QuickStart Intelligence. or resell this content. the WITH SCHEMABINDING option must be used. guarantees or conditions. Care should be exercised in nesting views deeply as it can become difficult to understand the complexity of the underlying code and it can be difficult to troubleshoot performance problems related to the views. . FirstName FROM HumanResources. The ORDER BY clause can be used in a view but only to satisfy the needs of a clause such as the TOP clause. FamilyName.com or by calling +1 800-785-3448. Queries that access the views should specify the order for the returned rows. Views can be based on other views (instead of base tables) up to 32 levels of nesting.EmployeeList (EmployeeID.

CTSales. It is illegal to reprint. If a view was created with the SCHEMABINDING option. The DROP VIEW statement supports the dropping of multiple views via a comma-delimited list as shown in the following code sample: DROP VIEW Sales.CASales. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. DROP VIEW Even if a view is recreated with exactly the same name as a view that has been dropped. . Sales. It is important to record why views are created and to then drop them if they are no longer required for the purpose they were created.QuickStart Intelligence Designing and Implementing Views 4-15 Dropping Views Key Points Dropping a view removes the definition of the view and all permissions associated with the view. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. it will need to be removed before changes can be made to the structure of the underlying tables." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Retaining view definitions that are not in use adds to the work required when reorganizing the structure of databases.WASales. Sales.com or by calling +1 800-785-3448. redistribute. permissions formerly associated with the view are removed.

guarantees or conditions.QuickStart Intelligence 4-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Altering Views Key Points After a view is defined. or resell this content. (This includes indexed views that are discussed in the next lesson). The Licensed Content is licensed "as-is. you can modify its definition without dropping and re-creating the view." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. Altering a view also involves less code than dropping and recreating a view.com or by calling +1 800-785-3448. The main advantage of using ALTER VIEW is that any permissions associated with the view are retained. It is illegal to reprint. ALTER VIEW The ALTER VIEW statement modifies a previously created view. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute.

Schemas SQL Server 2005 introduced the concept of schemas. a user John has no access to a table that is owned by Nupur. the two part naming for objects changed from owner. If Nupor creates a view or stored procedure that accesses the table and gives John permission to the view. At that point. This is not true. (This is often undesirable). Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. if Nupur creates a view or stored procedure that accesses a table owned by Tim and grants John access to the view or stored procedure. or resell this content. John can then access the view and though it. guarantees or conditions. objects no longer have owners. redistribute.object to schema.object. The configuration of security is simplified if schema owners also own objects that are contained in the schemas.QuickStart Intelligence Designing and Implementing Views 4-17 Ownership Chains and Views Key Points When querying a view. John would not be able to use the view or stored procedure. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the data in the underlying table. Objects still have owners. Ownership Chaining One of the key reasons for using views is to provide a layer of security abstraction so that access is given to views and not to the underlying table or tables.com or by calling +1 800-785-3448. . There seems to be a widespread misunderstanding that since that time. there needs to be an unbroken chain of ownership from the view to the underlying tables unless the user executing the query also has permissions on the underlying table or tables. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. Even schemas have owners. Two options could be used to correct this situation: • Tim could own the view or stored procedure instead of Nupur. an unbroken ownership chain must exist. For this mechanism to function correctly. • John could be granted permission to the underlying table. Ownership Chains vs. However. even if Nupur has access to Tim's table because of the broken ownership chain. In the example shown in the slide.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SQL Server Management Studio (SSMS) provides access to a list of views in Object Explorer. Sources of Information About Views You may need to see the definition of the view to understand how its data is derived from the source tables or to see the data defined by the view. and provided to you by QuickStart Intelligence.QuickStart Intelligence 4-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Sources of Information About Views Key Points Views are queried the same way that ordinary tables are queried.dm_sql_referenced_entities view. or resell this content. triggers. . Therefore. It is illegal to reprint. You may also though want to find out information about how a view is defined or about its properties. guarantees or conditions. The Licensed Content is licensed "as-is. display the dependencies of the object first to determine if any views are affected by the proposed change. If you change the name of an object referenced by a view. The output of the function is easier to consume in an application than the output of a system stored procedure such as sp_helptext. redistribute.com or by calling +1 800-785-3448. indexes and statistics defined on the views can be seen. Please report any unauthorized use of this content to piracy@microsoft. The OBJECT_DEFINITION() function allows querying the definition of an object in a relational format. By expanding the view nodes in Object Explorer. In Transact-SQL (T-SQL).sql_expression_dependencies view. object definitions (including the definitions of unencrypted views) would be located by executing the sp_helptext system stored procedure. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. details of the columns. Column-level dependencies can be found by querying the sys. In earlier versions of SQL Server. Overall dependencies can be found by querying the sys. before renaming an object. you must modify the view so that its text reflects the new name.views view. This includes both system views and user-created views. the list of views in a database can be obtained by querying the sys.

It is possible to modify a row in a view in such a way that the row would no longer belong to the view. Updatable Views Updates that are performed on views cannot affect columns from more than one base table. It will check during data modifications that any row modified would still be returned by the same view. you can create INSTEAD OF triggers. (To work around this restriction. guarantees or conditions. For example. and provided to you by QuickStart Intelligence. defaults. . These triggers are discussed in Module 15). constraints. This can be particularly challenging if all the columns in the base table are not present in the view. or resell this content. redistribute. Data that is modified in a base table via a view still needs to meet the restrictions on those columns such as nullability." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Designing and Implementing Views 4-19 Updatable Views Key Points It is possible to update data in the base tables by updating a view. While views can contain aggregated values from the base tables. etc. You could then update the row and set the State column to the value CA. For example. an INSERT on the view would fail if the base table it was based upon required mandatory columns that were not exposed in the view and that did not have DEFAULT values.com or by calling +1 800-785-3448. you can specify the WITH CHECK OPTION clause when defining the view. HAVING or DISTINCT. you could have a view that selected rows where the State column contained the value WA. these columns cannot be updated nor can columns involved in grouping operations such as GROUP BY. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. To avoid the chance of this. The Licensed Content is licensed "as-is. as if the base table was modified directly. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

redistribute. This is even more important when the view is created with the WITH ENCRYPTION option. It is illegal to reprint. and provided to you by QuickStart Intelligence.QuickStart Intelligence 4-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Obfuscating View Definitions Key Points Database developers often want to protect the definitions of their database objects. The Licensed Content is licensed "as-is. Many 3rd party utilities exist that can decrypt the source so you should not depend on this to protect your intellectual property if doing so is critical to you. Encrypted code (including the code definitions of views) makes it harder to perform problem diagnosis and query tracing and tuning. WITH ENCRYPTION The WITH ENCRYPTION clause provides limited obfuscation of the definition of a view. Please report any unauthorized use of this content to piracy@microsoft. Question: Do you think you might be deploying encrypted views in your organization? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The WITH ENCRYPTION clause can be included when defining or altering a view. guarantees or conditions. or resell this content. It is important to keep copies of the source code for views. . The encryption provided is not very strong." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448.

In the Connect to Server window. click Open. click Microsoft SQL Server 2008 R2. • In the virtual machine. click Start. guarantees or conditions.com or by calling +1 800-785-3448.ssmssln and click Open. type Proseware and click Connect. . It is illegal to reprint.QuickStart Intelligence Designing and Implementing Views 4-21 Demonstration 2A: Implementing Views Key Points In this demonstration you will see: • Create a view • Query a view • Query the definition of a view • Use the WITH ENCRYPTION option • Drop a view • Generate a script for an existing view Demonstration Steps 1. navigate to D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ. click Project/Solution. click SQL Server Management Studio." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Open and execute the 00 – Setup. Question: Why is the ability to script a view useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Open the 21 – Demonstration 2A. and provided to you by QuickStart Intelligence. or resell this content. The Licensed Content is licensed "as-is. click All Programs. From the File menu. 2.sql script file. redistribute.sql script file from within Solution Explorer. 3. Please report any unauthorized use of this content to piracy@microsoft. Follow the instructions contained within the comments of the script file. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.

guarantees or conditions. you will be able to: • Explain the dynamic resolution process for views • List the most important considerations when working with nested views • Create indexed views • Describe the purpose of partitioned views This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. you will see how views are incorporated directly into the execution plans of queries that they are used in.com or by calling +1 800-785-3448. . even if those tables are on different servers. or resell this content.QuickStart Intelligence 4-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Performance Considerations for Views Now that you understand why views are important and know how to create them. You will see the effect and potential disadvantages of nesting views and see how performance can be improved in some situations. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. Please report any unauthorized use of this content to piracy@microsoft. In this lesson. it is important to understand the potential performance impacts of using views. The Licensed Content is licensed "as-is. Objectives After completing this lesson. and provided to you by QuickStart Intelligence. you will see how the data from multiple tables can be combined into a single view. Finally.

A separate query plan for the view is not created. Merging the view query into the outer query is called "inlining" the query. Standard views do not appear in execution plans for queries. You can correct this situation by executing an updated ALTER VIEW statement or by calling the sp_refreshview system stored procedure. and provided to you by QuickStart Intelligence. It is illegal to reprint. . guarantees or conditions. The objects that they reference are resolved at execution time. you will notice that if you add a new column to the base table that the view will not reflect the column until the view has been refreshed. The use of SELECT * in a view definition should be avoided. redistribute. or resell this content. Views and Dynamic Resolution A single query plan is created that covers the query being executed and the definition of any views that it accesses. as the views are not accessed. As an example.QuickStart Intelligence Designing and Implementing Views 4-23 Views and Dynamic Resolution Key Points Standard views are expanded and incorporated into the queries that they are referenced in. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. The underlying objects that they reference will be seen in the execution plans.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Question: Suggest a type of join that could easily be eliminated when views are resolved? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It can be very benefical to performance as SQL Server can eliminate unnecessary joins and table accesses from queries.

Nested views can make it much harder to troubleshoot performance problems and more difficult to understand where complexity is arising in code. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. without realizing that this is occurring. Please report any unauthorized use of this content to piracy@microsoft. careful consideration needs to be made when doing this.QuickStart Intelligence 4-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Nested View Considerations Key Points While views can reference other views. or resell this content. guarantees or conditions. Views can help provide this. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. The biggest concern with nested views is that it is very easy to create code that is very difficult for the query optimizer to work with. and provided to you by QuickStart Intelligence. Nested Views Views can be nested up to 32 levels. Layers of abstraction are often regarded as desirable when designing code in any programming language.

table partitioning should be used instead of local partitioned views. Distributed partitioned views can be used to implement a federation of database servers. The Licensed Content is licensed "as-is. Partitioned Views Data ranges for each member table in a partitioned view are defined in a CHECK constraint specified on the partitioning column. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. all participating tables and the view reside on the same instance of SQL Server. In most cases. Good planning and testing is crucial as major performance problems can arise if the design of the partitioned views is not appropriate. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In a distributed partitioned view.com or by calling +1 800-785-3448. The data is partitioned between the member tables based on ranges of data values in one of the columns. at least one of the participating tables resides on a different (remote) server. In a local partitioned view. and provided to you by QuickStart Intelligence.QuickStart Intelligence Designing and Implementing Views 4-25 Partitioned Views Key Points Partitioned views allow the data in a large table to be split into smaller member tables. redistribute. It is illegal to reprint. A UNION ALL statement is used to combine selects of all the member tables into a single result set. .

and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448.ssmssln and click Open. Open the 31 – Demonstration 3A. click Microsoft SQL Server 2008 R2. From the File menu. 2.QuickStart Intelligence 4-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Views and Performance Key Points In this demonstration you will see how: • Views are eliminated in query plans • Views are expanded and integrated into the outer query before being optimized Demonstration Steps 1. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. • In the virtual machine. click All Programs. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • Open and execute the 00 – Setup. In the Connect to Server window. It is illegal to reprint. click Open.sql script file. click Start." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. . click SQL Server Management Studio. 3. guarantees or conditions. or resell this content. type Proseware and click Connect.sql script file from within Solution Explorer. click Project/Solution. navigate to D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Follow the instructions contained within the comments of the script file.

if the user is not already logged on: • On the Action menu. and then close the Virtual Machine Connection window. In the Virtual Machine Connection window. click on the Revert toolbar icon. Wait for the revert action to complete. click Revert. 7. guarantees or conditions. • In the Virtual Machine Connection window. • 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. and provided to you by QuickStart Intelligence. or resell this content. • Right-click 623XB-MIA-DC and click Start. 5. redistribute. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. wait until the Press CTRL+ALT+DELETE to log on message appears. Maximize the Hyper-V Manager window. and then click Hyper-V Manager. click the Ctrl-Alt-Delete menu item. 2. you must complete the following steps: 1.QuickStart Intelligence Designing and Implementing Views 4-27 Lab 4: Designing and Implementing Views Lab Setup For this lab. Before you begin the lab." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 6. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In the Virtual Machines list. click Start. On the host computer. In Virtual Machine Connection window. point to Administrative Tools. If you are prompted to confirm that you want to revert.com or by calling +1 800-785-3448. you will use the available virtual machine environment. if the virtual machine 623XB-MIA-DC is not started: 4. The Licensed Content is licensed "as-is. In the Virtual Machines list. 3. • In the Virtual Machine Connection window. • Right-click 623XB-MIA-SQL and click Connect. . wait until the Press CTRL+ALT+DELETE to log on message appears.

a request has been received from the new Marketing team that the catalog description of the product models should be added to the AvailableModels view. implement and test the required view. Details of organizational contacts are held in a number of tables. and then click Other User. check the Do not show me this console at logon check box and close the Server Manager window. type Proseware in the Server name text box. . 12. It is illegal to reprint. select Windows Authentication and click Connect. 11. Finally. they need a single view that comprises all contacts. redistribute. User name: AdventureWorks\Administrator ii. From the View menu. or resell this content. In the virtual machine. 15. Your manager is very concerned about providing access from the web-based system directly to the tables in your database. guarantees or conditions. In the File menu. click Start. Password: Pa$$w0rd 8. 13." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In Connect to Server window. When the query window opens. and click Project/Solution. click Open. Please report any unauthorized use of this content to piracy@microsoft. The relationship management system being used by the account management team needs to be able to gain access to these contacts. In the Authentication drop-down list box. You need to design.sql. 9. in the Virtual Machine Connection window. 14. double-click the query 00-Setup. click Microsoft SQL Server 2008 R2. She has requested you to design some views that the web-based system could connect to instead. if you have time.QuickStart Intelligence 4-28 Implementing a Microsoft® SQL Server® 2008 R2 Database • Click Switch User. 2 = Fast. Supporting Documentation View1: OnlineProducts ViewColumn SourceColumn ProductID ProductID ProductName ProductName ProductNumber ProductNumber Color Color (note ‘N/A’ should be returned when NULL) Availability Based on DaysToManufacture (0 = Instock. and click SQL Server Management Studio. click Full Screen Mode. click Execute on the toolbar. open the project D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ. Other Values = Call) This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. Lab Scenario A new web-based stock promotion system is being rolled out. 10.ssmssln. In Solution Explorer. 1 = Overnight. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. In the Open Project window. If the Server Manager window appears. However. • Log on using the following credentials: i. click All Programs. They would appreciate you modifying the view to provide this additional column.

Please report any unauthorized use of this content to piracy@microsoft. View3: Contacts ViewColumn SourceColumn in Prospect Source Column in Salesperson ContactID ProspectID SalespersonID FirstName FirstName FirstName MiddleName MiddleName MiddleName LastName LastName LastName ContactRole ‘PROSPECT’ ‘SALESPERSON’ Based on tables Marketing. It is illegal to reprint.QuickStart Intelligence Designing and Implementing Views ViewColumn SourceColumn Size Size UnitOfMeasure SizeUnitMeasureCode Price ListPrice Weight Weight 4-29 Note: Based on table Marketing. has begun to be sold and is still being sold. and provided to you by QuickStart Intelligence.Product and Marketing. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. (Derive this from SellStartDate and SellEndDate).Prospect and Marketing." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. Rows should only appear if the product has begun to be sold and is still being sold. View2: AvailableModels ViewColumn SourceColumn ProductID ProductID ProductName ProductName ProductModelID ProductModelID ProductModel ProductModel Based on tables Marketing.com or by calling +1 800-785-3448.Product. .Salesperson tables. The Licensed Content is licensed "as-is. (Derive this from SellStartDate and SellEndDate). or resell this content.ProductModel. redistribute. Rows should only appear if the product has at least one model.

Your manager is very concerned about providing access from the web-based system directly to the tables in your database. Implement and Test the WebStock Views Scenario A new web-based stock promotion system is being rolled. Create the WebStock schema 2. guarantees or conditions.QuickStart Intelligence 4-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Design. and provided to you by QuickStart Intelligence. She has requested you to design some views that the web-based system could connect to instead.  Task 2: Review the design requirements • You have been provided with the design requirements for the OnlineProducts and AvailableModels views. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Review these requirements.  Task 3: Design and implement the views • Design and implement the views  Task 4: Test the views • Query both views to ensure they return the required data Results: After this exercise. The main tasks for this exercise are as follows: 1. you should have created two new views: OnlineProducts and AvailableModels. Test the views  Task 1: Create the WebStock schema • In the MarketDev database create a new schema named WebStock with dbo as the owner. Review the design requirements 3. The Licensed Content is licensed "as-is. redistribute. both within the WebStock schema. . Design and implement the views 4.com or by calling +1 800-785-3448. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.  Task 3: Design and implement the view • Design and implement the view  Task 4: Test the view • Query the view to ensure it returns the required data Results: After this exercise.QuickStart Intelligence Designing and Implementing Views 4-31 Exercise 2: Design and Implement the Contacts View Scenario Details of organizational contacts are held in a number of tables. Design and implement the view 4. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. implement and test the required view. you should have created a new Contacts view within a new Relationship schema. The relationship management system being used by the account management team needs to be able to gain access to these contacts. Review these requirements. 1. guarantees or conditions. It is illegal to reprint. You need to design. Create the Relationship schema 2.com or by calling +1 800-785-3448. or resell this content. However. they need a single view that comprises all contacts. Please report any unauthorized use of this content to piracy@microsoft. Test the view  Task 1: Create the Relationship schema • In the MarketDev database create a new schema named Relationship with dbo as the owner. Review the design requirements 3. . and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is.  Task 2: Review the design requirements • You have been provided with the design requirements for the Contacts view.

the invariant language description (based on a blank string for LanguageID) should be returned. redistribute. you should have modified the AvailableModels view and it should return the new CatalogDescription column. the column should be null.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. If no descriptions exist. The Licensed Content is licensed "as-is. guarantees or conditions.  Task 2: Test the view • Query the view to ensure it now returns the required data Results: After this exercise. You need to now modify the view to provide this additional column. Multiple descriptions can exist for each model. If an English description exists (based on the LanguageID ‘en’). 1. it should be returned. .QuickStart Intelligence 4-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 3: Modify the AvailableModels View (Only if time permits) Scenario A request has been received from the new Marketing team that the catalog description of the product models should be added to the AvailableModels view. If no English description exists. Please report any unauthorized use of this content to piracy@microsoft. Alter the AvailableModels view to add the CatalogDescription column. Test the view  Task 1: Alter the AvailableModels View • Use the ALTER VIEW statement to change the view to suit the new requirements as described in the Exercise 3 scenario above. 2. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. The new column should be called CatalogDescription and should be taken from the ProductDescription table. or resell this content.

and provided to you by QuickStart Intelligence. Avoid nesting many layers within views. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. Ensure consistent connection SET options when intending to index views. How does SQL Server store the view in the database? 2. 2. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.QuickStart Intelligence Designing and Implementing Views 4-33 Module Review and Takeaways Review Questions 1. It is illegal to reprint. What is a Standard non-indexed view? 3. 4. redistribute. The Licensed Content is licensed "as-is. What is an unbroken ownership chain? Best Practices 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Use views to focus data for users. 3. Avoid ownership chain problems within views. or resell this content.

com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . guarantees or conditions. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. or resell this content. and provided to you by QuickStart Intelligence. redistribute.QuickStart Intelligence 4-34 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. redistribute.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-1 Module 5 Planning for SQL Server 2008 R2 Indexing Contents: Lesson 1: Core Indexing Concepts 5-3 Lesson 2: Data Types and Indexes 5-11 Lesson 3: Single Column and Composite Indexes 5-19 Lab 5: Planning for SQL Server Indexing 5-24 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. or resell this content. It is illegal to reprint.

Indexes are used to improve the performance of queries or enforce uniqueness.com or by calling +1 800-785-3448.QuickStart Intelligence 5-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview An index is a collection of pages associated with a table. Before learning to implement indexes. It is illegal to reprint. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. how effective different data types are when used within indexes. and provided to you by QuickStart Intelligence. guarantees or conditions. it is important to understand how they work. Objectives After completing this lesson. you will be able to: • Explain core indexing concepts • Describe the effectiveness of each data type common used in indexes • Plan for single column and composite indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. and how indexes can be constructed from multiple columns. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.

redistribute. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-3 Lesson 1 Core Indexing Concepts While it is possible for SQL Server to read all the pages in a table when calculating the results of a query. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. . guarantees or conditions. Finally. you will be able to: • Describe how SQL Server accesses data • Describe the need for indexes • Explain the concept of B-Tree index structures • Explain the concepts of index selectivity. The Licensed Content is licensed "as-is. or resell this content. In this lesson. density and depth • Explain why index fragmentation occurs This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. doing so is often highly inefficient. you will learn how indexes are structured and learn the key measures associated with the design of indexes. Indexes can be used to point to the location of required data and to minimize the need for scanning entire tables. you will see how indexes can become fragmented over time. Objectives After completing this lesson.

On occasions. It is illegal to reprint. if no proper indexing already exists. and provided to you by QuickStart Intelligence. Indexes are not required but accessing data by reading large numbers of pages is usually considerably slower than methods that use appropriate indexes. doing so is up to the optimizer and beyond the control of the database administrator or programmer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Question: When might a table scan be more efficient than using an index? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. SQL Server includes other types of index: • Integrated full-text search is a special type of index that provides flexible searching of text. SQL Server will create its own temporary indexes to improve query performance. guarantees or conditions. so these temporary indexes will not be discussed in this module. Queries can always be resolved by reading the underlying table data. • Primary and secondary XML indexes assist when querying XML data. it makes a decision about whether to read all the pages of the table or whether there are one or more indexes on the table that would reduce the amount of effort required in locating the required rows. Indexes Whenever SQL Server needs to access data in a table. Each of these other index types is discussed in later modules in this course. In this module. The temporary indexes are only used to improve a query plan. • Spatial indexes are used with the GEOMETRY and GEOGRAPHY data types. you will consider standard indexes created on tables. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. .QuickStart Intelligence 5-4 Implementing a Microsoft® SQL Server® 2008 R2 Database How SQL Server Accesses Data Key Points SQL Server can access data in a table by reading all the pages of the table (known as a table scan) or by using index pages to locate the required rows. or resell this content. However. Please report any unauthorized use of this content to piracy@microsoft. redistribute.

if books were stored in book name order. guarantees or conditions. It does so to make it fast to check whether or not a given value is already present." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. Note that even when you store the books in alphabetical order.com or by calling +1 800-785-3448. Whichever option is chosen makes one form of access easy and does not help other methods of access. A Useful Analogy At this point. Most libraries store books in a given order. Question: Which different ways might you want to locate books in a physical library? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Consider a physical library. redistribute. The order of the books could be based on the name of the book or the name of the author. it is useful to consider an analogy that might be easier to relate to.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-5 The Need for Indexes Key Points Indexes are not described in ANSI SQL definitions. which is basically an alphabetical order within a set of defined categories. or resell this content. It is illegal to reprint. SQL Server uses indexes for improving the performance of queries and for implementing certain constraints. When you assign a primary key or unique constraint to a column or set of columns. there are various ways that this could be done. For example. SQL Server also uses indexes as part of its implementation of primary key and unique constraints. Indexes can reduce the effort required to locate results but only if the indexes are well-designed. SQL Server automatically indexes that column or set of columns. The Need for Indexes As mentioned in the last topic. . The Licensed Content is licensed "as-is. how would you locate books written by a particular author? Indexes assist with this type of problem. Indexes are considered to be an implementation detail. SQL Server can always read the entire table to work out required results but doing so can be inefficient.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Whereas binary trees have at most two children per node. This style of tree can quickly become unbalanced and less useful. and provided to you by QuickStart Intelligence.QuickStart Intelligence 5-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Index Structures Key Points Tree structures are well known for providing rapid search capabilities for large numbers of entries in a list. SQL Server indexes are based on a form of self-balancing tree. The Licensed Content is licensed "as-is. Binary trees are simple structures where at each level. a decision is made to navigate left or right. guarantees or conditions. This helps improve the efficiency of the indexes and avoids the need for excessive depth within an index. Index Structures Indexes in database systems are often based on binary tree (B-Tree) structures. Please report any unauthorized use of this content to piracy@microsoft. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . Depth is defined as the number of levels from the top node (called the root node) and the bottom nodes (called leaf nodes). or resell this content. redistribute. SQL Server indexes can have a large number of children per node. It is illegal to reprint.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This would a process such as: • Find the first entry for the author in the index. Indexes with only 3 or 4 layers are very common. Please report any unauthorized use of this content to piracy@microsoft. redistribute. Now imagine doing the same for a range of authors such as one third of all the authors. • And so on. • Locate the book in the bookcases based on the information in the index entry. Index Depth is a measure of the number of levels from the root node to the leaf nodes.com or by calling +1 800-785-3448. The large number of children that each node in the index can have produces a very flat index structure. Selectivity. three core concepts are important: selectivity.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-7 Selectivity. Density and Index Depth Additional indexes on a table are most useful when they are highly selective. The Licensed Content is licensed "as-is. Density and Index Depth Key Points When designing indexes. Density is a measure of the lack of uniqueness of the data in a table. density and index depth. You quickly reach a point where it would be quicker to just scan the whole library and ignore the author index rather than running backwards and forwards between the index and the bookcases. • Return to the index and find the next entry for the author. and provided to you by QuickStart Intelligence. Users often imagine that SQL Server indexes are quite deep but the reality is quite different to this. For example. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. . • Locate the book in the bookcases based on the information in that next index entry. imagine how you would locate books by a specific author in a physical library using a card file index. guarantees or conditions. A dense table is one that has a high number of duplicates. It is illegal to reprint.

Internal vs. modifications to the data in the indexes can cause the need to split index pages. External Fragmentation Internal fragmentation is similar to what would occur if an existing bookcase was split into two bookcases. Detecting Fragmentation SQL Server provides a measure of fragmentation in the sys. External fragmentation relates to where the new bookcase would be physically located. While indexes may initially start full (or relatively full).QuickStart Intelligence 5-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Index Fragmentation Key Points Index fragmentation is the inefficient use of pages within an index. redistribute. imagine a fully populated library with full bookcases. the process is easy but if the book needs to be added in the middle of a full bookcase. indexes perform best when each page of the index is as full as possible.dm_db_index_physical_stats dynamic management view. The Licensed Content is licensed "as-is. . or resell this content. It is illegal to reprint. you could no longer just walk directly from bookcase to bookcase but would need to follow pointers around the library to follow a chain from one bookcase to another. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It would probably need to be placed at the end of the library. Please report any unauthorized use of this content to piracy@microsoft. even though it would "logically" need to be in a different order." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. The avg_fragmentation_in_percent column shows the percentage of fragmentation. Fragmentation occurs over time as data is modified. Each bookcase would then be only half full. Index Fragmentation For operations that read data. guarantees or conditions. What occurs when a new book needs to be added? If the book is added to the end of the library.com or by calling +1 800-785-3448. From our physical library analogy. there is a need to readjust the bookcase. That means that to read the bookcases in order.

and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. guarantees or conditions.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-9 SQL Server Management Studio also provides details of index fragmentation in the properties page for each index as shown in the following screenshot from the AdventureWorks2008R2 database: Question: Why does fragmentation affect performance? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. redistribute.

Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Open the 11 – Demonstration 1A.sql script file. guarantees or conditions. and provided to you by QuickStart Intelligence. 2. In the virtual machine. It is illegal to reprint. or resell this content.ssmssln and click Open. The Licensed Content is licensed "as-is. 5. From the File menu. click All Programs. click Start. click Open. click Microsoft SQL Server 2008 R2. Open and execute the 00 – Setup. In the Connect to Server window.QuickStart Intelligence 5-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Viewing Index Fragmentation Key Points In this demonstration you will see how to identify fragmented indexes Demonstration Steps 1. redistribute. Please report any unauthorized use of this content to piracy@microsoft. 3. click SQL Server Management Studio.sql script file from within Solution Explorer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. type Proseware in the Server name text box and click Connect. 4. Question: How might solid state disk drives change concerns around fragmentation? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . click Project/Solution. Follow the instructions contained within the comments of the script file. navigate to D:\6232B_Labs\6232B_05_PRJ\6232B_05_PRJ.com or by calling +1 800-785-3448.

. you will learn how effective a number of common data types are. It is illegal to reprint. and provided to you by QuickStart Intelligence. you will be able to: • Describe the effectiveness of numeric data when used in indexes • Describe the effectiveness of character data when used in indexes • Describe the effectiveness of date-related data when used in indexes • Describe the effectiveness of GUID data when used in indexes • Describe the effectiveness of BIT data when used in indexes • Explain how computed columns can be indexed." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. when used within indexes. guarantees or conditions.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-11 Lesson 2 Data Types and Indexes Not all data types work equally well as components of indexes. Objectives After completing this lesson. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In this lesson. or resell this content. The Licensed Content is licensed "as-is. This will assist you in choosing data types when designing indexes. redistribute. Please report any unauthorized use of this content to piracy@microsoft.

Numeric values are fast to compare and sort. this typically applies only to the exact numeric data types. The Licensed Content is licensed "as-is. large number of entries can fit in a small number of index pages. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Care needs to be taken with FLOAT and REAL predicates in certain operations. INT and BIGINT are the most efficient data types for indexing as they are relatively small and operations on them are very fast. and provided to you by QuickStart Intelligence. While numeric values are efficient in indexes. It is illegal to reprint. guarantees or conditions. Numeric Index Data When numeric values are used as components in indexes. . This improves both the general performance of index operations but also reduces the time taken to rebuild an index. Exact numeric types are the most efficient.com or by calling +1 800-785-3448. Question: Would you imagine that processor bit size effects the speed when comparing INT or BIGINT values? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Sort operations are very common in index operations. should this be required. redistribute. Please report any unauthorized use of this content to piracy@microsoft. FLOAT and REAL data types are much less useful in indexes as they are larger and require more complex comparison techniques than exact numeric data types. FLOAT and REAL data types are also not precise which can led to unpredictable results when used with the equality (=) operator. The same situation occurs outside their use in indexes.QuickStart Intelligence 5-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Numeric Index Data Key Points Numeric data types tend to produce highly-efficient indexes. This makes reading indexes based on numeric values very fast.

Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. Character based indexes also tend to cause fragmentation problems as new values are almost never ascending or descending.com or by calling +1 800-785-3448. For example. This complexity during comparisons makes character based index operations slow by comparison with the same operations on numeric values. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This makes character-based indexes slower to seek. This means that every time a string value needs to be compared to another string value. or resell this content. However. Character Index Data Character data values tend to be larger than numeric values. . The complexity of these operations depends upon whether or not a strict binary comparison of the values can be undertaken. guarantees or conditions. The Licensed Content is licensed "as-is. character based indexes are both common and useful. Most SQL Server systems use collations that are not based on binary comparisons. indexes constructed on character data tend to be less efficient than those constructed on numeric data. redistribute.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-13 Character Index Data Key Points While it might seem natural to base indexes on character data. This means that far less entries can exist in a given number of index pages. and provided to you by QuickStart Intelligence. Consider the operations required when comparing two string values. a complex set of rules needs to be applied to determine the outcome of the comparison. a character column might hold a customer's name or address details.

QuickStart Intelligence 5-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Date-Related Index Data Key Points Date related data types make good keys within indexes. Dates are very important (and very commonly used) in business applications as almost all business transactions involve a date (and possibly a time) when the transaction occurred. . or resell this content. Date-Related Index Data Date related data types are only slightly less efficient than the integer data types. redistribute. guarantees or conditions. It is very effective as a component of an index and more efficient than data types that also include time components.com or by calling +1 800-785-3448. Date related data types are relatively small and can be compared and sorted quickly. The Licensed Content is licensed "as-is. It is illegal to reprint. It is a very common requirement to need to locate all the transactions that occurred on a particular date or during a particular period (or range of dates). This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. SQL Server 2008 introduced the date data type.

The Licensed Content is licensed "as-is. Fragmentation problems are commonplace with indexes created on GUID data types and these problems are a very common cause of performance problems in SQL Server databases. GUID Index Data GUID values are reasonably efficient within indexes.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-15 GUID Index Data Key Points While GUID values can be relatively efficient in indexes. you will see how the use of GUID data types within indexes affects the performance of operations on the indexes." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This means that they pack quite tightly into indexes and can be compared and sorted quite quickly. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. or resell this content. significant problems arise when they are used in indexes. They are 16 bytes long and can be compared in a binary fashion. Because GUID values are random in nature. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. if those indexes need to process a large number of insert operations. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. operations on those indexes can lead to fragmentation problems and inefficiency. There is a common misconception that they are large. In the next module.

There is a common misconception that they are not useful but many valid scenarios exist for the use of BIT data type within indexes. and provided to you by QuickStart Intelligence. the number of values is not the issue. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. Note that the same index would be entirely useless for locating the finalized transactions. An index that uses the IsFinalized column would be very useful for finding the unfinalized transactions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. However. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. This stems from the fact that there are only two values. or resell this content. For example. consider a transaction table that contains 100 million rows and one of the columns (IsFinalized) indicates whether or not a transaction has been completed. guarantees or conditions. This difference is a good indication that it is an ideal candidate for the creation of a filtered index. (Filtered indexes are discussed later). BIT Index Data There is a very common misconception that bit columns are not useful in indexes. There might only be 500 transactions that are not completed. . It would be highly selective. It was discussed earlier in the module that the selectivity of queries is the most important issue issue.QuickStart Intelligence 5-16 Implementing a Microsoft® SQL Server® 2008 R2 Database BIT Index Data Key Points BIT columns are highly efficient in indexes. The Licensed Content is licensed "as-is. redistribute.

even if the requirements shown are met.). For example. ntext or image aren't permitted in the definition of the computed column • The NUMERIC_ROUNDABORT connection SET option needs to be OFF Note that SQL Server's query optimizer may ignore the index on a computed column. etc. It is illegal to reprint. a retail store may want to report on sales by day of the week (Sunday. SQL Server 2005 introduced the ability to persist computed columns. or resell this content. the function SYSDATETIME() returns the current date and time whenever it is called. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Tuesday. redistribute. the same output values would always be returned. Monday. . Indexing Computed Columns You can only create indexes on computed columns when certain conditions are met: • The expressions must be deterministic and precise • The ANSI_NULLS connection SET option must be ON • Expressions that return text. The Licensed Content is licensed "as-is. Its output would not be considered deterministic. You may want to create an index on a computed column when the results are queried or reported often. The requirement for determinism and precision means that for a given set of input values. Rather than calculating the value every time a SELECT operation is performed. the value can be calculated and stored whenever an INSERT This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. You can create a computed column that determines the day of the week based on the date of the sale and then index that computed column. For example. guarantees or conditions. It can also assist with improving the performance of poorly designed databases.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-17 Indexing Computed Columns Key Points Indexing a computed column can be highly efficient.

and provided to you by QuickStart Intelligence. Physical Analogy From our physical library analogy. Nothing about the book itself changes when the label is placed on it but you now don't have to pick the book up and count the number of pages in it. or resell this content. The Licensed Content is licensed "as-is. This is useful for data that is not updated frequently but is selected frequently.000 rows in the table) holds a number. Please report any unauthorized use of this content to piracy@microsoft. . Question: If a column in a database mostly held character values but occasionally (30 rows out of 50. how could you quickly locate a row with a specific numeric value? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. a persisted computed column for a book could be imagined as a label that is placed on the book that records the number of pages in the book. redistribute. guarantees or conditions.QuickStart Intelligence 5-18 Implementing a Microsoft® SQL Server® 2008 R2 Database or UPDATE occurs.com or by calling +1 800-785-3448. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. if you need to make a decision based on the number of pages in the book. Indexes can be created on the persisted computed column. An index could then be created based on the value on the label similarly to how an index could be created on the name of the author.

The Licensed Content is licensed "as-is. you will be able to: • Describe the differences between single column versus composite indexes • Describe the differences between ascending versus descending indexes • Explain how SQL Server keeps statistics on indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Indexes can also be constructed in ascending or descending order. redistribute. Please report any unauthorized use of this content to piracy@microsoft. . or resell this content. This lesson investigates these concepts and the effects they have on index design along with details of how SQL Server maintains statistics on the data contained within indexes. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Objectives After completing this lesson. It is illegal to reprint. and provided to you by QuickStart Intelligence. Indexes can also be based on the data from multiple columns.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-19 Lesson 3 Single Column and Composite Indexes The indexes discussed so far have been based on data from single columns.

redistribute. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. Single Columns vs. Once the correct topic was located. Separate indexes on publisher and release year would not be useful but an index that contained both publisher and release year could be very selective. when constructing composite indexes.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. In that case. Similarly. it would not help to narrow down the search to those books within the release year. Composite Indexes Composite indexes are often more useful than single column indexes in business applications. Multi-column indexes are known as composite indexes. you should typically index the most selective column first. or resell this content. While a publisher index would be useful for finding all the books released by the publisher. The best option would be an author index that also included details of each book's topic. The Licensed Content is licensed "as-is. an index by topic would be of limited value also." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. . The advantages of composite indexes are: • Higher selectivity • The possibility of avoiding the need to sort the output rows In our physical library analogy. consider a query that required the location of books by a publisher within a specific release year. Question: Why might an index on customer then order date be more or less effective than an index on order date then customer? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. all the books on that topic would have to be searched to determine if they were by the specified author. a scan of the index pages for the author would be all that is required to work out which books need to be accessed.QuickStart Intelligence 5-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Single Column vs. In the absence of any other design criteria. Composite Indexes Key Points Indexes can be constructed on multiple columns rather than on single columns.

For composite indexes. Descending Indexes In general it makes no difference whether a single column index is ascending or descending.com or by calling +1 800-785-3448. From our physical library analogy. . It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. Often this is used to avoid sorts. Composite indexes can benefit from different order in each component. or resell this content. For single column indexes. Ascending vs. From our physical library analogy. imagine that an author index a list of books by release date within the author index. This would be easier if the index was already structured this way." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. and provided to you by QuickStart Intelligence. For example. The Licensed Content is licensed "as-is. specifying the order of individual columns within the index might be useful. you might need to output orders by date descending within customer ascending. you could scan either the bookshelves or the indexes from either end. ascending and descending indexes are equally useful. Descending Indexes Key Points Each component of an index can be created in an ascending or descending order. The same amount of effort would be required no matter which end you started from.QuickStart Intelligence Planning for SQL Server 2008 R2 Indexing 5-21 Ascending vs.

QuickStart Intelligence

5-22

Implementing a Microsoft® SQL Server® 2008 R2 Database

Index Statistics

Key Points
SQL Server keeps statistics on indexes to assist when making decisions about how to access the data in a
table.

Index Statistics
Earlier in the module, you saw that SQL Server needs to make decisions about how to access the data in a
table. For each table that is referenced in a query, SQL Server might decide to read the data pages or it
might decide to use an index.
It is important to realize though, that SQL Server must make this decision before it begins to execute a
query. This means that it needs to have information that will assist it in making this determination. For
each index, SQL Server keeps statistics that tell it how the data is distributed.

Physical Analogy
When discussing the physical library analogy earlier, it was mentioned that if you were looking up the
books for an author, using an index that is ordered by author could be useful. However, if you were
locating books for a range of authors, that there would be a point at which scanning the entire library
would be quicker than running backwards and forwards from the index to the shelves of books.
The key issue here is that you need to know, before executing the query, how selective (and therefore
useful) the indexes would be. The statistics held on indexes provide this knowledge.
Question: Before starting to perform your lookup in a physical library, how would you know which way
was quicker?

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Planning for SQL Server 2008 R2 Indexing

5-23

Demonstration 3A: Viewing Index Statistics

Key Points
In this demonstration you will see how to work with index statistics.

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, 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_05_PRJ\6232B_05_PRJ.ssmssln and click
Open.

Open and execute the 00 – Setup.sql script file from within Solution Explorer.

2.

Open the 31 – Demonstration 3A.sql script file.

3.

Follow the instructions contained within the comments of the script file.

Question: Why would you not always choose to use FULLSCAN for statistics?

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-24

Implementing a Microsoft® SQL Server® 2008 R2 Database

Lab 5: Planning for SQL Server Indexing

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.

On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager.

2.

Maximize the Hyper-V Manager window.

3.

In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

4.

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.

5.

In Virtual Machine Connection window, click on the Revert toolbar icon.

6.

If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to
complete.

7.

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.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Planning for SQL Server 2008 R2 Indexing

Click Switch User, and then click Other User.

Log on using the following credentials:
i.

User name: AdventureWorks\Administrator

ii.

Password: Pa$$w0rd

8.

From the View menu, in the Virtual Machine Connection window, click Full Screen Mode.

9.

If the Server Manager window appears, check the Do not show me this console at logon check
box and close the Server Manager window.

5-25

10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click
SQL Server Management Studio.
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_05_PRJ\6232B_05_PRJ.ssmssln.
15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click
Execute on the toolbar.

Lab Scenario
You have been asked to explain the concept of index statistics and selectivity to a new developer. You will
explore the statistics available on an existing index and determine how selective some sample queries
would be.
One of the company developers has provided you with a list of the most important queries that will be
executed by the new marketing management system. Depending upon how much time you have
available, you need to determine the best column orders for indexes to support each query. Complete as
many as possible within the allocated time. In later modules, you will consider how these indexes would
be implemented. Each query is to be considered in isolation in this exercise.

Supporting Documentation
Query 1:
SELECT ProspectID, FirstName, LastName
FROM Marketing.Prospect
WHERE ProspectID = 12553;

Query 2:
SELECT ProspectID, FirstName, LastName
FROM Marketing.Prospect
WHERE FirstName LIKE 'Arif%';

Query 3:
SELECT ProspectID, FirstName, LastName
FROM Marketing.Prospect
WHERE FirstName LIKE 'Alejandro%'

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-26

Implementing a Microsoft® SQL Server® 2008 R2 Database

ORDER BY LastName, FirstName;

Query 4:
SELECT ProspectID, FirstName, LastName
FROM Marketing.Prospect
WHERE FirstName >= 'S'
ORDER BY LastName, FirstName;

Query 5:
SELECT LanguageID, COUNT(1)
FROM Marketing.ProductDescription
GROUP BY LanguageID;

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Planning for SQL Server 2008 R2 Indexing

5-27

Exercise 1: Explore existing index statistics
Scenario
You have been asked to explain the concept of index statistics and selectivity to a new developer. You will
explore the statistics available on an existing index and determine how selective some sample queries
would be.
The main tasks for this exercise are as follows:
1.

Execute the following command in the MarketDev database:

EXEC sp_helpstats ‘Marketing.Product’

2.

Review the results. Have any autostats been generated?

3.

Create manual statistics on the Color column. Call the statistics Product_Color_Stats. Use a full scan of
the data when creating the statistics.

4.

Re-execute the command from task 1 to see the change.

5.

Using the DBCC SHOW_STATISTICS command, review the created Product_Color_Stats statistics.

6.

Answer the following questions related to the Product_Color_Stats statistics:

7.

a.

How many rows were sampled?

b.

How many steps were created?

c.

What was the average key length?

d.

How many Black products are there?

Execute the following command to check how accurate the statistics that have been generated are:

SELECT COUNT(1) FROM Marketing.Product WHERE Color = 'Black';

8.

Calculate the selectivity of each of the three queries shown:
a)

SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'A%';

b)

SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE
'Alejandro%';

c)

SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE
'Arif%';

 Task 1: Execute SQL Command
1.

Execute the following command in the MarketDev database:

EXEC sp_helpstats ‘Marketing.Product’

 Task 2: Review the results

Review the results.

Check to see if any autostats has been generated?

 Task 3: Create statistics

Create manual statistics on the Color column. Call the statistics Product_Color_Stats. Use a full scan
of the data when creating the statistics.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-28

Implementing a Microsoft® SQL Server® 2008 R2 Database

 Task 4: Re-execute the SQL command from task 1

Re-execute the following command in the MarketDev database:

EXEC sp_helpstats ‘Marketing.Product’

 Task 5: Use DBCC SHOW_STATISTICS

Using the DBCC SHOW_STATISTICS command, review the created Product_Color_Stats statistics

 Task 6: Answer questions

Answer the following questions related to the Product_Color_Stats statistics:
a.

How many rows were sampled?

b.

How many steps were created?

c.

What was the average key length?

d.

How many Black products are there?

 Task 7: Execute SQL Command and check accuracy of statistics

Execute the following command to check how accurate the statistics that have been generated are:

SELECT COUNT(1) FROM Marketing.Product WHERE Color = 'Black';

 Task 8: Calculate Selectivity of each query

Calculate the selectivity of each of the three queries shown:

Query 1:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'A%';

Query 2:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE
'Alejandro%';

Query 3:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE
'Arif%';

Results: After this exercise, you have assessed Selectivity on each various queries.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Planning for SQL Server 2008 R2 Indexing

5-29

Challenge Exercise 2: Design column orders for indexes (Only if time
permits)
Scenario
One of the company developers has provided you with a list of the most important queries that will be
executed by the new marketing management system. You need to determine the best column orders for
indexes to support each query. In later modules, you will consider how these indexes would be
implemented. Each query is to be considered in isolation in this exercise.
The main tasks for this exercise are as follows:
1.
2.
3.
4.
5.

Determine which columns should be part of an index for Query1 and the best order for the columns
to support the query.
Determine which columns should be part of an index for Query2 and the best order for the columns
to support the query.
Determine which columns should be part of an index for Query3 and the best order for the columns
to support the query.
Determine which columns should be part of an index for Query4 and the best order for the columns
to support the query.
Determine which columns should be part of an index for Query5 and the best order for the columns
to support the query.

 Task 1: Design an index

Review the supporting documentation, determine which columns should be part of an index for
Query 1 and the best order for the columns to support the query.

 Task 2: Design an index

Review the supporting documentation, determine which columns should be part of an index for
Query 2 and the best order for the columns to support the query.

 Task 3: Design an index

Review the supporting documentation, determine which columns should be part of an index for
Query 3 and the best order for the columns to support the query.

 Task 4: Design an index

Review the supporting documentation, determine which columns should be part of an index for
Query 4 and the best order for the columns to support the query.

 Task 5: Design an index

Review the supporting documentation, determine which columns should be part of an index for
Query 5 and the best order for the columns to support the query.
Results: After this exercise, you should designed new indexes taking into consideration of Selectivity

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-30

Implementing a Microsoft® SQL Server® 2008 R2 Database

Module Review and Takeaways

Review Questions
1.
2.

Do tables need indexes?
Why do constraints use indexes?

Best Practices
1.
2.

Design indexes to maximize sensitivity which leads to lower I/O.
In absence of other requirements, aim to have the most selective columns first in composite indexes.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

guarantees or conditions. It is illegal to reprint.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-1 Module 6 Implementing Table Structures in SQL Server 2008 R2 Contents: Lesson 1: SQL Server Table Structures 6-3 Lesson 2: Working with Clustered Indexes 6-13 Lesson 3: Designing Effective Clustered Indexes 6-20 Lab 6: Implementing Table Structures in SQL Server 6-26 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. or resell this content.

and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. In this module. . For situations where you decide to have a specific structure in place. you will learn how to create an effective structure. the table itself can be structured like an index or left without such a structure. redistribute. Objectives After completing this lesson. you will be able to: • Explain how tables can be structured in SQL Server databases • Work with clustered indexes • Design effective clustered indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is.QuickStart Intelligence 6-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview One of the most important decisions that needs to be taken when designing tables in SQL Server databases relates to the structure of the table." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. you will learn how to choose an appropriate table structure. Please report any unauthorized use of this content to piracy@microsoft. Regardless of whether or not other indexes are used to locate rows. or resell this content. It is illegal to reprint.

and provided to you by QuickStart Intelligence. guarantees or conditions. gain an understanding of how common data modification operations are impacted by each option. Finally. redistribute. In this lesson." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. you will investigate both options. Please report any unauthorized use of this content to piracy@microsoft. you will be able to: • Describe how tables can be organized as heaps • Explain how common operations are performed on heaps • Detail the issues that can arise with forwarding pointers • Describe how tables can be organized with clustered indexes • Explain how common operations are performed on tables with clustered indexes • Describe how unique clustered indexes are structured differently to non-unique clustered indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . Objectives After completing this lesson. you will see how unique clustered indexes are structured differently to non-unique clustered indexes.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-3 Lesson 1 SQL Server Table Structures There are two ways that SQL Server tables can be structured. Rows can be added in any order or rows can be ordered. or resell this content. It is illegal to reprint.

Question: Why might modifying a row cause it to need to move between pages? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Data rows are added to the first available location within the table's pages that have sufficient space. guarantees or conditions. a heap would be represented by structuring your library so that every book is just placed in any available space found that is large enough. Without any other assistance. The Licensed Content is licensed "as-is. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Heaps The simplest table structure available in SQL Server is a heap. and provided to you by QuickStart Intelligence.QuickStart Intelligence 6-4 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a Heap? Key Points A heap is a table that has no enforced order for either the pages within the table or for the data rows within each page. If no space is available. Heaps are allocated index id zero in this map. Physical Analogy In the physical library analogy. Please report any unauthorized use of this content to piracy@microsoft. SQL Server tracks the available pages using an entry in an internal structure called an Index Allocation Map (IAM). redistribute.com or by calling +1 800-785-3448. Even though no index structure exists for a heap. It is illegal to reprint. additional pages are added to the table and the rows placed in those pages. or resell this content. finding a book would involve scanning one bookcase after another.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. However. an INSERT would be executed by locating any gap large enough to hold the book and placing it there. and provided to you by QuickStart Intelligence. redistribute. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is. removing the book and throwing it away. A DELETE operation could be imagined as scanning the bookcases until the book is found. UPDATE. If no space that is large enough is available. Question: What would be involved in finding a book in a library structured as a heap? (This would simulate a SELECT operation). if the replacement book was larger.com or by calling +1 800-785-3448. a new bookcase would be allocated and the book placed into it. An UPDATE operation would be represented by replacing a book with a (potentially) different copy of the same book. DELETE and SELECT operations. guarantees or conditions. This would continue unless a limit existed on the number of bookcases that the library could contain. More precisely. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Physical Analogy In the library analogy. It is important to understand how each of these operations is affected by structuring a table as a heap.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-5 Operations on Heaps Key Points The most common operations performed on tables are INSERT. or resell this content. It is illegal to reprint. The new location for the book could be in the same bookcase or in another bookcase. it could be placed directly back in the same location as the original book. the original book would be removed and placed into another location. If the replacement book was the same (or smaller) size as the original book. it would be like placing a tag on the book to say that it is to be thrown out the next time the library is cleaned up or space on the bookcase is needed.

guarantees or conditions. That is. Further imagine that three additional indexes were created in the library. Physical Analogy Now imagine that the physical library was organized as a heap where books were stored in no particular order. Either way. One option for resolving this would be to locate all index entries for the book and update the new physical location. This way. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute.Book 3". and provided to you by QuickStart Intelligence. Either yet another note could be left pointing to the new location or the original note could be modified to point to the new location. The entry would include an address like "Bookcase 12 . This is what a forwarding pointer is in SQL Server. An update to the book that caused it to need to be moved to a different location would be problematic.Shelf 5 . An alternate option would be to leave a note in the location where the book used to be that points to where the book has been moved to. A further challenge arises if the book needed to be moved again. there would need to be a specific address for a book. when an entry was found in the ISBN index. ISBN. This allows rows to be updated and moved without the need to update other indexes that point to them. There are two options ways that this could be handled.QuickStart Intelligence 6-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Forwarding Pointers Key Points When other indexes point to rows in a heap. This can cause performance issues over time. SQL Server deals with this by updating the original forwarding pointer. the entry would refer to the physical location of the book. . As there was no order to the books on the bookcases. performance does not continue to degrade by having to follow a chain of forwarding pointers." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. data modification operations cause forwarding pointers to be inserted into the heap. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. It is illegal to reprint. to make it easier to find books by author. the original indexes would not need to be updated.com or by calling +1 800-785-3448. or resell this content. and release date.

Note that while options to rebuild indexes have been available in prior versions. This command can also be used to change the compression settings for a table. guarantees or conditions. or resell this content. redistribute. each had significant downsides. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. SQL Server 2008 introduced a method for dealing with this problem via the command: ALTER TABLE SomeTable WITH REBUILD. There were no straightforward options for "cleaning up" a heap to remove the forwarding pointers. the option to rebuild a table was not available.com or by calling +1 800-785-3448. . While options existed for removing forwarding pointers.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-7 ALTER TABLE WITH REBUILD Forwarding pointers were a common performance problem with SQL Server tables that were structured as heaps. (Page and Row Compression are an advanced topic beyond the scope of this course). and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

An Index Allocation Map entry is used to point to a clustered index. There is a common misconception that pages in a clustered index are "physically stored in order". It is illegal to reprint. Clustered indexes are always index id = 1. If it was true. Because the rows of a table can only be in a single order. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. The order is based on a key made up of one or more columns. redistribute. An example of this would be to store books in ISBN (International Standard Book Number) order. This is known as a clustered index. The key is commonly called a clustering key. . it is not commonly the case. While this is possible in rare situations. Clustered Index A table with a clustered index has a predefined order for rows within a page and for pages within the table. SQL Server tries to align physical and logical order while creating an index but disorder can arise as data is modified.QuickStart Intelligence 6-8 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a Clustered Index? Key Points Rather than storing data rows of a data as a heap.com or by calling +1 800-785-3448. there can be only a single clustered index on a table. fragmentation of clustered indexes would not exist. Clearly. the library can only be in a single order. tables can be designed with an internal logical ordering. a clustered index is similar to storing all books in a specific order." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. Index and data pages are linked within a logical hierarchy and also double-linked across all pages at the same level of the hierarchy to assist when scanning across an index. guarantees or conditions. Physical Analogy In the library analogy.

the books would be located by finding the first This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. the bookcase would need to be split. It is illegal to reprint. if the replacement book is the same size or smaller and the ISBN has not changed. A DELETE operation would involve the book being removed from the bookcase.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-9 Operations on Clustered Indexes Key Points Earlier you saw how common operations were carried out on tables structured as heaps. and there is spare space within the bookcase." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. If the replacement book is larger and the ISBN has not changed.com or by calling +1 800-785-3448. all other books in the bookcase can be slid along to allow the larger book to be replaced in the same spot. Please report any unauthorized use of this content to piracy@microsoft. When a SELECT is performed. the book can be placed into the correct location and all other books in the bookcase moved to accommodate the new book. the original book would need to be removed and the replacement book treated like the insertion of a new book. no splitting is required. the required book can be quickly located by efficiently searching the library. If there is not sufficient space. . The Licensed Content is licensed "as-is. Physical Analogy In a library that is ordered in ISBN order. It is important to understand how each of those operations is affected by structuring a table with a clustered index. more formerly. If a range of ISBN's was requested. (Again. if the ISBN is known. If the ISBN of the replacement book wass different to the original book. If there was insufficient space in the bookcase to accommodate the larger book. redistribute. or resell this content. guarantees or conditions. New books could always be added to the end of the library and new bookcases added as required. If there is space somewhere on the bookcase that is in the required position. the bookcase needs to be split. INSERT operations would be straightforward if the books were being added in ISBN order. an INSERT operation requires a new book to be placed in exactly the correct logical ISBN order. Note that a new bookcase would be physically placed at the end of the library but would be logically inserted into the list of bookcases. it would be flagged as free space but simply left in place for later removal). the book can just be replaced in the same place. When an UPDATE operation is performed. In this case.

Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. . It is illegal to reprint. or resell this content. guarantees or conditions. Question: What sort of queries would now perform better in this library? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute.QuickStart Intelligence 6-10 Implementing a Microsoft® SQL Server® 2008 R2 Database book and continuing to collect books in order until a book is encountered that is out of range or until the end of the library is reached. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

and provided to you by QuickStart Intelligence. guarantees or conditions. If an insert of a new book is attempted and another book is found to have the same ISBN (assuming that the ISBN was the clustering key).QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-11 Unique vs. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The issue is that it is likely to be desirable to track each copy of the book separately." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Unique vs. It is important to understand that the comparison is made only on the clustering key. Non-Unique Clustered Indexes Key Points SQL Server must be able to uniquely identify any row in a table. Non-Unique Clustered Indexes If you do not specify indexes as being unique. Physical Analogy In the library analogy. The uniqueifier is not visible to users. or resell this content.com or by calling +1 800-785-3448. It is illegal to reprint. This value is commonly called a "uniqueifier". redistribute. the insertion of the new book would be refused. Clustered indexes can be created as unique or non-unique. SQL Server will add another value to the clustering key to ensure that the values are unique for each row. The Licensed Content is licensed "as-is. even if other properties of the book are different. The book would be rejected for having the same ISBN. A non-unique clustered index is similar to having a rule that allows more than a single book with the same ISBN. a unique index is like a rule that says that no more than a single copy of any book can ever be stored. . Please report any unauthorized use of this content to piracy@microsoft. The uniqueifier that is added by SQL Server would be like a "Copy Number" being added to books that can be duplicated.

click Start.QuickStart Intelligence 6-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Rebuilding Heaps Key Points In this demonstration you will see how to: • Create a table as a heap • Check the fragmentation and forwarding pointers for a heap • Rebuild a heap Demonstration Steps 1. guarantees or conditions.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. 4. 3. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Open the 11 – Demonstration 1A. Follow the instructions contained within the comments of the script file. or resell this content.sql script file. In the Connect to Server window. 2. click Microsoft SQL Server 2008 R2.sql script file from within Solution Explorer. In the virtual machine. It is illegal to reprint.ssmssln and click Open. click Project/Solution. 5. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click SQL Server Management Studio. From the File menu. click Open. redistribute. . Open and execute the 00 – Setup. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. navigate to D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ. Please report any unauthorized use of this content to piracy@microsoft. click All Programs. type Proseware in the Server name text box and click Connect.

It is illegal to reprint. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. redistribute. you will be able to: • Create clustered indexes • Drop a clustered index • Alter a clustered index • Incorporate Free Space in indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. altered or dropped. . The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. it is important to be familiar with how the indexes are created. Objectives After completing this lesson.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-13 Lesson 2 Working with Clustered Indexes If a decision has been made to structure a table with a clustered index. In this lesson. guarantees or conditions. understand how SQL Server performs them automatically in some situations and see how to incorporate free space within indexes to improve insert performance. you will see how to perform these actions.

the index that is created to support the PRIMARY KEY constraint will be created as a clustered PRIMARY KEY. It is illegal to reprint. If a table has been created as a heap. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. the dbo. The default action in SQL Server when a PRIMARY KEY constraint is added to a table is to make it a clustered PRIMARY KEY if no other clustered index already exists on the table. . ArticleID will be the clustering key as well as the PRIMARY KEY for the table. it causes the entire structure of the table to be reorganized. guarantees or conditions. In the second example on the slide. or resell this content.LogTime table with the LogTimeID column as the clustering key. no other clustered index is present on the table. The Licensed Content is licensed "as-is. This action can be overridden by specifying the word NONCLUSTERED when declaring the PRIMARY KEY constraint. so SQL Server will create the index to support the PRIMARY KEY constraint as a clustered index. When the PRIMARY KEY constraint is added to the table.QuickStart Intelligence 6-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Creating Clustered Indexes Key Points Clustered indexes can be created either directly using the CREATE INDEX command or automatically in some situations where a PRIMARY KEY constraint is specified on the table. the table dbo. it can be converted to a clustered index structure by adding a clustered index to the table. redistribute. This command will not only create an index over the data. Creating Clustered Indexes It is very important to understand the distinction between a PRIMARY KEY and a clustering key. It is a logical concept that is supported by an index but the index may or may not be a clustered index.com or by calling +1 800-785-3448. As there is no other clustered index on the table. In the fourth command shown in the examples on the slide.LogData is initially created as a heap. A PRIMARY KEY is a constraint. Please report any unauthorized use of this content to piracy@microsoft. a clustered index named CL_LogTime is added to the dbo. Many users confuse the two terms or attempt to use them interchangeably. The ArticleID column has a PRIMARY KEY constraint associated with it. In the first example on the slide.Article table is being declared." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence.

It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. or resell this content. The Licensed Content is licensed "as-is. redistribute. guarantees or conditions. and provided to you by QuickStart Intelligence.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-15 Question: What else would be added to your table if you added a non-unique clustered index to it? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. .

and provided to you by QuickStart Intelligence. redistribute.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. When the clustered index is dropped. Dropping a Clustered Index The DROP INDEX command can be used to drop clustered indexes that were created with the CREATE INDEX command. Indexes that are created internally to support constraints need to be removed by removing the constraint.QuickStart Intelligence 6-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Dropping a Clustered Index Key Points The method used to drop a clustered index depends upon the way the clustered index was created. The Licensed Content is licensed "as-is. The table is reorganized as a heap. Please report any unauthorized use of this content to piracy@microsoft. the data in the table is not lost. . guarantees or conditions. or resell this content. Note in the second example on the slide that the PRIMARY KEY constraint is being dropped. This would cause a clustered index that had been created to support that key to also be dropped. Question: How could you remove a primary key constraint that was being referenced by a foreign key constraint? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

an index can be rebuilt or reorganized. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. Disabling Indexes While the ALTER INDEX statement includes a DISABLE option that can be applied to any index. guarantees or conditions. Once a clustered index is disabled. WITH DROP EXISTING An option to change the structure of an index is provided while creating a replacement index. this option is of limited use with clustered indexes. no access to the data in the table is then permitted until it is rebuilt. The Licensed Content is licensed "as-is. For example. including the columns that make up the key. . redistribute. Altering a Clustered Index A few maintenance operations are possible with the ALTER INDEX statement. (Filegroups are a concept that is covered in the course 6231B Maintaining a SQL Server 2008 R2 Database). (Reorganizing an index only affects the leaf level of the index)." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Columns that make up the clustering key cannot be added or removed using this command and the index cannot be moved to a different filegroup. (Non-clustered indexes are covered in module 08). Restructuring an index is not permitted within an ALTER INDEX statement. Note that an index cannot be changed from a clustered to a non-clustered index or back using this command.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-17 Altering a Clustered Index Key Points Minor modifications to indexes are permitted through the ALTER INDEX statement but it cannot be used to modify the structure of the index. The CREATE INDEX command includes a WITH DROP EXISTING clause that can allow the statement to replace an existing index. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448.

FILLFACTOR and PADINDEX The availability of free space in an index page can have a significant effect on the performance of index update operations. causes the same free space to be allocated in the non-leaf levels of the index. what would be the downside of doing this? Question: When would a FILLFACTOR of 100 be useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. FILLFACTOR defaults to 0.com or by calling +1 800-785-3448. Question: While you could avoid many page splits by setting a FILLFACTOR of 50. a new index page must be created and the contents of the old page split across the two pages.QuickStart Intelligence 6-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Incorporating Free Space in Indexes Key Points The FILLFACTOR and PADINDEX options are used to provide free space within index pages. including a clustered index. This can affect performance if it happens too frequently. FILLFACTOR only applies to leaf level pages in an index." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. This can improve INSERT and UPDATE performance in some situations but often to the detriment of SELECT operations. or resell this content. The Licensed Content is licensed "as-is. PAD_INDEX is an option that. this means 70% full and 30% free space on each page. and provided to you by QuickStart Intelligence. . It is illegal to reprint. This is achieved by specifying a FILLFACTOR value. which means "fill 100%". Another other value (including 100) is taken as the percentage of how full each page should be. For the example in the slide. redistribute. The performance impacts of page splits can be alleviated by leaving empty space on each page when creating an index. guarantees or conditions. when enabled. If an index record must be inserted and there is no free space.

Please report any unauthorized use of this content to piracy@microsoft. From the File menu. click SQL Server Management Studio. • In the virtual machine. • Open and execute the 00 – Setup. and provided to you by QuickStart Intelligence.ssmssln and click Open." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-19 Demonstration 2A: Clustered Indexes Key Points In this demonstration you will see how to: • Create a table with a clustered index • Detect fragmentation in a clustered index • Correct fragmentation in a clustered index Demonstration Steps 1. . click Microsoft SQL Server 2008 R2. click Start. click Open. 3. type Proseware in the Server name text box and click Connect. 2. Follow the instructions contained within the comments of the script file. The Licensed Content is licensed "as-is. click Project/Solution. Open the 21 – Demonstration 2A. Question: Where was the performance of the UPDATE statement against this table much faster than the one against the heap? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. or resell this content. It is illegal to reprint. click All Programs. 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. guarantees or conditions. In the Connect to Server window. navigate to D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ.sql script file.com or by calling +1 800-785-3448.

QuickStart Intelligence 6-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Designing Effective Clustered Indexes When creating clustered indexes on tables. it is important to understand the characteristics of good clustering keys. redistribute.com or by calling +1 800-785-3448. Some data types work better for clustering keys than others. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will see how to design good clustering keys and also see how clustered indexes can be created on views. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. you will be able to: • Describe characteristics of good clustering keys • Explain which data types are most appropriate for use in clustering keys • Create indexed views • Explain considerations that must be made when working with indexed views This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. . In this lesson. and provided to you by QuickStart Intelligence. guarantees or conditions. Objectives After completing this lesson.

redistribute. the need to split pages. If the keys within the data are increasing as they are inserted. The Licensed Content is licensed "as-is. It is important to declare unique values as being unique. there is a set of characteristics that generally create the best clustering keys. and reduces the amount of memory needed for page buffers. This minimizes fragmentation.com or by calling +1 800-785-3448. SQL Server will still add a uniqueifier column to the key. then the inserts happen directly at the logical end of the table. • Static – clustering keys should be based on data values that do not change. • Unique – unique clustering keys do not need to have a uniqueifier column added by SQL Server. Keys should be short. While there is a limit of 16 columns and 900 bytes. This is one reason why primary keys are often used for this purpose. Otherwise. While not every situation is identical. and provided to you by QuickStart Intelligence. guarantees or conditions. You have seen already that moving rows is generally not desirable. • Increasing – this assists with INSERT behavior. good clustering keys are typically much. most designs call for clustering keys with the following characteristics: • Short – clustering keys should be short. It is illegal to reprint. Characteristics of Good Clustering Keys Although some designs might call for different styles of clustering key. static. They need to be sorted and they are stored at the leaf level of every other index. or resell this content. A change to the clustering key will mean the need to move the row. increasing and unique. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. much smaller than this. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-21 Characteristics of Good Clustering Keys Key Points Many different types of data can be used for clustering a table.

While they are larger than the integer types. Please report any unauthorized use of this content to piracy@microsoft. Physical Schema Users typically struggle with the concept that their physical data schema does not have to match their logical data schema. Date data is typically not unique but provides excellent advantages in size.QuickStart Intelligence 6-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Appropriate Data Types for Clustering Keys Key Points Similar to the way that some data types are generally better as components of indexes than other data types. guarantees or conditions. redistribute. Logical vs. SQL Server 2005 introduced the NEWSEQUENTIALID() function to try to address the issue of increasing values. sorting performance. It is illegal to reprint. while GUIDs might be used throughout an application layer. they do not have to be used throughout the physical implementation of the schema. some data types are more appropriate for use as clustering keys than others. Question: New uniqueidentifier values in SQL Server can be generated with the NEWID() function. or resell this content. One option would be to use one table to look up an int based on a GUID and have that int used everywhere else in the design. For example. The biggest challenge in current designs is the use (and overuse) of GUIDs that are stored in uniqueidentifier columns. GUIDs are random in nature and routinely cause index fragmentation through page splits when used as clustering keys. Appropriate Data Types for Clustering Keys int and bigint typically make the best clustering keys in general use. The Licensed Content is licensed "as-is. It works well for date range queries that are common in typical business applications.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Why doesn't this typically solve the problem of random values? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. (Constraints are discussed in a later module). Character data types can be used for clustering keys but the sorting performance of character data types is limited. particularly if they are used in conjunction with an IDENTITY constraint that causes their values to continue to increase. . Character values often tend to change in typical business applications. and provided to you by QuickStart Intelligence.

A view with a clustered index is called an "indexed view".QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-23 Creating Indexed Views Key Points Clustered indexes can be created over views. SQL Server makes updates to the data stored in the indexed view automatically. The Licensed Content is licensed "as-is. . and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. you don't modify the table directly. you modify the data in the "real" tables that underpin the view. SQL Server realizes that it needs to update the data in the indexed view. Indexed views are the closest SQL Server equivalent to "materialized views" in other databases. It is illegal to reprint. Indexes views are very useful for maintaining precalculated aggregates or joins. When updates to the underlying data are made. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Also. DELETE. They are most useful for data that is regularly selected but much less frequently updated. Indexed views have a negative impact on the performance of INSERT. guarantees or conditions. The differences are that the schema of the table isn't defined directly. it is defined by the SELECT statement in the view. You can imagine an indexed view as a special type of table with a clustered index. Creating Indexed Views The concept of an indexed view might at first seem odd as an index is being created over an object that is not persisted.com or by calling +1 800-785-3448. redistribute. When the data in the underlying tables is modified. Indexed views can have a profound (positive) impact on the performance of queries in particular circumstances. and UPDATE operations on the underlying tables but they can also have a very positive impact on the performance of SELECT queries on the view.

. an indexed view could not contain a column that returned the outcome of the SYSDATETIME() function. or resell this content. It is illegal to reprint. Indexed View Considerations Indexed views can be a challenge to set up and use. That is. SCHEMABINDING is an option that the view must have been created with before an index can be created on the view. guarantees or conditions. Books Online details a list of SET options that need to be in place both at creation time for the indexed view and in sessions that take advantage of the indexed views. Particular attention should be given to the CONCAT_NULL_YIELDS_NULL and QUOTED_IDENTIFIER settings. the views must always return the same data unless the underlying table data is altered. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The SCHEMABINDING option prevents changes to the schema of the underlying tables while the view exists. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Premium editions of SQL Server take more complete advantage of indexed views.QuickStart Intelligence 6-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Indexed View Considerations Key Points The use of indexed views is governed by a set of considerations that must be met for the views to be utilized. For example. redistribute. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. Indexes can only be built on views that are deterministic.

click Project/Solution. 2. Follow the instructions contained within the comments of the script file. Open the 31 – Demonstration 3A. From the File menu. or resell this content. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click Open. In the Connect to Server window. guarantees or conditions. click SQL Server Management Studio. The Licensed Content is licensed "as-is. click Microsoft SQL Server 2008 R2. • In the virtual machine. • Open and execute the 00 – Setup.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-25 Demonstration 3A: Indexed Views Key Points In this demonstration you will see how to: • Obtain details of indexes created on views • See if an indexed view has been used in an estimated execution plan Demonstration Steps 1. Please report any unauthorized use of this content to piracy@microsoft.sql script file from within Solution Explorer. navigate to D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ.sql script file. redistribute. . 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. It is illegal to reprint. click Start. click All Programs. type Proseware in the Server name text box and click Connect. Question: How could you ensure that an indexed view is selected when working with Standard Edition of SQL Server? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 3.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click on the Revert toolbar icon. 5. • Right-click 623XB-MIA-DC and click Connect. click Revert. Maximize the Hyper-V Manager window. and then close the Virtual Machine Connection window. click the Ctrl-Alt-Delete menu item. point to Administrative Tools. 6. wait until the Press CTRL+ALT+DELETE to log on message appears. redistribute. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. 3. and then click Hyper-V Manager. if the user is not already logged on: • On the Action menu. Before you begin the lab. The Licensed Content is licensed "as-is. Wait for the revert action to complete. 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. In the Virtual Machines list. Please report any unauthorized use of this content to piracy@microsoft. • In the Virtual Machine Connection window. 2. you must complete the following steps: 1. • In the Virtual Machine Connection window. It is illegal to reprint. In Virtual Machine Connection window. 7. if the virtual machine 623XB-MIA-DC is not started: 4. guarantees or conditions. and provided to you by QuickStart Intelligence. click Start. • Right-click 623XB-MIA-DC and click Start.com or by calling +1 800-785-3448. you will use the available virtual machine environment. .QuickStart Intelligence 6-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 6: Implementing Table Structures in SQL Server Lab Setup For this lab. In the Virtual Machine Connection window. or resell this content. • Right-click 623XB-MIA-SQL and click Connect. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In the Virtual Machines list.

When the query window opens.sql.ActivityLog Name Data Type ActivityTime datetimeoffset SessionID int Duration int ActivityType int Constraint Table 2: Relationship." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .com or by calling +1 800-785-3448. 13. If the Server Manager window appears. Please report any unauthorized use of this content to piracy@microsoft. 14. and click Project/Solution. • Log on using the following credentials: i. Lab Scenario One of the most important decisions when designing a table is to choose an appropriate table structure. 10. click Microsoft SQL Server 2008 R2.ssmssln. select Windows Authentication and click Connect. click Execute on the toolbar. ii. you will choose an appropriate structure for some new tables required for the relationship management system. and click SQL Server Management Studio.PhoneLog Name Data Type Constraint PhoneLogID int Primary Key SalespersonID int CalledPhoneNumber nvarchar(16) CallDurationSeconds int This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. in the Virtual Machine Connection window. type Proseware in the Server name text box. In the virtual machine. 11. guarantees or conditions. 9. and provided to you by QuickStart Intelligence. double-click the query 00-Setup. The Licensed Content is licensed "as-is. In the Open Project window. click Start. redistribute. In Connect to Server window. Supporting Documentation Table 1: Relationship. In this lab. and then click Other User. or resell this content. click Open.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 • Click Switch User. In Solution Explorer. check the Do not show me this console at logon check box and close the Server Manager window. 15. In the File menu. click All Programs. From the View menu. open the project D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ. 6-27 User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. It is illegal to reprint. click Full Screen Mode. In the Authentication drop-down list box. 12.

Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. redistribute. The Licensed Content is licensed "as-is. guarantees or conditions.2) Table 5: Name Data Type Constraint ApplicationID int IDENTITY(1.1) ApplicantName nvarchar(150) EmailAddress nvarchar(100) ReferenceID uniqueidentifier Comments nvarchar(500) This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. . or resell this content.com or by calling +1 800-785-3448.PrintMediaPlacement Name Data Type Constraint PrintMediaPlacementID int Primary Key MediaOutletID int PlacementDate datetime PublicationDate datetime RelatedProductID int PlacementCost decimal(18.MediaOutlet Name Data Type MediaOutletID int MediaOutletName nvarchar(40) PrimaryContact nvarchar(50) City nvarchar(50) Constraint Table 4: Relationship.QuickStart Intelligence 6-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Table 3: Relationship.

you have created two tables that are structured as Heaps.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-29 Exercise 1: Creating Tables as Heaps Scenario You need to create some new tables to support the relationship management system. You will create two tables that are structured as heaps. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Results: After this exercise. The Licensed Content is licensed "as-is. The main tasks for this exercise are as follows: 1.  Task 1: Review the Requirements • Review the requirements in the supporting documentation for Table 1 and 2. • Create a table based on the supporting documentation for Table 2. and provided to you by QuickStart Intelligence. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Create the Tables in the MarketDev database. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. 2. Review the Requirements.com or by calling +1 800-785-3448.  Task 2: Create the Tables in the MarketDev database • Create a table based on the supporting documentation for Table 1. redistribute.

2. guarantees or conditions. • Create a table based on the supporting documentation for Table 4. The main tasks for this exercise are as follows: 1. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . you have created two tables that have clustered indexes. redistribute. The Licensed Content is licensed "as-is. Review the Requirements. Create the Tables in the MarketDev database." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 6-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 2: Creating Tables with Clustered Indexes Scenario The design documentation also calls for some tables with clustered indexes. or resell this content. Results: After this exercise. You will then create two tables that have clustered indexes. Please report any unauthorized use of this content to piracy@microsoft.  Task 1: Review the Requirements • Review the requirements in the supporting documentation for Table 3 and 4.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence.  Task 2: Create the Tables in the MarketDev database • Create a table based on the supporting documentation for Table 3. It is illegal to reprint.

Call the table Relationship. or resell this content. 2.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-31 Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs.  Task 1: Review the Table Design • Review the table design in the supporting documentation for Table 5.Table_EmailAddress Table • In the supporting documentation for Table5. The main tasks for this exercise are as follows: 1.Table_ApplicationID  Task 4: Create the Relationship.Table_ApplicationID. create a table based on the design with a clustered index on the EmailAddress column.Table_Heap. Heaps (Only if time permits) Scenario A company developer has approached you to decide whether a new table should have a clustered index or not. Call the table Relationship.Table_ApplicationID Table • In the supporting documentation for Table5.Table_EmailAddress. 3. The Licensed Content is licensed "as-is. • Call the table Relationship. Create a table based on the design with no clustered index. Review the Design for Table 5. and provided to you by QuickStart Intelligence. Call the table Relationship.  Task 2: Create the Relationship. You will consider the design.Table_Heap  Task 3: Create the Relationship.com or by calling +1 800-785-3448. It is illegal to reprint. . 6. • Call the table Relationship. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • Call the table Relationship. Create a table based on the design with a clustered index on the ApplicantID column." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Table_ReferenceID. guarantees or conditions. Call the table Relationship. (Note: this may take some minutes to complete.Table_EmailAddress. 4. create a number of alternatives and compare the performance of each against a set of test workloads. Load and execute the workload script. 7. Create a table based on the design with a clustered index on the ReferenceID column. While the script is running. create a table based on the design with a clustered index on the ApplicantID column. You can check where it is up to by viewing the Messages tab. 5. Create a table based on the design with a clustered index on the EmailAddress column. Please report any unauthorized use of this content to piracy@microsoft. review the contents of the script and estimate the proportion of time difference you expect to see in the results). A message is printed as each of the four sections is completed.Table_Heap Table • In the supporting documentation for Table5. redistribute. Compare the performance of each table structure. Insert performance of the table is critical. create a table based on the design with no clustered index.

A message is printed as each of the four sections is completed. • Call the table Relationship. or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. guarantees or conditions. (Note: this may take some minutes to complete. The Licensed Content is licensed "as-is.  Task 6: Load and Execute the Workload Script • Load and execute the workload script.Table_ReferenceID Table • In the supporting documentation for Table5.com or by calling +1 800-785-3448.QuickStart Intelligence 6-32 Implementing a Microsoft® SQL Server® 2008 R2 Database  Task 5: Create the Relationship.  Task 7: Compare Table Performance • Compare the performance of each table structure Results: After this exercise. . and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. review the contents of the script and estimate the proportion of time difference you expect to see in the results). It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. you have created four tables compare performance between clustered and non-clustered indexes. create a table based on the design with a clustered index on the ReferenceID column.Table_ReferenceID. You can check where it is up to by viewing the Messages tab. While the script is running.

The Licensed Content is licensed "as-is. most tables should have a clustered index. and provided to you by QuickStart Intelligence. 3. . redistribute.QuickStart Intelligence Implementing Table Structures in SQL Server 2008 R2 6-33 Module Review and Takeaways Review Questions 1. 2. What is the main problem with uniqueidentifiers used as primary keys? 2. Unless specific circumstances arise. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. Where are newly inserted rows placed when a table is structured as a heap? Best Practices 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. consider avoiding their use throughout the physical implementation of the data model.com or by calling +1 800-785-3448. When using GUID primary keys in the logical data model. It is illegal to reprint. guarantees or conditions. The clustered index may or may not be placed on the table's primary key.

and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is.QuickStart Intelligence 6-34 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. redistribute. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. or resell this content.

redistribute. guarantees or conditions. and provided to you by QuickStart Intelligence.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-1 Module 7 Reading SQL Server 2008 R2 Execution Plans Contents: Lesson 1: Execution Plan Core Concepts 7-3 Lesson 2: Common Execution Plan Elements 7-14 Lesson 3: Working with Execution Plans 7-24 Lab 7: Reading SQL Server Execution Plans 7-31 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. or resell this content.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . It is illegal to reprint.

Work with execution plans This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. Explain the core concepts related to the use of execution plans 2. or resell this content. Describe the role of the most common execution plan elements 3. Objectives After completing this lesson. In this module. It is illegal to reprint. Execution plans show how each step of a query is to be executed. it is important to know how to determine the outcomes of the decisions that SQL Server makes. guarantees or conditions.com or by calling +1 800-785-3448. SQL Server can read the underlying table (which might be structured as a heap or with a clustered index) but it might also choose to use another index. . Please report any unauthorized use of this content to piracy@microsoft. you will be able to: 1. you will learn how to read and interpret execution plans. and provided to you by QuickStart Intelligence. you have seen that one of the most important decisions that SQL Server takes when executing a query.QuickStart Intelligence 7-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview In earlier modules. The Licensed Content is licensed "as-is. you will see how to design additional indexes but before learning this. is how to access the data in any of the tables involved in the query. In the next module.

It is illegal to reprint. what the different types of execution plans are. Explain why execution plans matter Describe the phases that SQL Server passes through while executing a query Explain what execution plans are Describe the difference between actual and estimated execution plans Describe execution contexts Make effective use of the different execution plan formats This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Execution plans can be retrieved in a variety of formats. and how execution plans relate to execution contexts. 3. It is also important to understand the differences between each of these formats and to know when to use each format. Objectives After completing this lesson. you can learn what an execution plan is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Armed with that information. 4. 5.com or by calling +1 800-785-3448. you will be able to: 1. guarantees or conditions. 2. Please report any unauthorized use of this content to piracy@microsoft. redistribute. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-3 Lesson 1 Execution Plan Core Concepts The first steps in working with SQL Server execution plans are to understand why they are so important and to understand the phases that SQL Server passes through when executing a query. 6. or resell this content.

This means that you need to already have an idea of how you expect SQL Server to execute your queries. Execution plans are also commonly referred to as query plans. Why is this happening? • I created an index to make access to the table fast but SQL Server is ignoring the index. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. redistribute.com or by calling +1 800-785-3448. guarantees or conditions. execution plans allow precise answers to be obtained. Many users capture execution plans and then try to resolve the worst performing aspects of a query. It is illegal to reprint. The best use of execution plans however. Execution plans show how SQL Server intends to execute a query or how it did execute a query." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. Why is it ignoring the indexes? These are such common questions yet SQL Server provides tools to help answer the questions. . you will notice questions that occur very regularly: • Why is it that my query takes such a long time to complete? • This query is so similar to another query that executes quickly. or participating in any of the SQL Server related email distribution lists. The ability to interpret these execution plans provides you with the ability to answer the questions above. Why won't it use my index? • I've created an index on every column in the table yet SQL Server still takes the same time to execute my query. Why Execution Plans Matter If you spend any time reading posts in the SQL Server forums or newsgroups. Please report any unauthorized use of this content to piracy@microsoft. was the plan that was used. is in verifying that the plan you expected to be used. yet this query takes much longer to complete.QuickStart Intelligence 7-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Why Execution Plans Matter Key Points Rather than trying to guess how a query is to be performed or how it was performed. You will see more information on doing this in the next module. or resell this content.

SQL Server needs to know exactly which object is being referred to. Please report any unauthorized use of this content to piracy@microsoft. a plan may be cached for later use. and provided to you by QuickStart Intelligence. SELECT * FROM Sales. Question: What is the difference between a statement and a batch? Object Name Resolution In the second phase.Product. SQL Server needs to apply a set of rules to relate the table name "Product" to the intended object. Object names within the statements are located. note that each of the objects in the following code could be completely different in structure and that the names relate to entirely different objects: SELECT * FROM Production. T-SQL Parsing The first phase when executing queries is to check that the statements supplied in the batch follow the rules of the language. or resell this content. SQL Server resolves the names of objects to their underlying object IDs. A key outcome of one of the phases is an execution plan. The Licensed Content is licensed "as-is. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. it might seem that mapping the Product table to its underlying object ID would be easy. redistribute. . Each statement is checked to find any syntax errors.Product. consider that SQL Server supports more than a single object with the same name in a database. consider the following statement: SELECT * FROM Product. through the use of schemas. Once compiled. SELECT * FROM Marketing. While at first glance. For example. guarantees or conditions.com or by calling +1 800-785-3448. For example. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.Product.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-5 Query Execution Phases Key Points SQL Server executes queries in a series of phases.

The more complex a SQL batch is. It may or may not succeed as runtime errors could occur. SQL Server needs to decide how to execute the overall batch. ALTER or DROP. SQL Server does not always find the best possible plan. SQL Server will make decisions about how to access the data contained in each of the tables that are part of each query. the execution engine and storage engine work to execute the plan. . the longer it could take SQL Server to evaluate all the possible plans that could be used to execute the batch. and provided to you by QuickStart Intelligence. Based on the available statistics. On later executions of the batch.QuickStart Intelligence 7-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Query Optimization Once the object IDs have been resolved. or resell this content. It is illegal to reprint. Many simple queries also have trivial plans that are quickly identified. based on its estimate of the cost of resources required to execute the plan. redistribute. There is no need to consider alternate plans for DDL (Data Definition Language) statements. Question: Can you think of a type of query that might lead to a trivial plan? Query Plan Execution Once a plan is found. it may be stored in the Plan Cache. guarantees or conditions. The Licensed Content is licensed "as-is. SQL Server will attempt to reuse execution plans from the Plan Cache." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. Finding the best plan might take longer than executing a less optimal plan. not always desirable.com or by calling +1 800-785-3448. The aim is to find a satisfactory plan in a reasonable period of time. Plan Caching If the plan is considered sufficiently useful. such as CREATE. for certain types of query. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. This is not always possible and. It weighs up the cost of a plan.

. SSMS also calculates a relationship between the costs of each statements. guarantees or conditions. SQL Server uses a cost-based optimizer and each element of the query plan is assigned a cost in relation to the total cost of the batch. Please report any unauthorized use of this content to piracy@microsoft. As part of the plan. Costs cannot be used to estimate execution time. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. The costs that are either estimated or calculated as part of the plan can be interpreted within the plan. redistribute. Costs can only be used to determine if an operation is cheaper or more expensive than another operation.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-7 What is an Execution Plan? Key Points An execution plan is a map that details either how SQL Server would execute a query or how SQL Server did execute a query. These decisions are based on the statistics that are available to SQL Server at the time. SQL Server uses a cost-based optimizer. which is useful where a batch contains more than one statement. Execution Plans Execution plans show the overall method that SQL Server is using to satisfy the requirements of the query. or resell this content. It is illegal to reprint. SQL Server decides the types of operations to be performed and the order that the operations will be performed in.com or by calling +1 800-785-3448. The cost of individual elements can be compared across statements in a single batch but comparisons should not be made between the costs of elements in different batches. Many operations are related to the choice SQL Server makes about how to access data in a table and whether or not available indexes will be used. Question: What resources do you imagine the cost would be based upon? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

You will see an example of this in the next demonstration. redistribute. Estimated Execution Plans Key Points SQL Server can record the plan it used for executing a query. Estimated execution plans are very useful when designing queries or when debugging queries that are suffering from performance problems. When SQL Server executes a plan. . These plans are known as "actual" execution plans. it may also make choices that differ from an estimated plan. One common reason for this is that the batch might include statements that create objects and then access them. on the Query menu. This is commonly related to the available resources (or more likely the lack of available resources) at the time the batch is executed. or resell this content. Note that it is not always possible to retrieve an estimated execution plan. another output tab is created that shows the execution plan that was used. Before it executes a query though. This is calculated without actually executing the query. SQL server has no knowledge of them and cannot create a plan for processing them. This type of plan is known as an "Estimated Execution Plan". there is an option to "Include Actual Execution Plan". In SQL Server Management Studio. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Another option on the Query menu is to "Display Estimated Execution Plan". This asks SQL Server to calculate an execution plan for a query (or batch) based on how it would attempt to execute the query. The Licensed Content is licensed "as-is. Once the results from a query are returned. Estimated Execution Plans It is possible to ask SQL Server to return details of the execution plan used. along with results returned from a query. As the objects do not yet exist. it needs to create an initial plan. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 7-8 Implementing a Microsoft® SQL Server® 2008 R2 Database Actual vs. Actual vs.com or by calling +1 800-785-3448. It is illegal to reprint. guarantees or conditions.

For actual execution plans.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-9 Execution plans include row counts in each data path. The Licensed Content is licensed "as-is. these are based on estimates from the available statistics. and provided to you by QuickStart Intelligence. For estimated execution plans. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. guarantees or conditions. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. both the estimated and actual row counts are shown. . It is illegal to reprint. redistribute.

This means that if a procedure includes a set of procedural logic statements (like the IF statement). or resell this content. This data is held in an object known as an Execution Context. execution contexts are not fully completed when they are created. You should favor set-based logic instead. there needs to be a structure that holds data related to their individual executions of the plan. Branches of the code are "fleshed out" when the code needs to move to the branch. it is useful to avoid too much procedural logic in stored procedures. . guarantees or conditions. redistribute. To maximize performance and minimize memory requirements. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. From a caching reuse point of view.QuickStart Intelligence 7-10 Implementing a Microsoft® SQL Server® 2008 R2 Database What is an Execution Context? Key Points Execution plans are reentrant. and provided to you by QuickStart Intelligence. Execution contexts are cached for reuse in a very similar way to the caching that occurs with execution plans. the execution context retrieved from cache may have gone in a different logical direction and not yet have all the details required." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SQL Server retrieves an execution context from cache if there is one available. Each user needs separate data related to their individual execution of the plan. This means that more than one user can be executing exactly the same execution plan at one time. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. Execution Context Execution plans detail the steps that SQL Server would take (or did take) when executing a batch of statements. When multiple users are executing the plan concurrently. When a user executes a plan.com or by calling +1 800-785-3448.

Please report any unauthorized use of this content to piracy@microsoft. They should not be used in new development work. redistribute.com or by calling +1 800-785-3448. guarantees or conditions. Text based plans are now deprecated. Graphical plans can be rendered from XML plans. Text based execution plans were superseded by XML based plans in SQL Server 2005 and are now deprecated. XML based plans should be used instead. XML plans are also ideal for programmatic access for users creating tools and utilities. Execution Plan Formats Prior to SQL Server 2005.sqlplan filetype and are entirely portable. XML plans can be saved as a . Text based plans can be retrieved from SQL Server by executing the statement: SET SHOWPLAN_TEXT ON. The Licensed Content is licensed "as-is. Note that graphical plans include only a subset of the information that is available from an XML plan. It is illegal to reprint. or resell this content. One challenge with this however. including plans that have been received from other users. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. as XML is relatively easy to consume programmatically in an application. While it is not easy to read XML plans directly. only text-based plans were available and many tools still use this type of plan. and provided to you by QuickStart Intelligence.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-11 Execution Plan Formats Key Points There are three formats for execution plans. Plan Portability SQL Server provided a graphical rendering of execution plans to make reading text based plans easier. further information can be obtained by reading the contents of the XML plan. was that it was very difficult to send a copy of a plan to another user for review. Graphical plans render XML based plans for each of use.

QuickStart Intelligence 7-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Question: What impact does having SSMS associated with the .com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. . guarantees or conditions. redistribute.sqlplan filetype have? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. or resell this content.

5. click Open. Follow the instructions contained within the comments of the script file. 3.sql script file from within Solution Explorer. In the virtual machine. or resell this content. navigate to D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ.ssmssln and click Open. Open the 11 – Demonstration 1A.sql script file. From the File menu. click All Programs. Open and execute the 00 – Setup. click Start.com or by calling +1 800-785-3448. click Project/Solution. type Proseware in the Server name text box and click Connect. Question: How do you explain that such different queries return the same plan? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 2. . redistribute. and provided to you by QuickStart Intelligence. click Microsoft SQL Server 2008 R2. In the Connect to Server window. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. 4. click SQL Server Management Studio." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-13 Demonstration 1A: Viewing Execution Plans in SSMS Key Points In this demonstration you will see how to: • Show an estimated execution plan • Compare execution costs between two queries in a batch • Show an actual execution plan • Save an execution plan Demonstration Steps 1. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. The Licensed Content is licensed "as-is.

In this lesson. you will be able to: • Describe the execution plan elements for table and clustered index scans and seeks • Describe the execution plan elements for nested loops and lookups • Describe the execution plan elements for merge and hash joins • Describe the execution plan elements for aggregations • Describe the execution plan elements for filter and sort • Describe the execution plan elements for data modification This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. appear regularly in execution plans. Objectives After completing this lesson. Please report any unauthorized use of this content to piracy@microsoft. along with the format of the plans. redistribute. and provided to you by QuickStart Intelligence. or resell this content. Certain elements however.com or by calling +1 800-785-3448. it is important to learn to interpret the plans. . The Licensed Content is licensed "as-is.QuickStart Intelligence 7-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Common Execution Plan Elements Now that the role of execution plans is understood." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Execution plans can contain a large number of different types of elements. guarantees or conditions. It is illegal to reprint. you will learn to interpret execution plans and learn about the most common execution plan elements.

consider how the following query would be executed: SELECT * FROM dbo. Please report any unauthorized use of this content to piracy@microsoft.Customer WHERE CustomerID = 12. Table and Clustered Index Scans and Seeks Question: What is the difference between a table scan and a clustered index scan? Table scans are a problem in many queries. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is referred to as a clustered index seek. or resell this content. SQL Server may be able to use the index that supports it to quickly locate the row or rows required. if a Customer table is clustered on a CustomerID column. It is illegal to reprint.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-15 Table and Clustered Index Scans and Seeks Key Points Three execution plan elements relate to reading data from a table. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. Table scans and clustered index scans are essentially identical except that table scans apply to heaps and clustered index scans apply to tables that are structured with clustered indexes. The particular element used depends upon the structure of the table: heap or clustered index and whether the clustered index (if present) is useful in resolving the query. SQL Server does not need to read the entire table and can use the index to quickly locate the correct customer. No doubt this relates to the word "index" in the name of the element. If a query's logic is related to the clustering key for the table. For example.com or by calling +1 800-785-3448. There is a common misconception that table scans are a problem but that clustered index scans are not. redistribute. .

redistribute. Two data paths will enter the nested loop element from the right-hand side as shown in the following screenshot: For each row in the upper input. a Key Lookup was also referred to as a Bookmark Lookup. The difference between a RID Lookup and a Key Lookup is whether the table has a clustered index. In some earlier documentation.com or by calling +1 800-785-3448. a lookup is performed against the bottom input. Note also that in earlier versions of SQL Server 2005. Please report any unauthorized use of this content to piracy@microsoft. Nested Loops and Lookups Nested loop operations are used to implement joins. Key Lookups apply to tables with clustered indexes. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Key Lookup operator was introduced in SQL Server 2005 Service Pack 2. It is illegal to reprint. the Bookmark Lookup was shown as a Clustered Index Seek operator with a LOOKUP keyword associated with it. guarantees or conditions.QuickStart Intelligence 7-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Nested Loops and Lookups Key Points Nested Loops are one of the most commonly encountered operations." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. RID Lookups apply to heaps. They are used to implement join operations and are commonly associated with RID or Key Lookup elements. or resell this content. . The Licensed Content is licensed "as-is.

Note that in the execution plan shown. Nested Loop is the preferred choice whenever the number of rows in the top input source is small when compared with the number of rows in the bottom input source. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. more than half the cost of the query is accounted for by the Key Lookup operator. redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. you will see options for minimizing this cost in some situations. a lookup is similar to reading through an author index and for each book found in the index.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-17 In the physical library analogy. Lookups are often expensive operations as they need to be executed once for every row of the top input source. or resell this content. guarantees or conditions.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. going to collect it from the bookcases. . and provided to you by QuickStart Intelligence. In the next module.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. . Merge Joins Apart from Nested Loop operations in which each row of one table is used to lookup rows from another table. These situations are similar to the problem encountered by Hash Match operations. The same problem would occur if the customer sheets were in postal code order. one order per sheet. one customer to a sheet. right semi joins. or resell this content. guarantees or conditions. It can only be used when the inputs are already in the same order. It is illegal to reprint. left anti semi joins. The process involved is similar to what occurs with a Merge Join operator. right outer joins. how would you perform the merge? The answer depends upon the order of the sheets. If the customer sheets were in customer ID order and the customer order sheets were also in customer ID order. One pile of paper holds details of all your customers. right anti semi joins and unions. left semi joins. If you needed to merge the two piles of paper together so that each customer's sheet was adjacent to his/her orders. and provided to you by QuickStart Intelligence. Merge Joins are more efficient than Hash Matches but require sorted inputs. The other pile of paper holds details of customer orders. Hash Matches Now imagine how you would merge the piles of customers and customer orders if the customers were in customer ID order but the customer orders were ordered by customer order number. There is no easy way to merge the piles. merging the two piles would be easy. Imagine two piles of paper sitting on the floor of your office. it is common to need to join tables where simple lookups are not possible. redistribute.QuickStart Intelligence 7-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Merge and Hash Joins Key Points Merge Joins and Hash Matches are other forms of join operations.com or by calling +1 800-785-3448. Merge Joins can be used to implement a variety of join types such as left outer joins.

QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-19 Hash Matches are using a relatively "brute force" method of joining. In the analogy with the piles of paper. The other input is processed based on the same algorithm. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. or resell this content. ten buckets would be created. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. One input is broken into a set of "hash buckets" based on an algorithm. the algorithm could be to obtain the first digit of the customer ID. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. With this algorithm.com or by calling +1 800-785-3448. . The Licensed Content is licensed "as-is. Although it may not be possible to always avoid Hash Matches in query plans. and provided to you by QuickStart Intelligence. their presence is often an indication of a lack of appropriate indexing on the underlying tables. redistribute.

It is illegal to reprint. One option would be to first sort all the customer orders by customer ID.QuickStart Intelligence 7-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Aggregations Key Points There are two types of Aggregate operator: Stream Aggregate and Hash Match Aggregate. and provided to you by QuickStart Intelligence. . Aggregations Imagine being asked to count how many orders are present for each customer based on a list of customer orders. Another alternative is to process the input via a hashing algorithm like the one used for Hash Match operations. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. or resell this content. If the customer orders are already in customer ID order. This is the equivalent of a Stream Aggregate operation.com or by calling +1 800-785-3448. performing the calculations is much more complex. then to count all the customer orders for each customer ID. the answer depends on the order that the customer orders are being held in. Please report any unauthorized use of this content to piracy@microsoft. However. if the aggregate being calculated is based on a different attribute of the customer orders than the attribute they are sorted by. Stream Aggregate operations are very efficient. redistribute. How would you perform this operation? Similar to the discussion on Merge Joins and Hash Matches. This is what SQL Server does when using a Hash Match Aggregate operation. The presence of these operations in a query plan is often (but not always) an indication of a lack of appropriate indexing on the underlying table. then performing the count (or other aggregation) is very easy.

Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-21 Filter and Sort Key Points Filter operations implement WHERE clause predicates or HAVING clause predicates. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. A Filter operation can be used to implement this limit. Question: What would affect the cost of a sort operation? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. a Sort operation could be used to sort rows before they are passed to other operations such as Merge Joins or for performing DISTINCT or UNION operations. Sort operations are often used to implement ORDER BY clauses in queries but they have other uses. For example.com or by calling +1 800-785-3448. Filter and Sort WHERE clauses and HAVING clauses limit the rows returned by a query. Not all data needs to be output in a specific order. or resell this content. Unnecessary ORDER BY operations should be avoided. Sorting data rows can be an expensive operation. guarantees or conditions. . Filter operations are typically low cost and are processed as the data passes through the element. Data rows from the input are only passed to the output if they meet specified filter criteria based on the predicates in those clauses." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Sort operations sort input data.

UPDATE and DELETE operations are used to present the outcome of underlying T-SQL data modification statements. It is illegal to reprint. UPDATE and DELETE operations.QuickStart Intelligence 7-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Data Modification Key Points INSERT. T-SQL MERGE statements can be implemented by combinations of INSERT. guarantees or conditions. Data Modification The purpose of these operations will usually be self-evident but what might be obvious is the potential cost of these operations or the complexity that can be involved with them. redistribute. . Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. A T-SQL INSERT. The Licensed Content is licensed "as-is. or resell this content. and provided to you by QuickStart Intelligence. UPDATE or DELETE statement might involve much more than the related execution plan operation." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Question: Can you think of an example where an INSERT statement in T-SQL need to perform more than an INSERT operation in an execution plan? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

click Start. click Microsoft SQL Server 2008 R2. 2.ssmssln and click Open.com or by calling +1 800-785-3448. type Proseware in the Server name text box and click Connect. From the File menu. • Open and execute the 00 – Setup. In the Connect to Server window.sql script file. guarantees or conditions. The Licensed Content is licensed "as-is.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-23 Demonstration 2A: Common Execution Plan Elements Key Points In this demonstration you will see queries that demonstrate the most common execution plan elements. Open the 21 – Demonstration 2A. or resell this content. Demonstration Steps 1. click Project/Solution. click Open. It is illegal to reprint. click All Programs. . 3. and provided to you by QuickStart Intelligence. redistribute. Follow the instructions contained within the comments of the script file." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • In the virtual machine. click SQL Server Management Studio.sql script file from within Solution Explorer. navigate to D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Question: Why is the plan for a simple delete so complex? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft.

you will see a variety of ways to capture plans and explore the criteria by which SQL Server decides whether or not to reuse plans. You will also see how they are used.com or by calling +1 800-785-3448.QuickStart Intelligence 7-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Working with Execution Plans Now that you understand the importance of execution plans and are familiar with common elements contained within the plans. Objectives After completing this lesson. It is illegal to reprint. In this lesson. . Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. or resell this content. consideration needs to be given to the different ways that the plans can be captured. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. SQL Server exposes a number of dynamic management views (DMVs) that can be used to explore query plan reuse. When working with execution plans. and provided to you by QuickStart Intelligence. you will be able to: • Implement methods for capturing plans • Explain how SQL Server decides whether or not to reuse existing plans when re-executing queries • Use execution plan related DMVs This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

redistribute. This can be very useful when a user asks about a problem occurring last Tuesday morning rather than at the time the problem is occurring. SQL Server Activity Monitor can display the results of querying these DMVs. or resell this content. The SQL Server Data Collection system collects information from the DMVs. The Licensed Content is licensed "as-is. SQL Profiler has an event: Performance events > Showplan XML that can be used to add a column to a trace. Unlike Activity Monitor which shows recent expensive queries. Dynamic management views provide information about recent expensive queries and missing indexes that were detected by SQL Server when creating the plan. Other options exist for capturing plans. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. The same options have been added to Visual Studio 2010 (VS). The trace will then include the actual execution plans. It is illegal to reprint. The overall performance of the system could be degraded.com or by calling +1 800-785-3448. to load queries into SSMS or VS for analysis. It is not always possible however. uploads it to a central database and provides a series of reports based on the data.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-25 Methods for Capturing Plans Key Points Earlier in this module you saw how to capture execution plans using SQL Server Management Studio. and provided to you by QuickStart Intelligence. Methods for Capturing Execution Plans SQL Server Management Studio (SSMS) can be used to obtain both estimated and actual execution plans. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Often you will need to analyze systems that are in production or to analyze queries generated by third party applications that you have no direct access to the source code of. This can help avoid the need to have two tools open when performing development against SQL Server. Caution needs to be taken with using this option as a very large trace output could be generated very quickly if appropriate filtering is not used." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the data collection system can show historical entries.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Follow the instructions contained within the comments of the script file. navigate to D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ.sql script file. redistribute.sql script file from within Solution Explorer. click All Programs.QuickStart Intelligence 7-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Capturing Plans in Activity Monitor Key Points In this demonstration you will see how to use Activity Monitor to view recent expensive queries. Open the 31 – Demonstration 3A. click Project/Solution. click Microsoft SQL Server 2008 R2. type Proseware in the Server name text box and click Connect. It is illegal to reprint. In the Connect to Server window. • Open and execute the 00 – Setup. From the File menu. click SQL Server Management Studio. click Open.ssmssln and click Open. guarantees or conditions. • In the virtual machine. or resell this content. . 3. Question: What could cause an expensive query to be removed from the Activity Monitor window? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. click Start. and provided to you by QuickStart Intelligence. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Please report any unauthorized use of this content to piracy@microsoft. 2. Demonstration Steps 1.

Please report any unauthorized use of this content to piracy@microsoft. You will see a further discussion on this "parameter sniffing" issue in later modules. This means that SQL Server would perform better if it reconsidered how to execute the query. It is illegal to reprint. The two main reasons for this are: • Correctness (changes to SET options. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. When memory resources become tight. guarantees or conditions. SQL Server may eventually decide to evict them from the cache and recompile the queries. However. If the value of the FromCustomerID parameter was the same as the value of the ToCustomerID parameter. to estimate its "value". redistribute. Re-Executing Queries Reusing query plans avoids the overhead of compiling and optimizing the queries.) • Optimality (data has been modified enough that a new plan should be considered) SQL Server assigns a cost to each plan that is cached. Usefulness of Cached Plans Even for cached plans.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-27 Re-Executing Queries Key Points SQL Server attempts to reuse execution plans where possible. . The decision to evict a plan from memory is based on this cost value and on whether or not the plan has been reused recently. a later execution of that query where a large number of customers were requested would not be selective. schema changes. For example. and thus generate a new plan. an index seek based on the CustomerID might be highly selective.com or by calling +1 800-785-3448. however." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. or resell this content. While this is often desirable. and provided to you by QuickStart Intelligence. SQL Server will need to decide which plans are the most useful to keep. Some queries. the reuse of existing plans can be counterproductive to performance. The value is a measure of how expensive the execution plan was to generate. etc. perform poorly when executed with a plan that was generated for a different set of parameters. consider a query with FromCustomerID and ToCustomerID parameters.

Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. and provided to you by QuickStart Intelligence.QuickStart Intelligence 7-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Options are available to force compilation behavior of code but they should be used sparingly and where necessary. guarantees or conditions. redistribute. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. You will see a further discussion on this issue in a later module. or resell this content.

including system and user sessions sys. Several of these views are useful when investigating execution plans. guarantees or conditions.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. or resell this content. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.dm_exec_cached_plan_depend ent_objects() Details of dependent objects for those plans This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Most DMV values are reset whenever the server is restarted.dm_exec_sql_text() Provides the ability to find the T-SQL code being executed for a request sys. Some are reset more often.dm_exec_query_plan() Provides the ability to find the execution plan associated with a request sys.dm_exec_requests Associated with a session and providing one row per currently executing request sys.dm_exec_query_stats Query statistics sys.dm_exec_sessions One row per session. View Description sys. redistribute. .dm_exec_cached_plans Details of cached query plans sys.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-29 Execution Plan Related DMVs Key Points Dynamic Management Views provide insight into the internal operations of SQL Server. and provided to you by QuickStart Intelligence.dm_exec_connections One row per user connection to the server sys.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click SQL Server Management Studio. In the Connect to Server window. click Microsoft SQL Server 2008 R2. click All Programs.sql script file. Open the 32 – Demonstration 3B. . and provided to you by QuickStart Intelligence.ssmssln and click Open. Please report any unauthorized use of this content to piracy@microsoft. From the File menu. 2. click Open.sql script file from within Solution Explorer. or resell this content. Demonstration Steps 1.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. type Proseware in the Server name text box and click Connect. • Open and execute the 00 – Setup. click Start. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. guarantees or conditions. Question: No matter how quickly you execute the command to check the cache after you clear it. It is illegal to reprint. click Project/Solution. 3. navigate to D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ. Follow the instructions contained within the comments of the script file. Why? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute.QuickStart Intelligence 7-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3B: Viewing Cached Plans Key Points In this demonstration you will see how to view cached execution plans. you would not see it empty. • In the virtual machine.

Wait for the revert action to complete. On the host computer. redistribute. you must complete the following steps: 1. Before you begin the lab. . In Virtual Machine Connection window. wait until the Press CTRL+ALT+DELETE to log on message appears. In the Virtual Machines list. click the Ctrl-Alt-Delete menu item." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the Virtual Machines list. click on the Revert toolbar icon. If you are prompted to confirm that you want to revert. and then click Hyper-V Manager. In the Virtual Machine Connection window. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-31 Lab 7: Reading SQL Server Execution Plans Lab Setup For this lab. • In the Virtual Machine Connection window. click Start. 2.com or by calling +1 800-785-3448. • Right-click 623XB-MIA-DC and click Start. The Licensed Content is licensed "as-is. wait until the Press CTRL+ALT+DELETE to log on message appears. • In the Virtual Machine Connection window. and provided to you by QuickStart Intelligence. 7. 5. 6. if the virtual machine 623XB-MIA-DC is not started: 4. • Right-click 623XB-MIA-SQL and click Connect. you will use the available virtual machine environment. or resell this content. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. point to Administrative Tools. click Revert. and then close the Virtual Machine Connection window. 3. Maximize the Hyper-V Manager window. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. if the user is not already logged on: • On the Action menu. guarantees or conditions. • Right-click 623XB-MIA-DC and click Connect. It is illegal to reprint.

14. User name: AdventureWorks\Administrator Password: Pa$$w0rd 8. Execution plans can contain many types of elements. 9.QuickStart Intelligence 7-32 Implementing a Microsoft® SQL Server® 2008 R2 Database • Click Switch User. In the virtual machine. In the Authentication drop-down list box. In the Open Project window. 11. select Windows Authentication and click Connect. check the Do not show me this console at logon check box and close the Server Manager window. or resell this content. To take this learning further. When the query window opens. click Full Screen Mode." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Log on using the following credentials: i. 10. . 15. In Connect to Server window. If the Server Manager window appears. redistribute. From the View menu. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click Start. guarantees or conditions. It is illegal to reprint. you need to have a way to view how these indexes are used. click Microsoft SQL Server 2008 R2. you will learn to use execution plans to compare the cost of statements in multi-statement batches. and provided to you by QuickStart Intelligence. ii. you will learn to view both estimated and actual execution plans. In the first exercise. If time permits. you will learn to identify the most common plan elements and see how statements lead to these elements being used. Lab Scenario You have been learning about the design of indexes. 12. and click Project/Solution.com or by calling +1 800-785-3448. You regularly find yourself trying to decide between different ways of structuring SQL queries. double-click the query 00-Setup. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. click All Programs. In the second exercise. open the project D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ. You are concerned that you aren’t always choosing the highest-performing options. In the File menu. and then click Other User.sql.ssmssln. click Execute on the toolbar. 13. and click SQL Server Management Studio. In Solution Explorer. in the Virtual Machine Connection window. click Open. type Proseware in the Server name text box.

5. 4. redistribute. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448.1. View the estimated execution plan for script 7. Load the test script. Please report any unauthorized use of this content to piracy@microsoft. • Click on the returned XML and view the execution plan.3. 2.1  Task 3: View the estimated execution plan for script 7.5 • Execute script 7. The main tasks for this exercise are as follows: 1.  Task 1: Load the test script • Load the 51 – Lab Exercise 1. then execute script 7.4 and note the returned plan  Task 7: Review the execution plans currently cached in memory using script 7. • Change the database context to AdventureWorks2008R2.4 • Request an estimated plan for script 7.5 to view the plans currently cached in memory This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 7. Generate the actual execution plan for script 7. guarantees or conditions. Review the actual execution plan for script 7.5.2 using SHOWPLAN_XML.4.  Task 6: Review the actual execution plan for script 7.2 in SQL Server Query Analyzer.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-33 Exercise 1: Actual vs.3 • Enable the option to include actual plans. Generate an estimated execution plan for script 7.4. and provided to you by QuickStart Intelligence. • Choose Show Execution Plan XML.sql script from Solution Explorer. 3. Review the execution plans currently cached in memory using script 7. or resell this content. • Note the inability to create an estimated plan the reason is shown in the messages tab.  Task 2: Generate an estimated execution plan for script 7.  Task 5: Try to generate an estimated execution plan for script 7.4 6.1 • Generate an estimated plan for script 7. you will learn to view both estimated and actual execution plans.4 • Execute script 7.2 using SHOWPLAN_XML • Execute script 7. • Right-click in the whitespace in the plan.3.  Task 4: Generate the actual execution plan for script 7. Estimated Plans Scenario In the first exercise." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Briefly review the XML. It is illegal to reprint. Try to generate an estimated execution plan for script 7. • Close the XML window and the execution plan window. . Note the returned execution plan tab and note that the plan is identical from the previous task.

The Licensed Content is licensed "as-is. It is illegal to reprint. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 7-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Results: After this exercise. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. .com or by calling +1 800-785-3448. redistribute. guarantees or conditions. you have reviewed various actual and estimated query plans.

Please report any unauthorized use of this content to piracy@microsoft.9.sql script from Solution Explorer. Explain the actual execution plan from script 7. Explain the actual execution plan from script 7. You will learn to identify the most common plan elements and see how statements lead to these elements being used. Explain the actual execution plan from script 7.9 6.13 10.7.8 • Execute script 7.9 • Execute script 7.6. • Explain the plan returned based upon the existing table structure. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The main tasks for this exercise are as follows: 1.8 5.  Task 2: Explain the actual execution plan from script 7.14  Task 1: Load the test script • Load the 61 – Lab Exercise 2. Explain the actual execution plan from script 7. The Licensed Content is licensed "as-is. guarantees or conditions. Explain the actual execution plan from script 7.10 7. Explain the actual execution plan from script 7.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-35 Exercise 2: Identify Common Plan Elements Scenario Execution plans can contain many types of elements. • Select the option to include actual execution plans from the Query menu.6 • Execute script 7. or resell this content.8.7 4.10 • Execute script 7. It is illegal to reprint. • Explain the plan returned based upon the existing table structure.6 3. .  Task 5: Explain the actual execution plan from script 7. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Explain the actual execution plan from script 7. • Explain the plan returned based upon the existing table structure. • Explain the plan returned based upon the existing table structure.11 8.  Task 6: Explain the actual execution plan from script 7.12 9.  Task 3: Explain the actual execution plan from script 7.com or by calling +1 800-785-3448. Load the test script 2. • Change the database context to AdventureWorks2008R2. Explain the actual execution plan from script 7.  Task 4: Explain the actual execution plan from script 7.10.7 • Execute script 7. • Explain the plan returned based upon the existing table structure. Explain the actual execution plan from script 7. and provided to you by QuickStart Intelligence.

14. or resell this content. • Compare the plan to the one returned by script 7." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448.11. guarantees or conditions.  Task 9: Explain the actual execution plan from script 7. Also note the green Missing Index warning.  Task 10: Explain the actual execution plan from script 7. • Note the difference in this plan from the plan for script 7. redistribute.13.10. you will have analyzed the most common plan elements returned from queries.11 • Execute script 7. and provided to you by QuickStart Intelligence. • Suggest a reason for the difference in plan. • Compare the plan to the one returned by script 7. Results: After this exercise.12.12. • Suggest a reason for the difference in plan.12 • Execute script 7. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.12. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence 7-36 Implementing a Microsoft® SQL Server® 2008 R2 Database  Task 7: Explain the actual execution plan from script 7.13 • Execute script 7. • Explain the plan returned based upon the existing table structure.14 • Execute script 7. where the queries are almost identical. where the queries are very similar. .  Task 8: Explain the actual execution plan from script 7. The Licensed Content is licensed "as-is.

In particular. explain the relationship between the two query plans. • Explain the execution plan that is returned. and provided to you by QuickStart Intelligence. Explain the actual execution plan from script 7. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • Select the option to include actual execution plans from the Query menu.QuickStart Intelligence Reading SQL Server 2008 R2 Execution Plans 7-37 Challenge Exercise 3: Query Cost Comparison (Only if time permits) Scenario You regularly find yourself trying to decide between different ways of structuring SQL queries.com or by calling +1 800-785-3448.  Task 1: Load the test script • Load the 71 – Lab Exercise 3. You will learn to use execution plans to compare the cost of statements in multi-statement batches. redistribute. Results: After this exercise. guarantees or conditions. The Licensed Content is licensed "as-is.15 • Execute script 7. Load the test script 2. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. • Change the database context to AdventureWorks2008R2. you have used execution plans to compare the cost of statements in multistatement batches.15.sql script from Solution Explorer.  Task 2: Explain the actual execution plan from script 7. The main tasks for this exercise are as follows: 1.15 as a single batch (both queries should be executed together). . You are concerned that you aren’t always choosing the highest-performing options. Please report any unauthorized use of this content to piracy@microsoft.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. What is the difference between a graphical execution plan and an XML execution plan? 2. redistribute. It is illegal to reprint. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . make sure the trace is filtered to reduce the number of events being captured.QuickStart Intelligence 7-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. Avoid capturing execution plans for large numbers of statements when using SQL Profiler. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. If you need to capture plans using Profiler. Give an example of why a T-SQL DELETE statement could have a complex execution plan? Best Practices 1.

and provided to you by QuickStart Intelligence. .QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-1 Module 8 Improving Performance through Nonclustered Indexes Contents: Lesson 1: Designing Effective Nonclustered Indexes 8-3 Lesson 2: Implementing Nonclustered Indexes 8-10 Lesson 3: Using the Database Engine Tuning Advisor 8-18 Lab 8: Improving Performance through Nonclustered Indexes 8-25 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. It is illegal to reprint.com or by calling +1 800-785-3448. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is.

you saw how to structure tables for efficiency. In previous modules. guarantees or conditions. Objectives After completing this lesson. redistribute. you will see how nonclustered indexes have the potential to significantly enhance the performance of your applications and learn to use a tool that can help you design these indexes appropriately. The Licensed Content is licensed "as-is. It is illegal to reprint. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will be able to: • • • Design effective nonclustered indexes Implement nonclustered indexes Use the database engine tuning advisor to design indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. In this module.QuickStart Intelligence 8-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview The biggest improvements in database query performance on most systems come from appropriate use of indexing. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. including the option of creating a clustered index on the table.com or by calling +1 800-785-3448.

you will be able to: • • • • Describe the concept of nonclustered indexes Explain how SQL Server structures nonclustered indexes when the underlying table is organized as a heap Explain how SQL Server structures nonclustered indexes when the underlying table is organized with a clustered index Obtain information about indexes that have been created This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. The Licensed Content is licensed "as-is. you will learn how SQL Server structures nonclustered indexes and how they can provide performance improvements for your applications." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . It is illegal to reprint. In this module.com or by calling +1 800-785-3448.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-3 Lesson 1 Designing Effective Nonclustered Indexes Before you start to implement nonclustered indexes. You will also see how to find information about the indexes that have been created. and provided to you by QuickStart Intelligence. you need to design them appropriately. Objectives After completing this lesson. redistribute.

and provided to you by QuickStart Intelligence. nonclustered indexes are indexes that point back to the bookcases. by publisher. They provide alternate ways to look up the information in the library. These additional indexes are called nonclustered indexes. The Licensed Content is licensed "as-is. For example. This means that nonclustered indexes that are created at one point in time may need to be altered or even dropped at a later point in time. Ongoing Review An application's data access patterns may change over time. . to continue to achieve high performance levels. Whenever updates to key columns from the nonclustered index or updates to clustering keys on the base table are made. or resell this content. and are used to improve the performance of important queries. Each additional index that is added to a table increases the work that SQL Server might need to perform when modifying the data rows in the table." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Nonclustered Indexes A table can have up to 999 non-clustered indexes. the nonclustered indexes need to be updated as well. redistribute. These indexes are assigned index IDs greater than 1. guarantees or conditions.com or by calling +1 800-785-3448. particularly in enterprises where ongoing development work is being performed on the applications. It is illegal to reprint. Physical Analogy Continuing our library analogy. they might allow access by author. Non-clustered indexes can be defined on a table regardless of whether the table uses a clustered index or a heap. Care must be taken to balance the number of indexes created against the overhead that they introduce. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. They can also be composite indexes where you could find an index by release date within the entries for each author. etc. Please report any unauthorized use of this content to piracy@microsoft. by release date.QuickStart Intelligence 8-4 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a Nonclustered Index? Key Points You have seen how tables can be structured as heaps or have clustered indexes. Additional indexes can be created on the tables to provide alternate ways to rapidly locate required data. This impacts the data modification performance of the system.

Once an author is found in the index. . and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Shelf 3. Physical Analogy Based on the library analogy. By default. guarantees or conditions. SQL Server obtains Row ID pointers in the leaf level of the index and uses these pointers to directly access all required data pages. or resell this content. Note that it would be a pointer to the exact location of the book. The Licensed Content is licensed "as-is.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-5 Nonclustered Indexes Over Heaps Key Points Nonclustered indexes have the same B-tree structure as clustered indexes. redistribute. Nonclustered Indexes Over Heaps After traversing the structure of the nonclustered index. Multiple nonclustered indexes can be created on a table regardless of whether the table is structured as a heap or if the table has a clustered index. but in the nonclustered index. Question: What is an upside of having the indexes point directly to RowIDs? Question: What is the downside of having multiple indexes pointing to data pages via RowID? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. no data apart from the keys is stored at the leaf level. When the underlying table is structured as a heap.com or by calling +1 800-785-3448. the leaf level of a nonclustered index holds Row ID pointers instead of data. Book 12". Please report any unauthorized use of this content to piracy@microsoft. the data and the index are stored separately. the entry in the index for each book would have an address like "Bookcase 4. a nonclustered index over a heap is like an author index pointing to books that have been stored in no particular order within the bookcases.

QuickStart Intelligence 8-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Nonclustered Indexes Over Clustered Indexes Key Points You have seen that the base table could be structured with a clustered index instead of a heap. redistribute. a nonclustered index over a clustered index is like having an author index built over a library where the books are all stored in ISBN order. Please report any unauthorized use of this content to piracy@microsoft. Nonclustered Indexes Over Clustered Indexes After traversing the structure of the nonclustered index. Instead. It is illegal to reprint. It then uses these keys to traverse the structure of the clustered index to locate the required data pages." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Physical Analogy In the library analogy. the leaf level of the nonclustered index also needs to hold the uniqueifier value for the data rows. guarantees or conditions. While SQL Server could have been designed so that nonclustered indexes still pointed to Row IDs. rather than the physical location of the books. Note that two sets of index traversal occur. and provided to you by QuickStart Intelligence. When the required author is found in the author index. The Licensed Content is licensed "as-is. SQL Server obtains clustering keys from the leaf level of the index. the entry in the index provides details of the ISBNs for the required books.com or by calling +1 800-785-3448. If the bookcases need to be rearranged (for example due to other rows being modified). These ISBNs are then used to locate the books within the bookcases. . it was not designed that way. or resell this content. no changes need to be made to the author index as it is only providing keys that are used for locating the books. Question: What is the downside of holding clustering keys in the leaf nodes of a nonclustered index instead of RowIDs? Question: What is the upside of holding clustering keys in the leaf nodes of a nonclustered index instead of RowIDs? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. If the clustered index was not a unique clustered index. the leaf levels of a nonclustered index contain the clustering keys for the base table.

QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-7 Methods for Obtaining Index Information Key Points You might require information about existing indexes before you create. Object Explorer lists the indexes associated with tables. Each index has a property page that details the structure of the index and of its operational. SQL Server 2008 provides many ways to obtain information about indexes.indexes Index type. redistribute. and provided to you by QuickStart Intelligence. guarantees or conditions. The Licensed Content is licensed "as-is. and sort order (ASC or DESC). SQL Server Management Studio SQL Server Management Studio (SSMS) offers a variety of ways to obtain information about indexes. This includes indexes that have been created by users and those indexes that relate to PRIMARY KEY and UNIQUE constraints in cases where indexes have been created by SQL Server to support those constraints. . type (key or nonkey). Please report any unauthorized use of this content to piracy@microsoft. Some of the more useful views are shown in the following table: System View Notes sys. System Stored Procedures and Catalog Views The sp_helpindex system stored procedure returns details of the indexes created on a specified table. SQL Server provides a series of catalog views that provide information about indexes. Many of these reports relate to index structure and usage. filegroup or partition scheme ID. or resell this content. or remove an index. sys." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint.index_columns Column ID.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. position within the index. SSMS also includes a set of prebuilt reports that show the state of a database. and the current setting of index options that are stored in metadata. modify. usage and physical layout characteristics.

Some of the most useful views and functions are shown in the following table: View Notes sys. redistribute. INDEXPROPERTY Index type. sys.stats Statistics associated with a table. sys. including statistic name and whether it was created automatically or by a user.stats_columns Column ID associated with the statistic. and current setting of index options that are stored in metadata." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Dynamic Management Views SQL Server provides a series of dynamic management objects with useful information about the structure and usage of indexes. and provided to you by QuickStart Intelligence. In the next demonstration. Some of the more useful functions are shown in the following table: Function Notes INDEXKEY_PROPERTY Index column position within the index and column sort order (ASC or DESC). It is illegal to reprint.QuickStart Intelligence 8-8 Implementing a Microsoft® SQL Server® 2008 R2 Database System View Notes sys.dm_db_index_physical_stats Index size and fragmentation statistics. guarantees or conditions.dm_db_index_usage_stats Index usage statistics by query type.com or by calling +1 800-785-3448. or resell this content. . INDEX_COL Name of the key column of the specified index. you will see examples of many of these methods for obtaining information on indexes. sys. System Functions SQL Server provides a set of functions that provide information about the structure of indexes. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft.dm_db_index_operational_stats Current index and table I/O statistics. number of levels. The Licensed Content is licensed "as-is.

click All Programs. 4. Open and execute the 00 – Setup. . 3. From the File menu. Open the 11 – Demonstration 1A. In the virtual machine.sql script file from within Solution Explorer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-9 Demonstration 1A: Obtaining Index Information Key Points In this demonstration you will see several ways to view information about indexes. and provided to you by QuickStart Intelligence. Demonstration Steps 1. type Proseware in the Server name text box and click Connect. The Licensed Content is licensed "as-is.sql script file.com or by calling +1 800-785-3448. In the Connect to Server window. redistribute. Question: What would be another way to find information about the physical structure of indexes? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Open. click Microsoft SQL Server 2008 R2. 5. Please report any unauthorized use of this content to piracy@microsoft. click SQL Server Management Studio. click Start. navigate to D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ. Follow the instructions contained within the comments of the script file. or resell this content. click Project/Solution.ssmssln and click Open. It is illegal to reprint. 2.

you have seen how Lookup functions used with Nested Loop execution plan elements can be very expensive operations. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. In this module.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. you will see options for alleviating these costs. . redistribute. or resell this content. In earlier modules. You will also see how to alter or drop nonclustered indexes and how filtered indexes can reduce the overhead associated with some nonclustered indexes. it is important to learn how nonclustered indexes are implemented.QuickStart Intelligence 8-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Implementing Nonclustered Indexes Now that you have learned how nonclustered indexes are structured. Objectives After completing this lesson. guarantees or conditions. you will be able to: • • • • • Create nonclustered indexes Describe the performance impact of Lookup operations as part of Nested Loops in execution plans Use INCLUDE Clause to create covering indexes Drop or alter nonclustered indexes Use filtered indexes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

Query performance can be enhanced by using composite indexes. It is illegal to reprint. However. . the clustered index (if the table needs one) should be created prior to the nonclustered indexes. Many standards for naming indexes exist. The majority of useful nonclustered indexes in business applications are composite indexes. guarantees or conditions. one suggested standard is to include in the name of the index the date of creation and a reference to documentation that describes why the index was created." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-11 Creating Nonclustered Indexes Key Points Nonclustered indexes are created with the CREATE INDEX statement. A common error is to create single column indexes on many columns of a table. wide keys increase the storage requirements of an index. These indexes are rarely useful. especially when users regularly search for information in more than one way. Composite Nonclustered Indexes A composite index specifies more than one column as the key value. If an index is created only to enhance performance.com or by calling +1 800-785-3448. or resell this content. Keeping documentation that explains why indexes were created avoids that confusion. along with strong opinions on which of the standards is best. By default. the CREATE INDEX statement creates nonclustered indexes rather than clustered indexes when you do not specify which type of index you require. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Database administrators are often hesitant to remove indexes when they do not know why those indexes were created. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. rather than as part of the initial schema of an application. It is important to choose an appropriate naming scheme for indexes. The Licensed Content is licensed "as-is. The important thing is to choose a standard and follow it consistently. Wherever possible. Otherwise SQL Server needs to rebuild all nonclustered indexes while creating the clustered index. Creating Nonclustered Indexes Creating a Nonclustered index requires supplying a name for the index. redistribute. the name of the table to be indexed and the columns that need to be used to create the index key.

QuickStart Intelligence 8-12 Implementing a Microsoft® SQL Server® 2008 R2 Database In composite indexes. guarantees or conditions. The Licensed Content is licensed "as-is. Ascending is the default order. in the absence of any other requirements. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. . the ordering of key columns is important and that the most selective column should be specified first. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. Each column that makes up the key can be specified as ASC (ascending) or DESC (descending). or resell this content.

or resell this content. The Licensed Content is licensed "as-is. this is equivalent to looking up an author in an index and for each entry found. The key lookups are estimated at 95% of the cost of executing the query. Please report any unauthorized use of this content to piracy@microsoft. This lookup process can be very expensive. running over to the bookcase to retrieve the books pointed to by the index. Performance Impact of Lookups in Nested Loops In the example shown on the slide. It is illegal to reprint. However. for each entry found.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-13 Performance Impact of Lookups in Nested Loops Key Points Nonclustered indexes can be very useful when needing to find specific data based on the key columns of the index." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute.com or by calling +1 800-785-3448. Question: How selective would you imagine a query needs to be before SQL Server will decide to ignore the index and just scan the data? Question: Is there any situation where there is no need for the lookups? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. There is a point at which the effort of doing this is not worthwhile and it is quicker to scan the entire library. SQL Server needs to then use the values from the leaf level of the index (either clustering keys or rowid) to look up the data rows from the base table. note that the percentage cost breakdown. and provided to you by QuickStart Intelligence. In the library analogy. . guarantees or conditions.

it was common for DBAs or developers to create indexes with a large number of columns.com or by calling +1 800-785-3448. The index structure in other levels is unaffected by these included columns. if an index was constructed on PublisherID. For example. doing so could be counterproductive. guarantees or conditions. only to help with covering queries.QuickStart Intelligence 8-14 Implementing a Microsoft® SQL Server® 2008 R2 Database INCLUDE Clause Key Points In earlier versions of SQL Server (prior to 2005). . in the library analogy. or resell this content. redistribute. INCLUDE Clause Adding columns to the key of an index adds a great deal of overhead to the index structure. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. to attempt to "cover" important queries. the order of the columns within the clause is not relevant. Question: For an index to cover a single table query. The INCLUDE clause was introduced to make the creation of covering indexes easier. which columns would need to be present in the index? Performance Impacts Covering indexes can have a very positive performance impact on the queries that they are designed to support. For this reason. it is important to decide which queries are most important and to aim to cover only those queries. the index would internally be sorted by Title for no benefit. A further issue is the limitation of 16 columns and 900 bytes for an index. However." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. ReleaseDate and Title. as this limits the ability to add columns to index keys when trying to cover queries. while it would be possible to create an index to cover most queries. Covering a query avoids the need for lookup operations and can greatly increase the performance of queries. Please report any unauthorized use of this content to piracy@microsoft. SQL Server 2005 introduced the ability to include one or more columns (up to 1024 columns) only at the leaf level of the index. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. They are included. It is illegal to reprint. Each index that is added to a table can negatively impact the performance of data modifications on the table. If more than one column is listed in an INCLUDE clause.

The Licensed Content is licensed "as-is. The rebuild command example shown in the example on the slide uses the ONLINE = ON option. It is illegal to reprint. This is only supported on Enterprise or higher editions of SQL Server. it is re-enabled by rebuilding the index. Limitations on Altering Indexes While it might at first glance seem that an index could be restructured via the ALTER INDEX statement. Once an index is disabled." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. . then those indexes need to be dropped by dropping the constraint instead.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-15 Dropping or Altering Nonclustered Indexes Key Points Only indexes created via CREATE INDEX can be dropped via DROP INDEX. guarantees or conditions. The ability to perform online index operations is one of the key reasons for purchasing these editions as many organizations no longer have available time windows for index maintenance operations.com or by calling +1 800-785-3448. an index is being disabled. Changing the columns that make up the key. If an index has been created by SQL Server to support a PRIMARY KEY or UNIQUE constraint. and provided to you by QuickStart Intelligence. In the example shown in the slide. These changes can be implemented by using the CREATE INDEX statement with the WITH DROP_EXISTING option. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. altering the sort order of the columns or changing settings such as FILLFACTOR and PADINDEX is not permitted. or resell this content.

even though most entries in the index would never be used. . SQL Server includes an entry for every row in a table at the leaf level of each index. This is not always desirable. Standard indexes created in this situation would contain an entry at the leaf level for every transaction row. An index on the finalized transactions would be pointless as it would never be sufficiently selective to be helpful.com or by calling +1 800-785-3448.QuickStart Intelligence 8-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Filtered Indexes Key Points By default. For example. Question: What is the downside of having an entry at the leaf level for every transaction row. whether finalized or not? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. consider a large table of transactions with one column that indicates if the transaction is finalized or not. an index on the unfinalized transactions could be highly selective and very useful. However. Filtered indexes only include rows that match a WHERE predicate that is specified when the index is created. even if it is persisted. Note that only very simple logic is permitted in the WHERE clause predicate for filtered indexes. or resell this content. guarantees or conditions. you cannot use the clause to compare two columns and you cannot reference a computed column." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Often only a very small number of rows will be unfinalized. The Licensed Content is licensed "as-is. redistribute. Filtered Indexes For the example in the slide. Filtered indexes only include entries for rows that match the WHERE predicate. It is illegal to reprint. and provided to you by QuickStart Intelligence.

The Licensed Content is licensed "as-is. navigate to D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ. type Proseware in the Server name text box and click Connect. From the File menu.sql script file.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-17 Demonstration 2A: Nonclustered Indexes Key Points In this demonstration you will see how to: • Create covering indexes • View included columns in indexes Demonstration Steps 1.ssmssln and click Open. click All Programs. . • Open and execute the 00 – Setup. 3. Follow the instructions contained within the comments of the script file. Please report any unauthorized use of this content to piracy@microsoft. Question: If included columns only apply to nonclustered indexes. • In the virtual machine.com or by calling +1 800-785-3448. 2. click Start. and provided to you by QuickStart Intelligence. It is illegal to reprint. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Project/Solution. Open the 21 – Demonstration 2A. click Open. click SQL Server Management Studio. why do you imagine that the columns in the clustered primary key also showed as included? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click Microsoft SQL Server 2008 R2.sql script file from within Solution Explorer. In the Connect to Server window. guarantees or conditions. redistribute. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

you will learn how to capture activity against SQL Server using SQL Profiler and then how to analyze that activity using the Database Engine Tuning Advisor. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 8-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Using the Database Engine Tuning Advisor Designing useful indexes is considered by many people as more of an art than a science. In this module. . guarantees or conditions. you will be able to: • • Capture traces of activity using SQL Server Profiler Use Database Engine Tuning Advisor to analyze trace results This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. While there is some truth to this statement. Objectives After completing this lesson.com or by calling +1 800-785-3448. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. The Licensed Content is licensed "as-is. a number of tools are available to assist with learning to create useful indexes. or resell this content.

or resell this content. It captures the activity from client applications to SQL Server and stores it in a trace." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This allows relationships between system resource impacts and the execution of queries in SQL Server to be made. and provided to you by QuickStart Intelligence. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The traces can also be replayed. You can also save your own selections as a new template. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. Rather than needing to select events and columns each time you run SQL Server Profiler. These traces can then be analyzed. When using traces for diagnosing problems. SQL Server Profiler SQL Server profiler captures data when events occur. SQL Server Profiler also allows you to step through queries when diagnosing problems. The ability to replay traces is useful for load testing systems or for ensuring that upgraded versions of SQL Server can be used with existing applications. It is illegal to reprint. A variety of information (shown as a set of columns) is available when each event occurs. The captured traces are useful when tuning the performance of an application and when diagnosing specific problems that are occurring. depending upon the options chosen. redistribute. log data from the Windows Performance Monitor tool can be loaded. SQL Trace SQL Server Profiler is a graphical tool and it is important to realize that it can have significant performance impacts on the server being traced. guarantees or conditions.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-19 SQL Server Profiler Key Points SQL Server Profiler is an important tool when tuning the performance of SQL Server queries. SQL Trace is a library of system stored procedures that can be used for tracing when minimizing the performance impacts of the tracing is necessary. a set of existing templates are available. Only events that have been selected are captured. The trace created contains only the selected columns for the selected events.

guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. The Licensed Content is licensed "as-is.QuickStart Intelligence 8-20 Implementing a Microsoft® SQL Server® 2008 R2 Database The Extended Events system that was introduced in SQL Server 2008 also provides capabilities for tracing SQL Server activity and resources. .com or by calling +1 800-785-3448. Both SQL Trace and Extended Events are outside the scope of this course. and provided to you by QuickStart Intelligence. Question: Where would the ability to replay a trace be useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. or resell this content.

and provided to you by QuickStart Intelligence. redistribute. navigate to D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ.sql script file from within Solution Explorer. 3. From the File menu. • In the virtual machine. Question: When so many statements were executed. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the Connect to Server window. why was there only one entry in the trace? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. click All Programs. or resell this content. click SQL Server Management Studio. 2. click Start.com or by calling +1 800-785-3448. click Project/Solution. Please report any unauthorized use of this content to piracy@microsoft. click Open. Demonstration Steps 1. Follow the instructions contained within the comments of the script file. Open the 31 – Demonstration 3A. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.sql script file. . type Proseware in the Server name text box and click Connect.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-21 Demonstration 3A: SQL Server Profiler Key Points In this demonstration you will see how to use SQL Server Profiler. • Open and execute the 00 – Setup. It is illegal to reprint.ssmssln and click Open. click Microsoft SQL Server 2008 R2.

guarantees or conditions.QuickStart Intelligence 8-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Database Engine Tuning Advisor Key Points The Database Engine Tuning Advisor utility analyzes the performance effects of workloads run against one or more databases. After analyzing the effects of a workload on your databases. The Licensed Content is licensed "as-is. or you can choose to implement the recommended changes immediately. The recommendations that are produced are provided as a set of Transact-SQL statements that would implement the suggested changes. Database Engine Tuning Advisor was further enhanced in SQL Server 2008 with improved workload parsing. redistribute. Database Engine Tuning Advisor In SQL Server 2000 and earlier." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a previous version of this tool was supplied. indexes that should be dropped. or a table of trace information. It was called the "Index Tuning Wizard". Typically these workloads are obtained from traces captured by SQL Server Profiler. integrated tuning. The workload source can be a file containing Transact-SQL statements. and depending on the tuning options you set. SQL Server Management Studio also has the ability to launch Database Engine Tuning Advisor to analyze an individual statement. Recommendations The recommendations that can be produced include suggested changes to the database such as new indexes. again generated by SQL Profiler. Please report any unauthorized use of this content to piracy@microsoft. Workloads A workload is a set of Transact-SQL statements that executes against databases that you want to tune. Database Engine Tuning Advisor provides recommendations for improving the performance of your system. partitioning recommendations. . and provided to you by QuickStart Intelligence. It is illegal to reprint. You can view the Transact-SQL and save it for later review and application. a trace file generated by SQL Profiler. In SQL Server 2005. or resell this content. the name was changed as the tool evolved to be able to provider a broader range of recommendations.com or by calling +1 800-785-3448. and the ability to tune multiple databases concurrently. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

or resell this content. redistribute. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-23 Be careful of applying changes to a database without detailed consideration. Also. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. especially in production environments. and provided to you by QuickStart Intelligence. ensure that any analysis that you perform is based on appropriately sized workloads so that recommendations are not made based on partial information. Question: Why is it important to tune an entire workload rather than individual queries? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

click SQL Server Management Studio. 2. Please report any unauthorized use of this content to piracy@microsoft.ssmssln and click Open. click Open. From the File menu.QuickStart Intelligence 8-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3B: Database Engine Tuning Advisor Key Points In this demonstration you will see how to use Database Engine Tuning Advisor. type Proseware in the Server name text box and click Connect. .com or by calling +1 800-785-3448. navigate to D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ. redistribute. Open the 32 – Demonstration 3B. or resell this content.sql script file. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Follow the instructions contained within the comments of the script file. Demonstration Steps 1. • In the virtual machine. Question: Should you immediately apply the recommendations to your server? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click Microsoft SQL Server 2008 R2. click Project/Solution. • Open and execute the 00 – Setup.sql script file from within Solution Explorer. click All Programs. The Licensed Content is licensed "as-is. It is illegal to reprint. 3. guarantees or conditions. In the Connect to Server window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click Start. and provided to you by QuickStart Intelligence.

com or by calling +1 800-785-3448. Wait for the revert action to complete. • Click Switch User. or resell this content. 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. you must complete the following steps: 1. and then click Other User. In Virtual Machine Connection window. 5. • In the Virtual Machine Connection window. 2. If you are prompted to confirm that you want to revert. • Right-click 623XB-MIA-DC and click Connect. Before you begin the lab. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. click on the Revert toolbar icon. 3. click the Ctrl-Alt-Delete menu item. • In the Virtual Machine Connection window. 4. . 6.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-25 Lab 8: Improving Performance through Nonclustered Indexes Lab Setup For this lab. In the Virtual Machines list. On the host computer. In the Virtual Machines list. point to Administrative Tools. if the user is not already logged on: • On the Action menu. guarantees or conditions. and then close the Virtual Machine Connection window. Maximize the Hyper-V Manager window. redistribute. wait until the Press CTRL+ALT+DELETE to log on message appears. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. click Start. wait until the Press CTRL+ALT+DELETE to log on message appears. and then click Hyper-V Manager. click Revert. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. you will use the available virtual machine environment. In the Virtual Machine Connection window. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. 7.

ServerID. Later you will learn to set up a basic query tuning trace in SQL Server Profiler and use the trace captured in Database Engine Tuning Advisor. 10.WebLog AS wl WHERE wl.WebLog (ServerID. Query 3: Query to review SELECT PostalCode. When the query window opens. guarantees or conditions. It is illegal to reprint. In the Authentication drop-down list box. click Execute on the toolbar.SessionStart >= @StartTime ORDER BY wl.QuickStart Intelligence 8-26 Implementing a Microsoft® SQL Server® 2008 R2 Database • Log on using the following credentials: i. or resell this content. In the File menu. and click Project/Solution. wl. 9. open the project D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ. It retrieves 5000 web log entries beyond a given starting time. and click SQL Server Management Studio. User name: AdventureWorks\Administrator ii. 12. The developer is puzzled that changing the request to 5000 entries at a time has caused SQL Server to ignore the index he built. select Windows Authentication and click Connect. Please report any unauthorized use of this content to piracy@microsoft. Previously. Supporting Documentation Query 1: Query to test DECLARE @StartTime datetime2 = '2010-08-30 16:27'.ServerID. the developer noted the cost of the sort operation and tried to create another index that would eliminate the sort. After you have created the new index. You need to investigate the query and suggest the best non-clustered index to support the query.SessionID. The Licensed Content is licensed "as-is. click Start. Query 2: Index Design CREATE INDEX IX_WebLog_Perf_20100830_B ON Marketing.com or by calling +1 800-785-3448. wl. If time permits. . wl. UserName). a non-clustered index was created on the SessionStart column. click Microsoft SQL Server 2008 R2. double-click the query 00-Setup.sql. In the Open Project window. Password: Pa$$w0rd 8. click All Programs. 11. click Open. SELECT TOP(5000) wl. If the Server Manager window appears." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. From the View menu. redistribute. 13. the index was being used. When 100 web log entries were being retrieved at a time. you will design a required nonclustered index. SessionStart) INCLUDE (SessionID. check the Do not show me this console at logon check box and close the Server Manager window. 14. In Connect to Server window. You need to explain to him why SQL Server has decided not to use this index. In the virtual machine. click Full Screen Mode. type Proseware in the Server name text box. In Solution Explorer. and provided to you by QuickStart Intelligence.UserName FROM Marketing.ssmssln. Country This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. in the Virtual Machine Connection window.SessionStart. Lab Scenario The marketing system includes a query that is constantly executed and is performing too slowly. 15. You will then test your suggestion.

PostalCode. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-27 FROM Marketing. It is illegal to reprint. guarantees or conditions.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. or resell this content. .

Results: After this exercise. The main tasks for this exercise are as follows: 1. a non-clustered index was created on the SessionStart column. Previously.  Task 2: Review the existing Index and Table structures • Review the existing Index and Table structures.com or by calling +1 800-785-3448.QuickStart Intelligence 8-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Nonclustered index usage review Scenario The marketing system includes a query that is constantly executed and is performing too slowly.  Task 4: Test your design • In the supporting documentation. redistribute. 2. or resell this content. The developer is puzzled that changing the request to 5000 entries at a time has caused SQL Server to ignore the index he built.  Task 1: Review the query • Review the Query 1 in the supporting documentation. use Query 1 to test your new index.  Task 3: Design a more appropriate index • Design a more appropriate index. 3." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. you have created a non-clustered index. The Licensed Content is licensed "as-is. You will then test your suggestion. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. You need to investigate the query and suggest the best non-clustered index to support the query. It retrieves 5000 web log entries beyond a given starting time. the index was being used. When 100 web log entries were being retrieved at a time. Test your design. It is illegal to reprint. 4. Review the query. . guarantees or conditions. Design a more appropriate index. Please report any unauthorized use of this content to piracy@microsoft. Review the existing Index and Table structures.

Review the index design. or resell this content.  Task 3: Test the design and explain why the index was not used • Enable Include Actual Execution Plan. redistribute.QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-29 Exercise 2: Improving nonclustered index designs Scenario After you have created the new index. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448.  Task 2: Implement the index • Create the index as per the index design. and provided to you by QuickStart Intelligence. Test the design and explain why the index was not used. Explain why SQL Server has decided not to use this index: The main tasks for this exercise are as follows: 1. Implement the index. guarantees or conditions. review the index design." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 2. • Review the Execution Plan and explain why the index was not used. • Execute the query. 3.  Task 1: Review the index design • In Query 2 in the supporting documentation. the developer noted the cost of the sort operation and tried to create another index that would eliminate the sort. It is illegal to reprint. Results: After this exercise. Please report any unauthorized use of this content to piracy@microsoft. you have understood why some indexes are not appropriate in some scenerios. . The Licensed Content is licensed "as-is.

You will then test your suggestion. and provided to you by QuickStart Intelligence. If you create another index.  Task 1: Review the query • Review Query 3 in the supporting documentation. Design a more appropriate index by following the Missing Index suggestion. you should have created a better index that will remove the sort operation. 2. 4. guarantees or conditions. confirm that SQL Server selects it • Create a new index that will remove the Sort operation. • Test to ensure that the new index is being used.  Task 2: Review the existing Index and Table structures • Review the existing Index and Table structures. Results: After this exercise. confirm that SQL Server selects it. Review the query. It is illegal to reprint. Review the existing Index and Table structures. You need to investigate the query and suggest the best nonclustered index to support the query." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The main tasks for this exercise are as follows: 1. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.  Task 4: Create a better index that removes the sort operation. .QuickStart Intelligence 8-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 3: SQL Server Profiler and Database Engine Tuning Advisor Scenario Query 3 is another important query.  Task 3: Design a more appropriate index by following the Missing Index suggestion • Review and implement the Missing Index that SQL Server has suggested. 3. • Test to ensure that the new index is being used. redistribute. Create a better index that removes the sort operation. If you create another index. The Licensed Content is licensed "as-is.

• Analyze the trace results using DTA. • Disable AutoScroll from the Window Menu. • Review the recommendations provided by the Database Tuning Advisor. Load and execute the workload file. • Configure it use the following: a. Please report any unauthorized use of this content to piracy@microsoft. redistribute. .QuickStart Intelligence Improving Performance through Nonclustered Indexes 8-31 Challenge Exercise 4: Nonclustered index design (Only if time permits) Scenario You will learn to set up a basic query tuning trace in SQL Server Profiler and to analyze use the trace captured in Database Engine Tuning Advisor. Filter: DatabaseName LIKE MarketDev • Start the SQL Server Profiler Trace. 3. Template: Tuning b.  Task 3: Stop and analyze the trace using DTA • Stop the SQL Server Profiler trace. Results: After this exercise. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.  Task 2: Load and execute the workload file • Load and execute the workload file 81 – Lab Exercise 4. Stop and analyze the trace using DTA.com or by calling +1 800-785-3448. Save To File: should be selected and any file name provided for a file on the desktop c.sql. guarantees or conditions. or resell this content. 2. you should have created a SQL Server Profiler trace and analyzed the recommendations from the Database Tuning Advisor. Maximum File Size: 500MB e. Enable file rollover: Not selected d. It is illegal to reprint. The main tasks for this exercise are as follows: 1. The Licensed Content is licensed "as-is. Open SQL Server Profiler and configure and start a trace.  Task 1: Open SQL Server Profiler and configure and start a trace • Open SQL Server Profiler.

If using an offline version of Books Online. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. Never apply Database Engine Tuning Advisor recommendations without further reviewing what is being suggested.com or by calling +1 800-785-3448. 2. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 3. What is a covering index? Can a clustered index be a covering index? Best Practices 1. Please report any unauthorized use of this content to piracy@microsoft. this should be taken as a hint to investigate the indexing structure of the table. and provided to you by QuickStart Intelligence. DBAs are hesitant to ever remove indexes without this knowledge.QuickStart Intelligence 8-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. When DETA suggests new statistics. ensure it is kept up to date. guarantees or conditions. The Licensed Content is licensed "as-is. Record details of why and when you create any indexes. 2. or resell this content. It is illegal to reprint.

or resell this content.QuickStart Intelligence Designing and Implementing Stored Procedures 9-1 Module 9 Designing and Implementing Stored Procedures Contents: Lesson 1: Introduction to Stored Procedures 9-3 Lesson 2: Working With Stored Procedures 9-11 Lesson 3: Implementing Parameterized Stored Procedures 9-23 Lesson 4: Controlling Execution Context 9-33 Lab 9: Designing and Implementing Stored Procedures 9-39 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. redistribute. guarantees or conditions. and provided to you by QuickStart Intelligence. . It is illegal to reprint.

Please report any unauthorized use of this content to piracy@microsoft. You will see the potential advantages of the use of stored procedures in this module along with guidelines on creating them. and provided to you by QuickStart Intelligence. . guarantees or conditions.QuickStart Intelligence 9-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Stored procedures allow the creation of T-SQL logic that will be stored and executed at the server.com or by calling +1 800-785-3448. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. redistribute. Objectives After completing this module. The Licensed Content is licensed "as-is. you will be able to: • • • • Describe the role of stored procedures and the potential benefits of using them Work with stored procedures Implement parameterized stored procedures Control the execution context of a stored procedure This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. This logic might enforce business rules or data consistency.

Objectives After completing this lesson. redistribute. It is also important to realize when designing stored procedures that not all T-SQL statements are permitted within stored procedures. In this lesson. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. It is illegal to reprint. System stored procedures provide a large amount of pre-built functionality that you can take advantage of when building applications. you will see the role of stored procedures and the potential benefits of using them." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. you will be able to: • • • • Describe the role of stored procedures Identify the potential benefits of using stored procedures Work with system stored procedures Identify statements that are not permitted within the body of a stored procedure declaration This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Designing and Implementing Stored Procedures 9-3 Lesson 1 Introduction to Stored Procedures SQL Server provides a number of stored procedures and users can also create stored procedures. The Licensed Content is licensed "as-is. or resell this content. and provided to you by QuickStart Intelligence. .

The application could send each batch of T-SQL commands to the server to be executed and resend the same commands if the same function needs to be executed again later. rather than sending all the statements that would otherwise be required. conditional execution. The creation of stored procedures in managed code will be discussed in Module 16. and other powerful programming features. As a side effect of executing the stored procedure. The application can then simply ask to execute the stored procedure each time it needs to use that same functionality. or resell this content. redistribute. they support userdeclared variables. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. . In fact.com or by calling +1 800-785-3448. guarantees or conditions. Stored procedures can be created in either T-SQL or in managed . rows of data can also be returned from the stored procedure.NET code and are executed by the EXECUTE T-SQL statement. multiple rowsets can be returned from a single stored procedure. It is illegal to reprint. T-SQL Code and Logic Reuse When applications interact with SQL Server there are two basic ways that they can send commands to the server. a stored procedure could be created at the server level to encapsulate all the T-SQL statements required. Please report any unauthorized use of this content to piracy@microsoft. Question: Why might it be useful to return multiple rowsets from a stored procedure? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. They can have input and output parameters and a return value. methods and functions in high-level languages.QuickStart Intelligence 9-4 Implementing a Microsoft® SQL Server® 2008 R2 Database What is a Stored Procedure? Key Points A stored procedure is a named collection of Transact-SQL statements that is stored on the server within the database itself." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Stored procedures are a method of encapsulating repetitive tasks. Stored Procedures Stored procedures are similar to procedures. Stored procedures are given names that they can be referred to by. Alternately.

This is referred to as deferred name resolution. Modular Programming Code reuse is important. Please report any unauthorized use of this content to piracy@microsoft. you only need to change the procedure." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. without needing to change the application code at all in many cases. Stored procedures help by allowing logic to be created once and then to be called many times and from many applications. The Licensed Content is licensed "as-is. Delayed Binding It is possible to create a stored procedure that accesses (or references) a database object that does not yet exist.com or by calling +1 800-785-3448. redistribute. and provided to you by QuickStart Intelligence. For example. They can be treated as a security boundary. Users can be given permission to execute a stored procedure without being given permission to access the objects that the stored procedure accesses. . It is illegal to reprint. Maintenance is easier as if a change is needed. guarantees or conditions. Performance Send the name of a stored procedure to be executed rather than hundreds or thousands of lines of executable T-SQL code can offer a significant reduction in the level of network traffic. Security Boundary Stored procedures can be part of a scheme that helps increase application security. Changing a stored procedure could avoid the need to change the data access logic in a group of applications.QuickStart Intelligence Designing and Implementing Stored Procedures 9-5 Benefits of Stored Procedures Key Points The use of stored procedures offers a number of benefits over issuing T-SQL code directly from an application. or resell this content. you can give a user (or set of users via a role) permission to execute a stored procedure that updates a table without granting the user any permissions at all directly on the table. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. This can be helpful in simplifying the order that database objects need to be created in.

Any difference at all (eg: whitespace. redistribute. etc. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. casing. to need to be created in a specific order? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. The Licensed Content is licensed "as-is. Question: Stored procedures can be created in any order. Why could cause the tables that are referenced by the stored procedures. to avoid the cost of the compilation of the code. While reuse of execution plans for ad-hoc T-SQL code issued by applications is possible. and provided to you by QuickStart Intelligence. guarantees or conditions. Query plans for ad-hoc T-SQL statements are amongst the first items removed from memory when memory pressure is occurring. it needs to be compiled." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. unless the difference is only a value that SQL Server decides must be the equivalent of a parameter. When a stored procedure is compiled. .) will cause a different query plan to be used. The rules governing the reuse of query plans for ad-hoc T-SQL are largely based on matching the text of the queries exactly.com or by calling +1 800-785-3448.QuickStart Intelligence 9-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Before T-SQL code is executed. SQL Server favors the reuse of stored procedure execution plans. in many cases SQL Server will attempt to retain (and reuse) the query plan that it previously generated. Stored procedures have a much higher chance of achieving query plan reuse.

The Licensed Content is licensed "as-is. sys. They are typically used for administrative tasks relating to configuring servers." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Originally. whereas the code for the system extended stored procedures is written in unmanaged native code (typically written in C++) and supplied via a DLL (dynamic link library).sp_configure. Note that since SQL Server 2005.QuickStart Intelligence Designing and Implementing Stored Procedures 9-7 Working with System Stored Procedures Key Points SQL Server is shipped with a large amount of pre-built functionality shipped within system stored procedures and system extended stored procedures. guarantees or conditions. the procedures are actually located in a hidden resource database rather than directly in the master database but the effect is the same. Type of System Stored Procedures There are two basic types of system stored procedure: system stored procedures and system extended stored procedures. Now.sp_addmessage.sp_executesql. or resell this content. The core difference between the two is that the code for system stored procedures is written in T-SQL and is supplied in the master database installed with SQL Server. and provided to you by QuickStart Intelligence. the need to maintain backwards compatibility has caused a mixture of these prefixes to appear in both types. Over time. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. most system stored procedures have an sp_ prefix and most system extended stored procedures have an xp_ prefix.com or by calling +1 800-785-3448. sys. Examples of system stored procedures are sys. . It is illegal to reprint. Both are supplied pre-built with SQL Server. System Stored Procedures System stored procedures are "special" in that they can be executed from within any database without needing to specify the master database as part of their name. System stored procedures are created within the sys schema. there was a basic distinction in the naming where system stored procedures had an sp_ prefix and system extended stored procedures had an xp_ prefix. redistribute. databases and objects or for retrieving information about them. Please report any unauthorized use of this content to piracy@microsoft.

Extended stored procedures run directly within the memory space of SQL Server. It is illegal to reprint.com or by calling +1 800-785-3448. User-defined extended stored procedures are well-known to the SQL Server product support group as a source of difficult problems to resolve. sys. . Managed code stored procedures should now be used instead of user-defined extended stored procedures. the ability to do so is now deprecated.QuickStart Intelligence 9-8 Implementing a Microsoft® SQL Server® 2008 R2 Database System Extended Stored Procedures System extended stored procedures are used to extend the functionality of the server in ways that cannot be achieved via T-SQL code alone. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.xp_dirtree. (Note how the last example here has an sp_ prefix). Examples of system extended stored procedures are sys." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is not a safe place for users to be executing code. or resell this content.xp_cmdshell and sys. The use of managed code to create stored procedures will be described in Module 16. guarantees or conditions.sp_trace_create. and provided to you by QuickStart Intelligence. User Extended Stored Procedures While it is still possible to create user-defined extended stored procedures and attach them to SQL Server. redistribute. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.

Please report any unauthorized use of this content to piracy@microsoft. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Statements not Permitted Most T-SQL statements can be used within the bodies of stored procedures. not by attempting to change the database context to another database ie: the USE statement cannot be used within the body of a stored procedure in the way that it can be used in a T-SQL script. and provided to you by QuickStart Intelligence. redistribute. The Licensed Content is licensed "as-is. guarantees or conditions. For the statements that are not permitted. It is illegal to reprint. The table on the slide shows that statements that cannot be used. the reason usually relates to one of the following: • • • creation of other objects changing SET options that relate to query plans changing database context via the USE statement Note that stored procedures can access objects in other databases but that they need to be referred to by name.QuickStart Intelligence Designing and Implementing Stored Procedures 9-9 Statements not Permitted Key Points Not all T-SQL statements are permitted within stored procedure declarations.com or by calling +1 800-785-3448.

and provided to you by QuickStart Intelligence. Open the 11 – Demonstration 1A. Question: What does the mismatch of prefixes in system stored procedure and system extended store procedure names suggest? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Start. guarantees or conditions.ssmssln and click Open. type Proseware in the Server name text box and click Connect. click SQL Server Management Studio. 5.com or by calling +1 800-785-3448. . Follow the instructions contained within the comments of the script file.sql script file. click Microsoft SQL Server 2008 R2. 4." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. navigate to D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ. From the File menu. 2.sql script file from within Solution Explorer. Please report any unauthorized use of this content to piracy@microsoft. In the Connect to Server window. Open and execute the 00 – Setup. 2. The Licensed Content is licensed "as-is. How to execute system stored procedures How to execute system extended stored procedures Demonstration Steps 1.QuickStart Intelligence 9-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Working with System Stored Procedures and Extended Stored Procedures Key Points In this demonstration you will see how: 1. click Open. click Project/Solution. redistribute. click All Programs. In the virtual machine. It is illegal to reprint. 3.

redistribute.QuickStart Intelligence Designing and Implementing Stored Procedures 9-11 Lesson 2 Working with Stored Procedures Now that you have an understanding of why stored procedures are important. and provided to you by QuickStart Intelligence. you need to gain an understanding of the practicalities involved in working with stored procedures. The Licensed Content is licensed "as-is. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Objectives After completing this lesson. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.com or by calling +1 800-785-3448. . guarantees or conditions. you will be able to: • • • • • • • Create a stored procedure Execute stored procedures Alter a stored procedure Drop a stored procedure Identify stored procedure dependencies Explain guidelines for creating stored procedures Obfuscate stored procedure definitions This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

redistribute. The Licensed Content is licensed "as-is. As such." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. A procedure cannot be replaced by using the CREATE PROC statement. Debugging Stored Procedures A good practice when working with stored procedures is to first write and test the T-SQL statements that you want to include in your stored procedure and if you receive the results you expected. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. then wrap the T-SQL statements as the body of a stored procedure. it would be created in the tempdb database and removed the next time the server is restarted. It is important to keep connection settings such as QUOTED_IDENTIFIER and ANSI_NULLS consistent when working with stored procedures. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. .com or by calling +1 800-785-3448. CREATE PROC CREATE PROCEDURE is commonly abbreviated to CREATE PROC. and provided to you by QuickStart Intelligence. It needs to be explicitly altered using an ALTER PROC statement or dropped and then recreated. Creating a stored procedure requires both the CREATE PROCEDURE permission in the current database and the ALTER permission on the schema in which the procedure is being created. The settings associated with the stored procedure are taken from the settings in the session where it is created. The # prefix on a name indicates that it is a temporary object. or resell this content. All statements from the keyword AS until the end of the script or until the end of the batch (using a batch separator such as GO) will become part of the body of the stored procedure. The CREATE PROC statement must be the only statement in the T-SQL batch. Stored procedures are always created in the current database with the single exception of stored procedures created with a # prefix in their name.QuickStart Intelligence 9-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Creating a Stored Procedure Key Points The T-SQL CREATE PROCEDURE statement is used to create new procedures.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. doing so is considered a good practice. The Licensed Content is licensed "as-is. guarantees or conditions. It is illegal to reprint. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. or resell this content. . redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Designing and Implementing Stored Procedures 9-13 Note: Even though wrapping the body of a stored procedure with a BEGIN…END block is not required.

The EXECUTE statement is commonly abbreviated as EXEC. system stored procedures can be executed within the master database without having to explicitly refer to that database. Two-Part Naming When Creating Stored Procedures If you create a stored procedure by only supplying the name of the procedure (and not the schema name as well). The Licensed Content is licensed "as-is. it will search the dbo schema for a table with that name. redistribute. Scripts that create stored procedures this way tend to be fragile as the location of the created stored procedure would depend upon the default schema of the user executing the script.QuickStart Intelligence 9-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Executing Stored Procedures Key Points The T-SQL EXECUTE statement is used to execute stored procedures. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. AS mentioned in the first lesson. Two-Part Naming on Referenced Objects It is very important when creating stored procedures to use at least two-part names for objects referenced by the stored procedure. or resell this content. If you use only the name of a table. This minimizes SQL Server's options for query plan reuse because it does not know until the moment the stored procedure is executed which objects it needs to refer to as different users can have different default schemas. That does not apply to other stored procedures. you avoid any ambiguity about which table you are referring to and you maximize the chance of SQL Server being able to reuse query execution plans for the stored procedure. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . guarantees or conditions. SQL Server will first search in your default schema for the table and then if it did not locate a table with that name. If you refer to a table by both its schema name and its table name. EXECUTE Statement The EXECUTE is mostly used to execute stored procedures but can also be used to execute other objects such as dynamic SQL statements.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. It is illegal to reprint. SQL Server will attempt to create the stored procedure in your default schema.

you should also supply the name of both the schema and the stored procedure. .com or by calling +1 800-785-3448. SQL Server also looks in the master database in the sys schema for the stored procedure. or resell this content. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. If you supply only the name of the stored procedure." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. • • SQL Server then looks in the default schema for the user executing the stored procedure. It is illegal to reprint.QuickStart Intelligence Designing and Implementing Stored Procedures 9-15 Two-Part Naming When Executing Stored Procedures When you execute a stored procedure. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. redistribute. SQL Server then looks in the dbo schema in the current database for the stored procedure. SQL Server can end up trying to find the stored procedure in a number of places: If the stored procedure name starts with sp_ (not recommended for user stored procedures). Having SQL Server perform unnecessary steps to locate a stored procedure reduces performance for no reason.

For example. If you drop the procedure and recreate it. None of these options are retained and they are replaced by whatever options are supplied in the ALTER PROC statement." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Connection Settings The connection settings such as QUOTED_IDENTIFIER and ANSI_NULLS that will be associated with the modified stored procedure will be those taken from the session that makes the change. ALTER PROCEDURE is often abbreviated to ALTER PROC. a T-SQL procedure cannot be changed to a managed code procedure via an ALTER PROCEDURE statement or vice-versa. The Licensed Content is licensed "as-is. guarantees or conditions. Complete Replacement Note that when you alter a stored procedure. you need to supply again any options (such as WITH ENCRYPTION) that were supplied while creating the procedure. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Procedure Type Note that the type of procedure cannot be changed.com or by calling +1 800-785-3448. not from the original stored procedure so it is important to keep these consistent when making changes. ALTER PROC The main reason for using the ALTER PROC statement is to retain any existing permissions on the procedure while it is being changed. those permissions that had been granted to the users would be removed when the procedure was dropped. It is illegal to reprint. . and provided to you by QuickStart Intelligence. Users may have been granted permission to execute the procedure. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. redistribute.QuickStart Intelligence 9-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Altering a Stored Procedure Key Points The T-SQL ALTER PROCEDURE statement is used to replace an existing procedure.

guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.QuickStart Intelligence Designing and Implementing Stored Procedures 9-17 Dropping a Stored Procedure Key Points Dropping a stored procedure is straightforward. redistribute.procedures System View You can see a list of existing procedures in the current database by querying the sys. It is illegal to reprint.procedures view will show you the list of procedures in the current database. Permissions Dropping a procedure requires either ALTER permission on the schema that the procedure is part of or CONTROL permission on the procedure itself." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . The DROP PROCEDURE statement is used to drop a stored procedure and is commonly abbreviated as DROP PROC. The Licensed Content is licensed "as-is. or resell this content. sys. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence.

and provided to you by QuickStart Intelligence.sql_expression_dependencies provide a one row per name dependency on userdefined entities in the current database. sys.dm_sql_referenced_entities and sys. It was known to have issues and to report incomplete information due to issues with deferred name resolution. sp_depends Earlier versions of SQL Server used the sp_depends system stored procedure to return details of dependencies between objects. It is illegal to reprint. or resell this content. sys. .com or by calling +1 800-785-3448. guarantees or conditions.dm_sql_referencing_entities provide more targeted views over the data provided by sys. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 9-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Stored Procedure Dependencies Key Points It is a good idea before dropping a stored procedure to check for any other objects that are dependent upon the stored procedure. Sys. The Licensed Content is licensed "as-is. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.sql_expression_dependencies view replaces the previous use of the sp_depends system stored procedure. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. You will see an example of these dependency views being used in the next demonstration.sql_expression_dependencies Use of the sys.sql_expression_dependencies.

This applied to both the creation of stored procedures and to their execution. The Licensed Content is licensed "as-is. SQL Server uses the sp_ prefix to designate system stored procedures. However. or resell this content. For example. It is important to have a consistent way of naming your stored procedures. Please report any unauthorized use of this content to piracy@microsoft. Apply consistent naming conventions It is recommended that you do not create any stored procedures using sp_ as a prefix. and provided to you by QuickStart Intelligence. Others use an action verb followed by a description of the action to be performed. These original settings are used when the stored procedure is executed. some people use a naming convention of a table name followed by an action. guarantees or conditions. It is possible via Policy Based Management (first introduced in SQL Server 2008 and beyond the scope of this course) or via DDL triggers (first introduced in SQL Server 2005 and also beyond the scope of this course) to enforce naming conventions on most objects. There is no right or wrong way to do this in all situations but you should decide on a method for naming to be used in your applications and to consistently apply it. The name you choose may conflict with some future system procedure. the importance of using at least two part naming when referring to objects within stored procedure was described.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. Qualify names inside of stored procedures Earlier in this lesson. . Keep consistent SET Options The Database Engine saves the settings of both SET QUOTED_IDENTIFIER and SET ANSI_NULLS when a Transact-SQL stored procedure is created or altered." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. this does not work well for more complex procedures that affect multiple tables.QuickStart Intelligence Designing and Implementing Stored Procedures 9-19 Guidelines for Creating Stored Procedures Key Points There are a number of important guidelines that should be considered when creating stored procedures.

You can nest stored procedures and managed code references up to 32 levels. Doing this limits reuse possibilities and can hinder performance. It is illegal to reprint. guarantees or conditions. . or resell this content. Please report any unauthorized use of this content to piracy@microsoft. redistribute. Don't write one procedure that does an enormous number of tasks. type.QuickStart Intelligence 9-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Use @@nestlevel to see current nesting level Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. or aggregate. You can use @@nestlevel for checking the nesting level of the current stored procedure execution on the local server.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Keep one procedure per task Avoid writing "the procedure to rule them all" (with apologies to Lord of the Rings).

WITH ENCRYPTION As was mentioned in an earlier module dealing with views. Original copies of the source need to be kept regardless of the fact that decryption might be possible. It is known to be relatively easy to defeat as the encryption keys are stored in known locations within the encrypted text. . it is very important to understand that while SQL Server provides an option (WITH ENCRYPTION) to obfuscate the definition of your stored procedures.QuickStart Intelligence Designing and Implementing Stored Procedures 9-21 Obfuscating Stored Procedure Definitions Key Points SQL Server provides an option to obfuscate the definition of stored procedures via the WITH ENCRYPTION option. Question: Why might you want to obfuscate the definition of a stored procedure? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. There are a number of 3rd party tools that are capable of reversing the encryption. It is illegal to reprint. Encrypted code is much harder to work with in terms of diagnosing and tuning performance issues. that the encryption is not particularly strong.com or by calling +1 800-785-3448. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. or resell this content. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. Caution needs to be exhibited in using it as it makes working with the application more difficult and likely does not achieve the aims it is being targeted at. The Licensed Content is licensed "as-is. Do not depend upon this.

In the Connect to Server window. and provided to you by QuickStart Intelligence. click All Programs.sql script file from within Solution Explorer. click Project/Solution. 2. From the File menu. type Proseware in the Server name text box and click Connect. It is illegal to reprint. click Start.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.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. The Licensed Content is licensed "as-is. click SQL Server Management Studio. Follow the instructions contained within the comments of the script file. • In the virtual machine. redistribute. click Open. click Microsoft SQL Server 2008 R2. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. • Open and execute the 00 – Setup. 3. Open the 21 – Demonstration 2A.sql script file. navigate to D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ.QuickStart Intelligence 9-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: Stored Procedures Key Points In this demonstration you will see: • • • • • How to create a stored procedure How to execute a stored procedure How to create a stored procedure that returns multiple rowsets How to alter a stored procedure How to view the list of stored procedures Demonstration Steps 1. Question: How could the GetBlueProductsAndModels stored procedure be made more useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Designing and Implementing Stored Procedures 9-23 Lesson 3 Implementing Parameterized Stored Procedures The stored procedures that you have seen earlier in this module have not involved parameters. While the reuse of query execution plans is in general desirable. It is illegal to reprint. guarantees or conditions. . You will see situations where this can occur and consider options for workarounds to avoid the detrimental outcomes. and provided to you by QuickStart Intelligence. redistribute. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. Objectives After completing this lesson. or resell this content. there are situations where this reuse is detrimental. you will be able to: • • • • Parameterize stored procedures Work with input parameters Work with output parameters Explain the issues surrounding parameter sniffing and performance and the potential workarounds. Stored procedures can use both input and output parameters and return values. Stored procedures are more flexible when you include parameters as part of the procedure definition because you can create more generic application logic." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. They have produced their output without needing any input from the user and they have not returned any values back apart from the rows that they have returned.

Output Parameters Output parameters allow the stored procedure to pass a data value or a cursor variable back to the caller. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. you must specify the OUTPUT keyword in both the CREATE PROCEDURE and the EXECUTE statements. It is illegal to reprint. You will see an example of this in the next topic.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. output parameters and return values. and provided to you by QuickStart Intelligence. They contain 3 major components: input parameters. Return Value Every stored procedure returns an integer return code to the caller. . you declare one or more variables as parameters in the CREATE PROCEDURE statement.QuickStart Intelligence 9-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Working with Parameterized Stored Procedures Key Points Parameterized stored procedures allow for a much higher level of code reuse. (User-defined functions are discussed in a later module)." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. otherwise a negative value is returned. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. redistribute. They allow the caller to pass a data value to the stored procedure or function. To use an output parameter within Transact-SQL. guarantees or conditions. A key difference between stored procedures and user-defined function are that user-defined functions cannot specify output parameters. To define a stored procedure that accepts input parameters. the return code is 0 if no error occurs. If the stored procedure does not explicitly set a value for the return code. Input Parameters Parameters are used to exchange data between stored procedures and functions and the application or tool that called the stored procedure or function. Return values are commonly used to return a status result or an error code from a procedure and are sent by the T-SQL RETURN statement.

It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. or resell this content.com or by calling +1 800-785-3448. you should use OUTPUT parameters to output values rather than the RETURN value." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. in general. guarantees or conditions.QuickStart Intelligence Designing and Implementing Stored Procedures 9-25 While it is possible to send a business-logic related value via a RETURN statement. redistribute. and provided to you by QuickStart Intelligence.

@Status tinyint = 5 AS Two parameters have been defined (@DueDate and @Status). a user can execute the stored procedure without specifying a value for that parameter. or resell this content. guarantees or conditions.QuickStart Intelligence 9-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Using Input Parameters Key Points Stored procedures can accept input parameters. Default Values Provide default values for a parameter where appropriate. The other is to pass the list by name. Please report any unauthorized use of this content to piracy@microsoft. Look at the beginning of the procedure declaration from the example on the slide: CREATE PROCEDURE Sales. This might include checking whether the parameter is NULL.OrdersByDueDateAndStatus @DueDate datetime." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The @Status parameter has a default value of 5.com or by calling +1 800-785-3448. Validating Input Parameters As a best practice validate all incoming parameter values at the beginning of a stored procedure to trap missing and invalid values early. You cannot combine these two options in a single EXEC call. then a value of 5 will be used. The data type will be checked when a call is made. One is to pass the parameter list in order. Input Parameters Stored procedure parameters must have an @ prefix and must have a data type specified. redistribute. . It is illegal to reprint. There are two ways to call a stored procedure with input parameters. similar to the way that parameters are passed to functions or methods or subroutines in higher-level languages. The Licensed Content is licensed "as-is. If a value for the parameter is not supplied when the stored procedure is executed. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The @DueDate parameter has no default value and must be supplied when the procedure is executed. If a default is defined. and provided to you by QuickStart Intelligence.

the procedure will be executed with the @Status value set at a default value of 5. or resell this content. @DueDate = '20050713'. Please report any unauthorized use of this content to piracy@microsoft.OrdersByDueDateAndStatus '20050713'. Now look at the second option: EXEC Sales.OrdersByDueDateAndStatus @DueDate = '20050713'. guarantees or conditions. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. SQL Server knows which parameter is which by its position in the parameter list. Note that the names of the parameter have not been mentioned. look at the third option: EXEC Sales. In this case. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In this case. Executing a Stored Procedure with Input Parameters Three examples of executing the stored procedure are shown on the slide. Finally. . @Status = 5. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This execution supplies a value for both @DueDate and for @Status.OrdersByDueDateAndStatus '20050713'.com or by calling +1 800-785-3448.QuickStart Intelligence Designing and Implementing Stored Procedures 9-27 Validating parameters early avoids doing substantial work in the procedure and then having to undo all that work.5. a value for the @DueDate parameter has been supplied but no value for the @Status parameter has been supplied.OrdersByDueDateAndStatus @Status = 5. the stored procedure is being called with both parameters but they are being identified by name. Look at the first option: EXEC Sales. In this case. Note that you could have also achieved the same outcome with the parameters specified in the reverse order as they are identified by name: EXEC Sales. redistribute.

QuickStart Intelligence 9-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Using Output Parameters Key Points Output parameters are used very similarly to input parameters. SQL Server output parameter are really input/output parameters. SELECT @OrderCount. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. guarantees or conditions.com or by calling +1 800-785-3448. Now look at how the procedure is called: DECLARE @DueDate datetime = '20050713'. a variable to hold a due date has been declared. and provided to you by QuickStart Intelligence. @OrderCount int OUTPUT AS In this case. Note that in SQL Server there is no true equivalent of a . along with another to hold the order count. redistribute. DECLARE @OrderCount int.GetOrderCountByDueDate @DueDate. EXEC Sales. . Please report any unauthorized use of this content to piracy@microsoft. output parameters have a few special requirements. @OrderCount OUTPUT. It is illegal to reprint. variables to hold the parameter values have been declared. First. Look at the beginning of the procedure declaration from the example on the slide: CREATE PROC Sales. The Licensed Content is licensed "as-is.NET output parameter. the @DueDate parameter is an input parameter and the @OrderCount parameter has been specified as an output parameter." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The keyword OUTPUT must also be specified in the list of parameters passed during the EXEC statement. In this case. While they are declared and used very similarly to input parameters.GetOrderCountByDueDate @DueDate datetime. Output Parameter Requirements • • The keyword OUTPUT must be specified when declaring the output parameters of the stored procedure.

If you do not specify the OUTPUT parameter in the EXEC statement. note that the @OrderCount parameter is followed by the OUTPUT keyword. . guarantees or conditions. However.com or by calling +1 800-785-3448.QuickStart Intelligence Designing and Implementing Stored Procedures 9-29 In the EXEC call. you would then use the returned value somehow in the business logic that follows the EXEC call. Question: Why might you use output parameters in conjunction with IDENTITY columns? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. and provided to you by QuickStart Intelligence. the output parameter value would simply not be copied back into the @OrderCount variable. It is illegal to reprint. or resell this content. The Licensed Content is licensed "as-is. This is a common bug when working with output parameters. Finally. Please report any unauthorized use of this content to piracy@microsoft. the stored procedure would still execute as normal. including preparing a value to return in the output parameter.

and provided to you by QuickStart Intelligence. or resell this content. you might need a very different query plan to the times when you ask for A to Z.QuickStart Intelligence 9-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Parameter Sniffing and Performance Key Points In general. If you ask for the rows from A to A. Parameter Sniffing It has been mentioned that SQL Server attempts to reuse query execution plans from one execution of a stored procedure to the next. . guarantees or conditions. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. imagine a procedure that takes a range of names as parameters. sp_recompile System Stored Procedure If you call sp_recompile. redistribute. This causes the procedure to be recompiled every time it is executed. In that case. While the code for these looks very similar. The Licensed Content is licensed "as-is. often called a "parameter sniffing" problem. all existing plans that reference the object will be invalidated and recompiled the next time they are executed. SQL Server provides a variety of ways to deal with this problem. You can also pass the name of a table or view to this procedure. the reuse of query plans when a stored procedure is re-executed is a good thing. variable values are not "sniffed" at all and this can lead to poor execution plans regardless.com or by calling +1 800-785-3448. any existing plans for the stored procedure passed to it will be marked as invalid and the procedure will be recompiled next time it is executed. a stored procedure would benefit from an entirely different query execution plan for different parameter values. WITH RECOMPILE You can add a WITH RECOMPILE option when declaring a stored procedure. Please report any unauthorized use of this content to piracy@microsoft. While this is mostly helpful." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note that this only applies to parameters and not to variables within the batch. Sometimes however.

Question: How would you determine the value to assign in an OPTIMIZE FOR hint? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. . SQL Server will recompile the procedure before running it and will not store the resulting plan.QuickStart Intelligence Designing and Implementing Stored Procedures 9-31 EXEC WITH RECOMPILE If you add WITH RECOMPILE to the EXEC statement. OPTIMIZE FOR There is a query hint OPTION (OPTIMIZE FOR) that allows you to specify the value of a parameter that should be assumed when compiling the procedure.com or by calling +1 800-785-3448. regardless of the actual value of the parameter. The Licensed Content is licensed "as-is. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. guarantees or conditions. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.

navigate to D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ. Open the 31 – Demonstration 3A. It is illegal to reprint. • In the virtual machine." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. click Project/Solution. From the File menu. Follow the instructions contained within the comments of the script file. redistribute. type Proseware in the Server name text box and click Connect.sql script file from within Solution Explorer. guarantees or conditions. click Microsoft SQL Server 2008 R2. click Start. 3. click All Programs. .sql script file. click SQL Server Management Studio. Question: Why do we need to treat NULL differently to other possible values? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. • Open and execute the 00 – Setup. Please report any unauthorized use of this content to piracy@microsoft.ssmssln and click Open. and provided to you by QuickStart Intelligence. 2. click Open. or resell this content.QuickStart Intelligence 9-32 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Stored Procedure Parameters Key Points In this demonstration you will see: • • How to create a stored procedure with parameters How to alter a stored procedure with parameters to correct a common stored procedure bug Demonstration Steps 1. In the Connect to Server window. The Licensed Content is licensed "as-is.

It is illegal to reprint. or resell this content.com or by calling +1 800-785-3448.QuickStart Intelligence Designing and Implementing Stored Procedures 9-33 Lesson 4 Controlling Execution Context Stored procedures normally execute in the security context of the user calling the procedure. however. Sometimes. more precise control over the security context that the procedure is executing in is required. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. Ownership chaining issues with stored procedures are identical to those that were discussed for views in Module 4. and provided to you by QuickStart Intelligence. you will be able to: • • • Control execution context Work with the EXECUTE AS clause View execution context This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the user can execute the procedure without the need for permissions on the underlying objects. redistribute. Objectives After completing this lesson. . As long as a chain of ownership extends from the stored procedure to the objects that are referenced. The Licensed Content is licensed "as-is.

User tokens do not contain server-role memberships and do not honor the server-level permissions granted to the identities in the token including those that are granted to the server-level public role. Execution Contexts An execution context is represented by a login token and a user token. and provided to you by QuickStart Intelligence. The primary identity is the database user itself. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. User and Login Security Tokens A security token for a user or login contains the following: • • • • One server or database principal as the primary identity One or more principals as secondary identities Zero or more authenticators The privileges and permissions of the primary and secondary identities Login Token: A login token is valid across the instance of SQL Server. It contains the primary and secondary identities against which server-level permissions and any database-level permissions associated with these identities are checked. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This context is used to establish the identity against which permissions to execute statements or perform actions are checked. depending on the number of databases to which the account has access. guarantees or conditions. The primary identity is the login itself. . The secondary identity includes permissions inherited from database roles. redistribute. or resell this content.QuickStart Intelligence 9-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Controlling Execution Context Key Points The security context that a stored procedure executes in is referred to as its execution context. It contains the primary and secondary identities against which database-level permissions are checked. User Token: A user token is valid only for a specific database. A login connecting to an instance of SQL Server has one login token and one or more user tokens. The Licensed Content is licensed "as-is. The secondary identity includes permissions inherited from rules and groups. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The tokens identify the primary and secondary principals against which permissions are checked and the source used to authenticate the token.

com or by calling +1 800-785-3448. In the example shown in the slide. This causes the procedure to be executed with 'Pat' as the security context rather than with the default security context supplied by the caller of the stored procedure. Question: What is an authenticator? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Designing and Implementing Stored Procedures 9-35 Controlling Execution Context While the default behavior of execution contexts is usually appropriate. there are times when it is desirable to execute within a different security context. a WITH EXECUTE AS 'Pat' clause has been added to the definition of the stored procedure. . and provided to you by QuickStart Intelligence. guarantees or conditions. It is illegal to reprint. or resell this content.

The stand-alone EXECUTE AS statement can be used to impersonate server-level principals. Please report any unauthorized use of this content to piracy@microsoft. any resource within the server that the impersonated login has permissions on can be accessed. or resell this content. the scope of the impersonation is server-wide. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. by using the EXECUTE AS USER statement. or a server-level module. The Licensed Content is licensed "as-is. redistribute. by using the EXECUTE AS LOGIN statement. or within a server-scoped module by using the EXECUTE AS clause. or logins." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This means that after the context switch. The stand-alone EXECUTE AS statement can also be used to impersonate database level principals. This means that references to objects outside the scope of the database will return an error. or implicitly by using the EXECUTE AS clause on modules. or users. This impersonation depends on whether the module is a database-level module. the scope of impersonation is restricted to the database by default. Any login in the sysadmin role has IMPERSONATE permission on all users. when impersonating a principal by using the EXECUTE AS USER statement. and provided to you by QuickStart Intelligence. such as a stored procedure or function. Implicit Impersonation Implicit impersonations are performed through the WITH EXECUTE AS clause on modules and are used to impersonate the specified user or login at the database or server level. . It is illegal to reprint. you must first have IMPERSONATE permission on that user.QuickStart Intelligence 9-36 Implementing a Microsoft® SQL Server® 2008 R2 Database The EXECUTE AS Clause Key Points The EXECUTE AS clause sets the execution context of a stored procedure.com or by calling +1 800-785-3448. It is useful when you need to override the default security context. or within a databasescoped module by using the EXECUTE AS clause. Explicit Impersonation SQL Server supports the ability to impersonate another principal either explicitly by using the stand-alone EXECUTE AS statement. However. When impersonating a principal by using the EXECUTE AS LOGIN statement. such as a server-level trigger. To execute as another user.

login_token system view shows all tokens associated with the login.login_token System View The sys. These details are provided by the sys. sys. The Licensed Content is licensed "as-is. the Windows login GREGW701\Greg has associated server tokens for the public and sysadmin roles.user_token system view shows all tokens associated with the user within the database.com or by calling +1 800-785-3448.user_token System View The sys. This will include the login itself and the roles that the user is a member of. .user_token system views. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. sys. In the example shown in the slide. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. and provided to you by QuickStart Intelligence.login_token and sys. redistribute.QuickStart Intelligence Designing and Implementing Stored Procedures 9-37 Viewing Execution Context Key Points You may wish to programmatically query the current security context details. Please report any unauthorized use of this content to piracy@microsoft. the user is a member of the dbo role for the current database. In the example shown in the slide.

sql script file from within Solution Explorer. click Project/Solution. Please report any unauthorized use of this content to piracy@microsoft. From the File menu. and provided to you by QuickStart Intelligence. navigate to D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ. guarantees or conditions. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Open and execute the 00 – Setup.sql script file. • In the virtual machine.com or by calling +1 800-785-3448. click SQL Server Management Studio. In the Connect to Server window. 3. . Follow the instructions contained within the comments of the script file. or resell this content. click Open. The Licensed Content is licensed "as-is. type Proseware in the Server name text box and click Connect. 2. It is illegal to reprint. click Start. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.QuickStart Intelligence 9-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 4A: Viewing Execution Context Key Points In this demonstration you will see: • • • How to view details of execution context How to change execution context for a session How to use the WITH EXECUTE AS clause in a stored procedure Demonstration Steps 1.ssmssln and click Open. click Microsoft SQL Server 2008 R2. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Open the 41 – Demonstration 4A. click All Programs.

In the Virtual Machines list. The Licensed Content is licensed "as-is. 4. On the host computer. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. you must complete the following steps: 1. • In the Virtual Machine Connection window. click Revert. click on the Revert toolbar icon. point to Administrative Tools. In the Virtual Machines list. wait until the Press CTRL+ALT+DELETE to log on message appears. you will use the available virtual machine environment." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Right-click 623XB-MIA-DC and click Connect. • Right-click 623XB-MIA-SQL and click Connect. or resell this content. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. • Click Switch User. • In the Virtual Machine Connection window. Before you begin the lab. Wait for the revert action to complete. In the Virtual Machine Connection window. It is illegal to reprint.QuickStart Intelligence Designing and Implementing Stored Procedures 9-39 Lab 9: Designing and Implementing Stored Procedures Lab Setup For this lab. and then close the Virtual Machine Connection window. In Virtual Machine Connection window.com or by calling +1 800-785-3448. 5. 6. wait until the Press CTRL+ALT+DELETE to log on message appears. . 2. and provided to you by QuickStart Intelligence. 3. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 7. click Start. redistribute. click the Ctrl-Alt-Delete menu item. and then click Other User. If you are prompted to confirm that you want to revert. and then click Hyper-V Manager. if the user is not already logged on: • On the Action menu. Maximize the Hyper-V Manager window. Please report any unauthorized use of this content to piracy@microsoft.

check the Do not show me this console at logon check box and close the Server Manager window. In the Authentication drop-down list box. User name: AdventureWorks\Administrator ii. The This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.GetProductColors Input Parameters: None Output Parameters: None Output Columns: Color (from Marketing. From the View menu. NULL values should not be returned. In Connect to Server window. FrenchDescription. click Full Screen Mode. SellEndDate and Color (from Marketing. Stored Procedure Reports. 9. SellStartDate. Output Order: ProductID. If the Server Manager window appears. type Proseware in the Server name text box. In Solution Explorer.com or by calling +1 800-785-3448.Product).ProductModel). When the query window opens. It is illegal to reprint. 15. in the Virtual Machine Connection window. ChineseDescription. open the project D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ. and provided to you by QuickStart Intelligence.ProductDescription table for the appropriate language.sql. 10.ssmssln. click Microsoft SQL Server 2008 R2. In the virtual machine.QuickStart Intelligence 9-40 Implementing a Microsoft® SQL Server® 2008 R2 Database • Log on using the following credentials: i. return the Description column from the Marketing." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 13. guarantees or conditions. EnglishDescription. The procedures will be created within a new Reports schema. click Open. In the Open Project window. ProductModelID Notes: For descriptions. click All Programs.Product) Output Order: Color Notes: Colors should not be returned more than once in the output. The Licensed Content is licensed "as-is. click Execute on the toolbar. 11. ProductModelID (from Marketing. In the File menu. . Please report any unauthorized use of this content to piracy@microsoft. 14.GetProductsAndModels Input Parameters: None Output Parameters: None Output Columns: ProductID. click Start. and click SQL Server Management Studio. or resell this content. and click Project/Solution. Supporting Documentation Stored Procedure Reports. Password: Pa$$w0rd 8. Lab Scenario You need to create a set of stored procedures to support a new reporting application. ProductName. select Windows Authentication and click Connect. redistribute. double-click the query 00-Setup. ProductNumber. 12.

Input Parameters: None Output Parameters: None Output Columns: Color (from Marketing. or resell this content. Stored Procedure Reports.com or by calling +1 800-785-3448. ListPrice (returned as a column named Price). Color. return the invariant language description if it is present.Product) Output Order: Color Notes: Colors should not be returned more than once in the output.GetProductsByColor Input Parameters: @Color (same datatype as the Color column in the Marketing.Product table) Output Parameters: None Output Columns: ProductID. redistribute. ProductName. The Licensed Content is licensed "as-is. NULL values should not be returned. and provided to you by QuickStart Intelligence. Where neither the specific language or invariant language descriptions exist." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.GetProductColors LanguageID for English is 'en'. Please report any unauthorized use of this content to piracy@microsoft. . It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.Product) Output Order: ProductName Notes: The procedure should return products that have no Color if the parameter is NULL. for French is 'fr' and for Chinese is 'zh-cht'.QuickStart Intelligence Designing and Implementing Stored Procedures Stored Procedure 9-41 Reports. Size and SizeUnitMeasureCode (returned as a column named UnitOfMeasure) (from Marketing. guarantees or conditions. The LanguageID for the invariant language is a blank string ''. If no specific language description is available. return the ProductName instead.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. you will create two stored procedures to support one of the new reports.GetProductColors stored procedure specification Design.GetProductsAndModels stored procedure specification Design. create and test the stored procedure based on the specifications given in the supporting documentation for the exercise  Task 3: Review the Reports. 4.GetProductColors stored procedure specification • Review the Reports. Tests should have shown that they are working as expected.GetProductsAndModels stored procedure specification • Review the second specification (Reports. you should have created two new stored procedures. guarantees or conditions. and provided to you by QuickStart Intelligence. . The main tasks for this exercise are as follows: 1. The Licensed Content is licensed "as-is.GetProductColors stored procedure • Design. create and test the Reports. It is illegal to reprint. Review the Reports. redistribute.GetProductsAndModels stored procedure  Task 1: Review the Reports. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft.GetProductsAndModels stored procedure • Design.GetProductsAndModels)in the supporting documentation  Task 4: Design. 3. create and test the Reports. create and test the Reports. 2.GetProductColors stored procedure Review the Reports. create and test the Reports. create and test the stored procedure based on the second specifications given in the supporting documentation for the exercise Results: After this exercise.GetProductColors specification in the supporting documentation  Task 2: Design.QuickStart Intelligence 9-42 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Create stored procedures Scenario In this exercise.

redistribute.GetProductsByColor specification in the supporting documentation  Task 2: Design. Please report any unauthorized use of this content to piracy@microsoft.GetProductsByColor stored procedure based on the specifications given in the supporting documentation for the exercise Results: After this exercise. 2. It is illegal to reprint.com or by calling +1 800-785-3448. create and test the Reports. create and test the Reports. guarantees or conditions. you will create another stored procedure that takes parameters.GetProductsByColor stored procedure specification • Review the Reports.GetProductsByColor stored procedure • Design.QuickStart Intelligence Designing and Implementing Stored Procedures 9-43 Exercise 2: Create a parameterized stored procedure Scenario In this exercise." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. Tests should have shown that it is working as expected. The Licensed Content is licensed "as-is. create and test the Reports. Review the Reports. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content.GetProductsByColor stored procedure specification Design. . you should have created a new stored procedure that takes parameters.GetProductsByColor stored procedure  Task 1: Review the Reports. The main tasks for this exercise are as follows: 1.

GetProductsAndModels stored procedure to execute as OWNER and test that the procedure still works. The main tasks for this exercise are as follows: 1.GetProductColors stored procedure to execute as OWNER.GetProductsByColor stored procedure to execute as OWNER and test that the procedure still works.GetProductColors stored procedure to execute as OWNER and test that the procedure still works.QuickStart Intelligence 9-44 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits) Scenario In this exercise.  Task 1: Alter the Reports.GetProductColors stored procedure to execute as OWNER • Alter the Reports. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence.  Task 3: Alter the Reports. 3. It is illegal to reprint. you will alter the stored procedures to use a different execution context.com or by calling +1 800-785-3448.GetProductsAndModels stored procedure to execute as OWNER.GetProductsByColor stored procedure to execute as OWNER • Alter the Reports. Please report any unauthorized use of this content to piracy@microsoft.  Task 2: Alter the Reports. guarantees or conditions. you should have altered the stored procedures to execute as OWNER. redistribute. Results: After this exercise. The Licensed Content is licensed "as-is. Tests should have shown that they are working as expected. or resell this content. Alter the Reports. Alter the Reports.GetProductsAndModels stored procedure to execute as OWNER • Alter the Reports.GetProductsByColor stored procedure to execute as OWNER. 2. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Alter the Reports.

Avoid designing procedures that perform a large number of tasks. rather than granting permissions on the underlying tables to users. tables and other objects within databases. The Licensed Content is licensed "as-is. Use the EXECUTE AS clause to override the execution context of stored procedures that use dynamic SQL. views. Design procedures to perform individual tasks. . 3. or resell this content. redistribute. guarantees or conditions.QuickStart Intelligence Designing and Implementing Stored Procedures 9-45 Module Review and Takeaways Review Questions 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. What does the WITH RECOMPILE option do when used with a CREATE PROC statement? What does the WITH RECOMPILE option do when used with an EXECUTE statement? Best Practices 1. unless those tasks are performed by executing other stored procedures. 2. Keep consistent ownership of stored procedures.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. 2.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. redistribute. It is illegal to reprint. The Licensed Content is licensed "as-is. guarantees or conditions.QuickStart Intelligence 9-46 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. or resell this content.com or by calling +1 800-785-3448. .

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. redistribute. . and provided to you by QuickStart Intelligence.QuickStart Intelligence Merging Data and Passing Tables 10-1 Module 10 Merging Data and Passing Tables Contents: Lesson 1: Using the MERGE Statement 10-3 Lesson 2: Implementing Table Types 10-14 Lesson 3: Using TABLE Types As Parameters 10-22 Lab 10: Passing Tables and Merging Data 10-26 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. It is illegal to reprint. The Licensed Content is licensed "as-is.

QuickStart Intelligence 10-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview Each time a client application makes a call to a SQL Server system. you will be able to: • • • Use the MERGE statement Implement table types Use TABLE types as parameters This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It relates to the latency of the network. In this module you will review the techniques that provide the ability to process sets of data rather than individual rows. Please report any unauthorized use of this content to piracy@microsoft. The basic delay is unrelated to the amount of data being passed. It is illegal to reprint.com or by calling +1 800-785-3448. or resell this content. considerable delay is encountered at the network layer. and provided to you by QuickStart Intelligence. Objectives After completing this lesson. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Each call is termed a "roundtrip". You will then see how these techniques can be used in combination with TABLE parameter types to minimize the number of required stored procedure calls in typical applications. For this reason. redistribute. . The Licensed Content is licensed "as-is. it is important to minimize the number of times that a client needs to call a server for a given amount of data that must be passed between them.

com or by calling +1 800-785-3448. redistribute. It is illegal to reprint. . In this lesson. SQL Server 2008 introduced the MERGE statement that provides this ability plus the ability to process entire sets of data rather than processing row by row or in several separate set-based statements. This leads to much more efficient execution and simplifies the required coding. guarantees or conditions. Objectives After completing this lesson. you will investigate the use of the MERGE statement and the use of the most common options associated with the statement. and provided to you by QuickStart Intelligence. you will be able to: • • • • • • Explain the role of the MERGE statement Describe how to use the WHEN MATCHED clause Describe how to use the WHEN NOT MATCHED BY TARGET clause Describe how to use the WHEN NOT MATCHED BY SOURCE clause Explain the role of the OUTPUT clause and $action Describe MERGE determinism and performance This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The Licensed Content is licensed "as-is. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Merging Data and Passing Tables 10-3 Lesson 1 Using the MERGE Statement A very common requirement when coding in T-SQL is the need to update a row if it exists but to insert the row if it does not already exist." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

updates or deletes occur or none occur. . Source and Target The MERGE statement uses two table data sources. It is important to realize that the MERGE statement functions as an atomic operation in that all inserts. It can operate on entire sets of data rather than just on single rows and can perform alternate actions such as deletes.QuickStart Intelligence 10-4 Implementing a Microsoft® SQL Server® 2008 R2 Database MERGE Statement Key Points The MERGE statement is most commonly used to insert data that does not already exist but to update the data if it does exist. The target table is the table that is being modified and is specified first in the MERGE statement. A typical situation where the need for the MERGE statement arises is in the population of data warehouses from data in source transactional systems." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Some other database engines (not SQL Server) provide an UPSERT statement for this purpose. guarantees or conditions. It is illegal to reprint. or resell this content. Any inserts. When a customer row is received from the transactional system. Atomicity Where statements in other languages typically operate on single rows. the MERGE statement in SQL Server can operate on entire sets of data in a single statement execution. MERGE It is a common requirement to need to update data if it already exists but to insert it if it does not already exist. For example. redistribute. When later updates to the customer are made. Please report any unauthorized use of this content to piracy@microsoft. updates or deletes are applied only to the target table. it needs to be inserted into the data warehouse. consider a data warehouse holding details of a customer. the data warehouse would then need to be updated. The MERGE statement provided by SQL Server is a more capable replacement for such statements in other database engines and is based on the ANSI SQL standard together with some Microsoft extensions to the standard. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. guarantees or conditions. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence Merging Data and Passing Tables 10-5 The source table provides the rows that need to be matched to the rows in the target table. or resell this content. It is specified in a USING clause. redistribute. It is illegal to reprint. You can think of the source table as the incoming data. The source table does not have to be an actual table but can be other types of expressions that return a table such as: • • • • A view A sub-select (or derived table) with an alias A common table expression (CTE) A VALUES clause with an alias The source and target are matched together as the result of an ON clause. This can involve one or more columns from both tables.com or by calling +1 800-785-3448.

WHEN MATCHED . if the source row This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. then the action specified in the first WHEN MATCHED clause is performed. The Licensed Content is licensed "as-is. or resell this content.QuickStart Intelligence 10-6 Implementing a Microsoft® SQL Server® 2008 R2 Database WHEN MATCHED Key Points The WHEN MATCHED clause defines the action to be taken when a row in the source is matched to a row in the target. the first clause must have an AND condition. When two clauses are used. rows in the EmployeeUpdate table are being matched to rows in the Employee table based upon the EmployeeID. a syntax error is returned. The WHEN MATCHED clause specifies the action that needs to occur when a source row matches a target row. If the source row matches the target and also satisfies the AND condition.. the FullName and EmploymentStatus columns in the target table are updated with the values of those columns in the source.. No more than two WHEN MATCHED clauses can be present. and provided to you by QuickStart Intelligence.. . When a source row matches a target row. Multiple Clauses It is also possible to include two WHEN MATCHED clauses such as shown in the following code block: WHEN MATCHED AND s. Note that only the target table can be updated. It is illegal to reprint. guarantees or conditions. WHEN MATCHED The ON clause is used to match source rows to target rows.Quantity > 0 . Please report any unauthorized use of this content to piracy@microsoft. In most cases.. If an attempt is made to modify any other table. this will involve an UPDATE statement but it could alternately involve a DELETE statement.com or by calling +1 800-785-3448. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the example shown in the slide. Otherwise.

or resell this content. the condition in the second WHEN MATCHED clause is evaluated instead. Question: What is different about the UPDATE statement in the example shown. redistribute.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. compared to a normal UPDATE statement? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. It is illegal to reprint.QuickStart Intelligence Merging Data and Passing Tables 10-7 matches the target but does not satisfy the AND condition. and provided to you by QuickStart Intelligence. When two WHEN MATCHED clauses are present. . one action must specify an UPDATE and the other action must specify a DELETE." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

Note again that no table name is included in the action statement (INSERT statement) as modifications may only be made to the target table." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. The most common action performed by a WHEN NOT MATCHED BY TARGET clause is to insert a new row into the target table. The WHEN NOT MATCHED BY TARGET clause is part of the ANSI SQL standard. . The clause is then just written as WHEN NOT MATCHED. best practice suggests including one. In the example shown in the slide. While a column list is optional. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. WHEN NOT MATCHED The next clause in the MERGE statement that you will consider is the WHEN NOT MATCHED BY TARGET statement. the inclusion of a column list is considered a best practice and avoids issues related to changes to the underlying table such as the reordering of columns or the addition of new columns. and provided to you by QuickStart Intelligence. Syntax The words BY TARGET are optional and are often omitted. Please report any unauthorized use of this content to piracy@microsoft. It was mentioned in the last topic that the most common action performed by a WHEN MATCHED clause is to update the existing row in the target table. The Licensed Content is licensed "as-is. redistribute. when a row from the EmployeeUpdate table cannot be found in the Employee table. The same recommendation applies to an INSERT action within a MERGE statement. With a standard INSERT statement in T-SQL. a new employee row would be added into the Employee table. guarantees or conditions. or resell this content.QuickStart Intelligence 10-8 Implementing a Microsoft® SQL Server® 2008 R2 Database WHEN NOT MATCHED BY TARGET Key Points The WHEN NOT MATCHED BY TARGET clause specifies the action that needs to be taken when a row in the source cannot be matched to a row in the target. It is illegal to reprint.

It is illegal to reprint. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. WHEN NOT MATCHED BY SOURCE While much less commonly used than the clauses discussed in the previous topics. Question: What would the DELETE statement look like if it only deleted rows where the date in a column called LastModifed were older than a year? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. all rows in the Employee table that were not matched by an incoming source row from the EmployeeUpdate table would be deleted. redistribute. Generally. At first glance. you can also take an action for rows in the target that did not match any incoming rows from the source. Note the format of the DELETE statement in the example on the slide. The Licensed Content is licensed "as-is.QuickStart Intelligence Merging Data and Passing Tables 10-9 WHEN NOT MATCHED BY SOURCE Key Points The WHEN NOT MATCHED BY SOURCE statement is used to specify an action to be taken for rows in the target that were not matched by rows from the source. and provided to you by QuickStart Intelligence. it might seem quite odd as it has no table or predicate specified. this will involve deleting the unmatched rows in the target table but UPDATE actions are also permitted. In this example.com or by calling +1 800-785-3448.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. employees are deleted when their rows have not been modified within the last ten years. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. . OUTPUT Clause The OUTPUT clause was a useful addition to the INSERT.EmployeeDelete table instead of being returned to the client. Consider the following example: DELETE FROM HumanResources.com or by calling +1 800-785-3448. For example.BusinessEntityID. It is illegal to reprint.-10.NationalIDNumber INTO Audit. As part of this modification. In this example. consider the following code: DELETE FROM HumanResources. this clause can also be used with the MERGE statement.EmployeeDelete WHERE ModifiedDate < DATEADD(YEAR. deleted. In this example.Employee OUTPUT deleted. a set of rows is returned that provides details of the BusinessEntityID and NationalIDNumber for each row deleted.SYSDATETIME()).BusinessEntityID.NationalIDNumber WHERE ModifiedDate < DATEADD(YEAR. this applied to INSERT. In SQL Server 2008 and later.QuickStart Intelligence 10-10 Implementing a Microsoft® SQL Server® 2008 R2 Database OUTPUT Clause and $action Key Points The OUTPUT clause was added in SQL Server 2005 and allows the return of a set of rows when performing data modifications. DELETE and UPDATE. details of the employees being deleted are inserted into the Audit. guarantees or conditions.-10. In 2005. and provided to you by QuickStart Intelligence.Employee OUTPUT deleted. or resell this content. the OUTPUT clause can include an INTO sub-clause that causes the rows to be inserted into another existing table instead. As well as returning rows to the client application. UPDATE and DELETE statements in SQL Server 2005. The Licensed Content is licensed "as-is. deleted.SYSDATETIME()).

The Licensed Content is licensed "as-is. you wish to only audit the deletion. In this example. or resell this content.Action = 'DELETE'.EmployeeID = eu. However. UPDATE and DELETE actions. the OUTPUT clause is being used with the MERGE statement. Note that from SQL Server 2008 onwards. Question: How could the OUTPUT clause be useful in a DELETE statement? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Because a single MERGE statement can perform INSERT.EmployeeID. The enclosed statement must be given an alias. The rowset cannot be used as a general purpose table source but can be used as a table source for an INSERT SELECT statement.FullName. the alias "Mods" has been assigned. It is illegal to reprint. It returns the words "INSERT". You can treat the MERGE statement with an OUTPUT clause as a table source for an INSERT SELECT statement. Please report any unauthorized use of this content to piracy@microsoft. it is now possible to consume the rowset returned by the OUTPUT clause more directly. "UPDATE" or "DELETE".FullName = eu. guarantees or conditions. In this case.FullName. it can be useful to know which action was performed for each row returned by the OUTPUT clause. To make this possible. the OUTPUT clause also supports a $action virtual column that returns details of the action performed on each row. . In this example. When an UPDATE is performed.FullName.Employee AS e USING dbo. rows can be returned from the deleted virtual table.EmploymentStatus WHEN NOT MATCHED THEN INSERT (EmployeeID.EmploymentStatus = eu. and provided to you by QuickStart Intelligence. values will be available in both the inserted and deleted virtual tables. this level of query composability also applies to the OUTPUT clause when used in standard T-SQL INSERT. e. Composable SQL In SQL Server 2008 and later. rows can be returned from the inserted virtual table.EmploymentStatus) OUTPUT $action AS Action. A row would be returned for each row either updated or deleted. When an INSERT is performed.EmployeeUpdate AS eu ON e. Consider the following example: INSERT INTO Audit. only the DELETE actions have been selected. The power of being able to SELECT from a MERGE statement is that you can then apply a WHERE clause. When a DELETE is performed.EmployeeID WHEN MATCHED THEN UPDATE SET e.eu.EmploymentStatus) VALUES (eu.eu. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.EmployeeDelete SELECT Mods.com or by calling +1 800-785-3448.EmployeeID FROM (MERGE INTO dbo.EmployeeID) AS Mods WHERE Mods.deleted. UPDATE and DELETE statements.QuickStart Intelligence Merging Data and Passing Tables 10-11 OUTPUT and MERGE The OUTPUT clause can also be used with the MERGE statement.

redistribute. UPDATE or DELETE statements. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. . if more than one source row matches a target row. If more than a single source row matches a target row. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. UPDATE and DELETE statements and conditional logic. no error is thrown. Performance of MERGE The MERGE statement will often outperform code constructed from separate INSERT. an error occurs and all actions performed by the MERGE statement are rolled back. the MERGE statement only ever makes a single pass through the data. Each source row must match only a single target row or none at all. This is not permitted for an UPDATE action performed within a MERGE statement. Determinism When an UPDATE statement is executed with a join.QuickStart Intelligence 10-12 Implementing a Microsoft® SQL Server® 2008 R2 Database MERGE Determinism and Performance Key Points The actions performed by a MERGE statement are not identical to those that would be performed by separate INSERT. It is illegal to reprint. The Licensed Content is licensed "as-is. In particular.

navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 5. The Licensed Content is licensed "as-is. guarantees or conditions. type Proseware in the Server name text box and click Connect. Question: What is meant by the term "composable query"? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click Open. In the Connect to Server window.ssmssln and click Open. 2.QuickStart Intelligence Merging Data and Passing Tables 10-13 Demonstration 1A: MERGE Statement Key Points In this demonstration you will see: • • • • • How to use the MERGE statement How to use the OUTPUT clause with the MERGE statement How to perform optional updates with MERGE How to use MERGE as a composable query How to use the VALUES clause as a MERGE source Demonstration Steps 1. It is illegal to reprint. . click Microsoft SQL Server 2008 R2. 4. From the File menu.sql script file from within Solution Explorer. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.com or by calling +1 800-785-3448. click All Programs. redistribute. Open and execute the 00 – Setup. 3. click SQL Server Management Studio. and provided to you by QuickStart Intelligence. In the virtual machine. or resell this content.sql script file. click Start. click Project/Solution. Follow the instructions contained within the comments of the script file. Open the 11 – Demonstration 1A. Please report any unauthorized use of this content to piracy@microsoft.

and provided to you by QuickStart Intelligence. SQL Server 2000 introduced the TABLE data type for use as variables. you will be able to: • • • • Explain the need to reduce round-trip overhead Describe previous options for passing lists as parameters Explain the role of the TABLE type Populate TABLE types with row constructors This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. The use of TABLE valued parameters can significantly reduce the number of round trips needed between client application code and SQL Server. The aim is to minimize the amount of time lost through network delays and latency. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 10-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 2 Implementing Table Types It was mentioned earlier that reducing the number of calls between client applications and SQL Server is important. Objectives After completing this lesson." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. redistribute. The Licensed Content is licensed "as-is. SQL Server 2008 introduced the ability to declare these as permanent (or temporary) data types and to use them as parameters.com or by calling +1 800-785-3448. . It is illegal to reprint.

the time taken for commands to be sent to the server and for responses to be received can be substantial. You typically need to do the following: • • • • • • Start a transaction Save the order header Save the first order detail line Save the second order detail line Save the third order detail line Commit the transaction This means that performing a single action results in six separate round trips to the server.QuickStart Intelligence Merging Data and Passing Tables 10-15 Reducing Round-Trip Overhead Key Points In many applications. While the transaction needs to be held open for this time. Causes of Excessive Round Trips Developers often aim to create code that is able to be reused." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. It is desirable then to minimize the number of times this happens in an operation. Consider what is involved in inserting a new customer order into a SQL Server database. Question: How could the number of round trips being made to the server be reduced? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. guarantees or conditions. redistribute. the transaction is being held open for the time to insert the order header and detail lines. It can often be longer than the time to execute the SQL command at the server. One common end result of this is the creation of many small functions and procedures that perform single tasks. Performing a larger task however. . can then require calling many subtasks. The Licensed Content is licensed "as-is. In the previous example. its duration is being artificially increased by the time taken to make all the round trips to the server. and provided to you by QuickStart Intelligence. or resell this content. It is illegal to reprint. This is not desirable. Transaction Duration A golden rule when designing systems to maximize concurrency is to never hold a transaction open for longer than required.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Custom string parsing logic needed to be written. or resell this content. redistribute. The Licensed Content is licensed "as-is. . and provided to you by QuickStart Intelligence. The most commonly used method was to use delimited lists. For example. developers would also sometimes pass XML values as strings but they then needed to write very complex parsing logic. When delimited lists were used. With the introduction of the XML data type. The structure was loose. A string could be passed to code expecting a number. guarantees or conditions. This became more common with SQL Server 2005 when the XML data type was introduced. Mostly these were implemented as comma-delimited lists but other delimiters (eg: pipe) were used.QuickStart Intelligence 10-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Options for Passing Lists as Parameters Key Points One method for reducing the number of round trips from a client application to SQL Server is to pass lists of values in each trip. the entire set of values was sent as a string. the parsing became easier but not trivial. the available options for passing lists of values within a single procedure call were very limited.com or by calling +1 800-785-3448. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. Processing the received XML is also non-trivial and some processing methods (such as OPENXML) had memory implications. while others (such as the nodes() method) had query optimization implications. Passing XML Another option for passing lists of values was to use XML. Prior to SQL Server 2005. Previous Options Prior to SQL Server 2008. In modules 17 and 18 you will learn more about the use of XML in SQL Server. There are issues with doing this: • • • No control was able to be exerted over the data type being passed. one string might contain five columns and another might contain six.

The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. Open the 21 – Demonstration 2A. In the Connect to Server window. Follow the instructions contained within the comments of the script file.sql script file. click Microsoft SQL Server 2008 R2. redistribute. click Project/Solution. • In the virtual machine. guarantees or conditions. click Start. 3." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. type Proseware in the Server name text box and click Connect.ssmssln and click Open. navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ. It is illegal to reprint.QuickStart Intelligence Merging Data and Passing Tables 10-17 Demonstration 2A: Passing Delimited Lists Key Points In this demonstration you will see: • • • • How to query a table-valued function that performs list parsing How the function allows for different delimiters How to use the function in a join How common errors can occur with delimited lists Demonstration Steps 1. . Question: What are the basic problems with using delimited lists for parameters? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click Open. Please report any unauthorized use of this content to piracy@microsoft. • Open and execute the 00 – Setup. or resell this content. 2. click SQL Server Management Studio.sql script file from within Solution Explorer. click All Programs. and provided to you by QuickStart Intelligence. From the File menu.

and provided to you by QuickStart Intelligence.2)). Please report any unauthorized use of this content to piracy@microsoft. TABLE Type In SQL Server 2000.CustomerBalance AS TABLE (CustomerID int.CustomerBalance.com or by calling +1 800-785-3448. You needed to define the schema of the table when declaring the variable such as in the following code: DECLARE @BalanceList TABLE (CustomerID int. CurrentBalance decimal(18. You can create table data types that can be used both for the data type of variables but also for the data type of parameters. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.QuickStart Intelligence 10-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Introduction to the TABLE Type Key Points SQL Server 2008 introduced the ability to create user TABLE data types and record them in the system catalog. SQL Server 2008 introduced the ability to create user-defined table data type definitions. In this example. only last for the duration of the batch in which the variable is defined. GO DECLARE @BalanceList dbo. It is illegal to reprint. The schema of the table and the variable. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. it was possible to declare a variable of type TABLE. redistribute. The Licensed Content is licensed "as-is.2)). In the example shown on the slide. guarantees or conditions. CurrentBalance decimal(18. . a variable called @BalanceList is defined as being a table. CustomerBalance is declared as a new data type. These types are very useful as they can be used for both variables and for parameters. You can declare a variable as being of CustomerBalance data type as follows: CREATE TYPE dbo.

com or by calling +1 800-785-3448. Note that there is no ALTER TYPE statement that can be used to modify the TABLE type definition.QuickStart Intelligence Merging Data and Passing Tables 10-19 A key advantage of table data types is that you can pass complex structures inside a table more easily than you could in alternatives such as comma-delimited lists. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. which leads to less potential inconsistencies. . This is also useful even when declaring variables as a table type can be created and then used for variables through the database application. guarantees or conditions. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Types must be dropped and then recreated when they need to be altered. The Licensed Content is licensed "as-is. You can have multiple rows each of two or more columns and you can be sure of the data types that will be stored. It is illegal to reprint.

and provided to you by QuickStart Intelligence.QuickStart Intelligence 10-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Populating TABLE Types with Row Constructors Key Points SQL Server 2008 also introduced the concept of row constructors and multi-row INSERT statements. That data type was the table data type that was defined in the example from the previous topic. SQL Server 2008 introduced the concept of a row constructor.. Note that a multi-row INSERT that inserts 3 rows is quite different to 3 separate INSERT statements.EXEC statement was used.. It is an atomic operation involving 3 rows in that all inserts occur or none occur. Question: What would improve the INSERT query shown in the slide example? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. a variable named @Balance of type dbo. . or resell this content. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448.CustomerBalance has been declared. In the example shown in the slide. It is illegal to reprint. redistribute. guarantees or conditions. Note also that multi-row INSERT statements cannot include more than 1000 rows per statement and that multi-row INSERTS also help reduce the number of roundtrips from a client application to a server. Three rows have then been inserted into the table variable. These are useful when working with TABLE data types as well as when working with database tables." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Row Constructors for Populating TABLE Types Versions of SQL Server prior to SQL Server 2008 only permitted inserting a single row of data at a time with an INSERT statement unless an INSERT…SELECT or INSERT.

click Microsoft SQL Server 2008 R2. It is illegal to reprint. In the Connect to Server window. From the File menu. 3. The Licensed Content is licensed "as-is. • Open and execute the 00 – Setup. navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ. Open the 22 – Demonstration 2B.sql script file. click Open. click Start. or resell this content. How to work with row constructors How to declare a table data type How to work with variables with user-defined table data types Demonstration Steps 1. and provided to you by QuickStart Intelligence. click All Programs. click Project/Solution.ssmssln and click Open.com or by calling +1 800-785-3448. Follow the instructions contained within the comments of the script file. 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. type Proseware in the Server name text box and click Connect. guarantees or conditions. .sql script file from within Solution Explorer. 2. click SQL Server Management Studio. redistribute. Question: Can other users make use of the table type that you create? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • In the virtual machine.QuickStart Intelligence Merging Data and Passing Tables 10-21 Demonstration 2B: TABLE Types and Row Constructors Key Points In this demonstration you will see: 1. Please report any unauthorized use of this content to piracy@microsoft. 3.

com or by calling +1 800-785-3448. particularly for use with stored procedures but also able to be used with user-defined functions. redistribute. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. Another potential use for the TABLE data types is in the declaration of parameters. In this lesson. guarantees or conditions. It is illegal to reprint. You will also see how to call a stored procedure when passing a table valued parameter. you will be able to: • • Describe the use of TABLE input parameters for stored procedures Use row constructors to populate parameters to be passed to stored procedures This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. . Objectives After completing this lesson." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is.QuickStart Intelligence 10-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Using TABLE Types As Parameters In the previous lesson you saw how to declare TABLE data types and how to declare variables of those types. you will see how to use TABLE input parameters to stored procedures and see how this solves the round trip problems identified in lesson 1. or resell this content.

The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. That single stored procedure could also begin and commit the transaction so the transaction would not span even a single network round trip.com or by calling +1 800-785-3448. a data type called SalesDetails is being created to hold the detail lines for a customer sale. What is more interesting though is that you could pass multiple order headers and their corresponding order detail rows in a single call. and provided to you by QuickStart Intelligence. Note that the term READONLY must be specified and that it is the only allowable value.QuickStart Intelligence Merging Data and Passing Tables 10-23 TABLE Input Parameters for Stored Procedures Key Points As well as being used for declaring variables. the requirements for saving a customer order were noted. Please report any unauthorized use of this content to piracy@microsoft. Using this same technique. In the example shown in the slide. guarantees or conditions. Question: What would you have to do to be able to pass multiple sales and their detail lines in a single call? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Table Valued Parameters Table-valued parameters can only be used as input parameters. or resell this content. (User-defined functions will be discussed in Module 13). A stored procedure is then being created that takes sales header details as standard relational parameters but also takes the entire list of sales details rows as a single parameter. user-defined table data types can be used as parameter data types for stored procedures and functions. redistribute. This allows for the creation of a stored procedure that would process an entire sale in a single call. This means that the procedure could now save one or more orders with all their detail rows in a single round-trip to the server. Reducing Round Trips In an earlier discussion. . you could place the order header in one table and all the order rows in another table and pass both in a single call to a stored procedure that saves the order. It is illegal to reprint.

First. . You will see this in detail in the upcoming demonstration. Please report any unauthorized use of this content to piracy@microsoft. Passing a Table Valued Parameter in an EXEC Statement As well as defining a table-valued parameter for a stored procedure. Finally. The final step in using such a procedure is to then pass a table parameter in the EXEC statement. you also need to construct a table to pass to the stored procedure in the EXEC call. you populate that variable.QuickStart Intelligence 10-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Using Row Constructors to Populate Parameters Key Points In the previous topic. you saw how to declare a stored procedure that uses a table-valued parameter. Row constructors are ideal for populating the table variables that will be passed in an EXEC call." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. the stored procedure is called via an EXEC statement and the detail rows are passed as a single parameter.com or by calling +1 800-785-3448. you declare a table variable with the same user-defined table data type that was used when declaring the stored procedure. or resell this content. redistribute. guarantees or conditions. and provided to you by QuickStart Intelligence. It is illegal to reprint. In the example shown in the slide. The Licensed Content is licensed "as-is. three product detail rows are being inserted into the @SalesDetails variable. Next.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.sql script file from within Solution Explorer. It is illegal to reprint. How traditional stored procedure calls often involve multiple round trips to the server How to declare a table data type How to use the table data type to avoid round trips How to view catalog information about the table data types by querying the sys. click All Programs. guarantees or conditions. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Project/Solution.sql script file.ssmssln and click Open.com or by calling +1 800-785-3448. From the File menu.types and sys. Follow the instructions contained within the comments of the script file. 2. click Open. . click SQL Server Management Studio. click Start. navigate to D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ. • In the virtual machine. Question: What is the purpose of the SCOPE_IDENTITY() function shown in the demonstration? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 3. click Microsoft SQL Server 2008 R2. or resell this content.table_types system views Demonstration Steps 1. 3. 2. type Proseware in the Server name text box and click Connect. In the Connect to Server window. Please report any unauthorized use of this content to piracy@microsoft. redistribute. • Open and execute the 00 – Setup. Open the 31 – Demonstration 3A.QuickStart Intelligence Merging Data and Passing Tables 10-25 Demonstration 3A: Passing Tables to Stored Procedures Key Points In this demonstration you will see: 1. The Licensed Content is licensed "as-is. 4. and provided to you by QuickStart Intelligence.

wait until the Press CTRL+ALT+DELETE to log on message appears. • Right-click 623XB-MIA-DC and click Connect. and provided to you by QuickStart Intelligence. Before you begin the lab. 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-DC is not started: • Right-click 623XB-MIA-DC and click Start. On the host computer. click Start.com or by calling +1 800-785-3448. and then click Other User. Please report any unauthorized use of this content to piracy@microsoft. click on the Revert toolbar icon. click Revert. 5. If you are prompted to confirm that you want to revert. In Virtual Machine Connection window. • Click Switch User. you will use the available virtual machine environment. 7. if the user is not already logged on: • On the Action menu. It is illegal to reprint. 2. and then click Hyper-V Manager." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. 6. you must complete the following steps: 1. click the Ctrl-Alt-Delete menu item. In the Virtual Machines list. • Log on using the following credentials: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. . and then close the Virtual Machine Connection window. redistribute. guarantees or conditions. • In the Virtual Machine Connection window. point to Administrative Tools. 4. • In the Virtual Machine Connection window.QuickStart Intelligence 10-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 10: Passing Tables and Merging Data Lab Setup For this lab. The Licensed Content is licensed "as-is. In the Virtual Machines list. • Right-click 623XB-MIA-SQL and click Connect. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. 3.

9. redistribute. click Microsoft SQL Server 2008 R2. If time permits. In Connect to Server window. you will create a replacement stored procedure Reports. click Start. If the Server Manager window appears.sql. From the View menu. Notes: The SalespersonID must be provided. click Full Screen Mode. check the Do not show me this console at logon check box and close the Server Manager window. 14. The Licensed Content is licensed "as-is. Password: Pa$$w0rd 8. In the File menu. click Open. SQL Server 2008 introduced the table type and table-valued parameters. and provided to you by QuickStart Intelligence. 12. MiddleName.ssmssln. The parameter should be named: SalespersonDetails Output Parameters: None Output Rows: For each row. If it matches an existing salesperson. including SalespersonID. Only update columns that are provided. 13. double-click the query 00-Setup. click Execute on the toolbar. 15.QuickStart Intelligence Merging Data and Passing Tables 10-27 i.SalespersonMerge Requirements Input Parameters: Table of Salesperson details. in the Virtual Machine Connection window. In the Authentication drop-down list box. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. LastName.GetProductsByColorList that was based on passing a comma-delimited list of values. In this lab. return one column called Action that contains INSERT or UPDATE and another column with the SalespersonID.SalesTerritory table. and click SQL Server Management Studio. select Windows Authentication and click Connect. Supporting Documentation Procedure Required: Marketing. FirstName. In Solution Explorer. In the virtual machine." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click All Programs. 10. you will then create a new procedure that processes complete rows of data and performs updates using the MERGE statement. EmailAlias. User name: AdventureWorks\Administrator ii. Any SalesTerritoryID that is provided must be valid as it is defined as a foreign key to the Marketing.GetProductsByColorList_Test that uses a table-valued parameter to replace an existing stored procedure Reports. Lab Scenario In earlier versions of SQL Server. SalesTerritoryID.com or by calling +1 800-785-3448. 11. It is illegal to reprint. In the Open Project window. . type Proseware in the Server name text box. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. BadgeNumber. guarantees or conditions. When the query window opens. passing lists of values to stored procedures was a challenge. open the project D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ. that row should be updated. and click Project/Solution.

or resell this content. Please report any unauthorized use of this content to piracy@microsoft. 3. redistribute.GetProductsByColorList  Task 2: Review the existing function • Review the function dbo. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Review the parameters of a stored procedure Review the existing function Create a new table type  Task 1: Review the parameters of a stored procedure • Review the parameters of the existing stored procedure Reports. guarantees or conditions.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence.StringListToTable used by the existing stored procedure. 2. Note the hardcoded length of 1000 for each component of the returned table entries  Task 3: Create a new table type • Create a new table type to support this type of input parameter. The Licensed Content is licensed "as-is. you will create a table type to support the parameter that will later need to be passed to the replacement stored procedure.QuickStart Intelligence 10-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Create a Table Type Scenario In this exercise. The main tasks for this exercise are as follows: 1. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . you have created a new table type. Call the type StringList Results: After this exercise.

you will create a replacement stored procedure Reports. redistribute. you should have created a new stored procedure that uses the table type for its parameter. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.GetProductsByColorList_Test) takes a single table @ColorList as a parameter  Task 2: Test the new procedure • Test the new procedure Results: After this exercise. or resell this content. The main tasks for this exercise are as follows: 1.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.GetProductsByColorList_Test that uses the table type for its parameter.QuickStart Intelligence Merging Data and Passing Tables 10-29 Exercise 2: Use a Table Type Parameter Scenario In this exercise. . Create the stored procedure Test the stored procedure  Task 1: Create the stored procedure • Create a new stored procedure that is functionally equivalent to Reports. guarantees or conditions. 2.GetProductsByColorList except that the new procedure (call it Reports.

QuickStart Intelligence 10-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits) Scenario In this exercise. The procedure should allow for the creation or update of salespeople held in the Marketing. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.Salesperson table. It is illegal to reprint. 2. or resell this content. Create a new table type Create a replacement procedure Test the replacement procedure. you will create a new stored procedure that takes a table-valued parameter and uses the MERGE statement to update a table in the marketing system. 3. .com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. (Create it in the dbo schema)  Task 2: Create a replacement stored procedure • Review the supporting documentation and create a replacement procedure based on the requirements  Task 3: Test the replacement procedure • Test the replacement procedure Results: After this exercise. and provided to you by QuickStart Intelligence. you should have created a new stored procedure that takes a table-valued parameter and uses the MERGE statement to update a table.  Task 1: Create a new table type • Create the required table type. guarantees or conditions. redistribute. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The main tasks for this exercise are as follows: 1.

Please report any unauthorized use of this content to piracy@microsoft. very minor changes are required to construct a stored procedure that can insert multiple sales orders compared to a stored procedure that can insert a single sales order. For example. .QuickStart Intelligence Merging Data and Passing Tables 10-31 Module Review and Takeaways Review Questions 1. The Licensed Content is licensed "as-is. redistribute. 2.com or by calling +1 800-785-3448. the detail rows of an invoice. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. What is the difference between SOURCE NOT MATCHED and TARGET NOT MATCHED in a MERGE statement? What is a key advantage of the MERGE statement in terms of performance? Best Practices 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 2. and provided to you by QuickStart Intelligence. guarantees or conditions. for example. Consider making multiple-entity procedures instead of single-entity procedures to help minimize round trip behavior and to reduce locking. It is illegal to reprint. or resell this content. Use multi-row inserts when the rows being inserted are related in some way.

QuickStart Intelligence

10-32

Implementing a Microsoft® SQL Server® 2008 R2 Database

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-1

Module 11
Creating Highly Concurrent SQL Server 2008 R2 Applications
Contents:
Lesson 1: Introduction to Transactions

11-3

Lesson 2: Introduction to Locks

11-17

Lesson 3: Management of Locking

11-28

Lesson 4: Transaction Isolation Levels

11-38

Lab 11: Creating Highly Concurrent SQL Server Applications

11-44

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-2

Implementing a Microsoft® SQL Server® 2008 R2 Database

Module Overview

It is the responsibility of an enterprise database system to provide mechanisms ensuring the physical
integrity of each transaction. A transaction is a sequence of operations performed as a single logical unit
of work, and Microsoft® SQL Server™ provides locking facilities that preserve transaction isolation. In this
module, you will learn how to manage transactions and locks.
Database systems struggle with the need to balance consistency and concurrency. There is often a direct
trade-off between these two aims. The challenge is to use the lowest concurrency impact possible while
still maintaining sufficient consistency.
This module explains how to use transactions and the SQL Server locking mechanisms to meet the
performance and data integrity requirements of your applications.
Another aim of database management systems is to provide each user with the illusion wherever possible
that they are the only user on the system. Transaction isolation levels are critical to minimizing the impact
of one user on another. In this module you will also investigate transaction isolation levels.

Objectives
After completing this module, you will be able to:



Describe the role of transactions
Explain the role of locks
Manage locking
Work with transaction isolation levels

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-3

Lesson 1

Introduction to Transactions

A core capability provided by relational database management systems such as SQL Server is to provide
the ability to group a set of changes that need to be made and to ensure that the entire set of changes
occurs or that none occur. Transactions are how this requirement is met within SQL Server.

Objectives
After completing this lesson, you will be able to:





Explain what transactions are
Describe auto commit transactions
Describe explicit transactions
Describe implicit transactions
Explain the role of transaction recovery
Detail considerations for using transactions

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-4

Implementing a Microsoft® SQL Server® 2008 R2 Database

What are Transactions?

Key Points
A transaction is a sequence of steps that perform a logical unit of work. They must exhibit four properties
that are collectively known as ACID.

Atomicity
Atomicity says that either all the steps in the transaction must succeed or none of them should be
performed.

Consistency
Consistency ensures that when the transaction is complete, data must be in a consistent state. A consistent
state is one where the data is consistent with the business rules related to the data. Inconsistent data
violates one or more business rules. In SQL Server, the database has to be in a consistent state after each
statement within a transaction and not only at the end of the transaction.

Isolation
Isolation defines that changes made by a transaction must be isolated from other concurrent transactions.

Durability
Durability defines that when the transaction is complete, the changes must be made permanent in the
database and must survive even system failures.
Transactions ensure that multiple data modifications are processed as a unit. For example, a banking
transaction might credit one account and debit another. Both steps must be completed together or not at
all. SQL Server supports transaction processing to manage multiple transactions.

Transaction Log
Every transaction is recorded in a transaction log to maintain database consistency and to aid in
transaction recovery. When changes are made to data in SQL Server, the database pages that have been
This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-5

modified are written to the transaction log on the disk first and later written to the database. If any part of
the transaction fails, all of the changes made so far are rolled back to leave the database in its original
state. This system ensures that updates are complete and recoverable.
Transactions use locking to prevent other users from changing or reading data in a transaction that has
not completed. Locking is required in online transaction processing (OLTP) for multi-user systems.
Question: Can you think of database operations in your organization where database transactions are
especially critical?

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-6

Implementing a Microsoft® SQL Server® 2008 R2 Database

Auto Commit Transactions

Key Points
Autocommit mode is the default transaction management mode of the SQL Server Database Engine.
Every Transact-SQL statement is committed or rolled back when it completes. If a statement completes
successfully, it is committed; if it encounters any error, it is rolled back.

Autocommit Mode
A connection to an instance of the Database Engine operates in autocommit mode whenever this default
mode has not been overridden by either explicit or implicit transactions. Autocommit mode is also the
default mode for ADO, OLE DB, ODBC, and DB-Library.
A connection to an instance of the Database Engine operates in autocommit mode until a BEGIN
TRANSACTION statement starts an explicit transaction, or implicit transaction mode is set on. When the
explicit transaction is committed or rolled back, or when implicit transaction mode is turned off, the
connection returns to autocommit mode.
If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the
Database Engine is to roll back only the statement that generated the error. You can change this behavior
using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement
error causes the batch to quit and if you are currently in a transaction, that would cause an automatic
rollback of the current transaction.

Compile Errors
Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. When working in autocommit
mode, compile time errors can cause more than one Transact-SQL statement to fail. In this mode, a batch
of statements is compiled as a unit and if a compile error is found, nothing in the batch is compiled or
executed. The following example shows how this might happen.
USE AdventureWorks2008;
GO

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

CREATE
GO
INSERT
INSERT
INSERT
GO
SELECT
GO

11-7

TABLE NewTable (Id INT PRIMARY KEY, Info CHAR(3));
INTO NewTable VALUES (1, 'aaa');
INTO NewTable VALUES (2, 'bbb');
INTO NewTable VALUSE (3, 'ccc');
* FROM NewTable;

-- Syntax error.

-- Returns no rows.

Because there is a typographical error in the third INSERT statement, the batch cannot compile, and so
none of the three INSERT statements run.
XACT_ABORT can convert statement terminating errors into batch terminating errors. It will be covered in
more detail in the T-SQL Error Handling module.
Question: When might autocommit mode not be appropriate in a database application?

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-8

Implementing a Microsoft® SQL Server® 2008 R2 Database

Explicit Transactions

Key Points
An explicit transaction is one in which you explicitly define both the start and end of the transaction. You
can use explicit transactions to define your own units of business logic. For example, in a bank transfer
function, you might enclose the withdrawal of funds from one account and the deposit of those funds in
another account within one logical unit of work. DB-Library applications and Transact-SQL scripts use the
BEGIN TRANSACTION, COMMIT TRANSACTION, COMMIT WORK, ROLLBACK TRANSACTION, or
ROLLBACK WORK Transact-SQL statements to define explicit transactions.

Starting a Transaction
You start a transaction by using the BEGIN TRANSACTION statement. You can specify a name for the
transaction, and you can use the WITH MARK option to specify a description for the transaction to be
marked in the transaction log. This transaction log mark can be used when restoring a database to
indicate the point to which you want to restore. The BEGIN TRANSACTION statement is often abbreviated
to BEGIN TRAN.
XACT_ABORT has an effect on explicit transaction as well as on implicit transactions. By default, only the
statement in error would be rolled back and the batch would continue to run and commit the other
statements in the transaction.
Therefore error handling must be implemented (which will be discussed in a later module) or
XACT_ABORT can be turned on to abort the batch and rollback the whole transaction in case of an error.

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

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-9

The COMMIT TRANSACTION statement is often abbreviated to just the word COMMIT. To assist users
from other database platforms that are migrating to SQL Server, the statement COMMIT WORK can also
be used.

Rolling Back a Transaction
You can cancel the work contained in a transaction by issuing the ROLLBACK TRANSACTION statement.
Use this to end a transaction if errors have occurred and you want the contents of the transaction to be
undone and the database to remain in the state it was before the transaction began.
The ROLLBACK TRANSACTION statement is often abbreviated to just the word ROLLBACK. To assist users
from other database platforms that are migrating to SQL Server, the statement ROLLBACK WORK can also
be used.

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

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-10

Implementing a Microsoft® SQL Server® 2008 R2 Database

Implicit Transactions

Key Points
When a connection is operating in implicit transaction mode, the database engine automatically starts a
new transaction after the current transaction is committed or rolled back. You do nothing to delineate the
start of a transaction; you only commit or roll back each transaction. Implicit transaction mode generates
a continuous chain of transactions.

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

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

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

Starting Implicit Transactions
When using implicit transaction mode, a transaction is automatically started when any of the following
statements are executed:

ALTER TABLE

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications











11-11

CREATE
DELETE
DROP
FETCH
GRANT
INSERT
OPEN
REVOKE
SELECT
TRUNCATE TABLE
UPDATE

Nested transactions (where a transaction is started within another transaction) are not allowed in implicit
transaction mode. If the connection is already in a transaction, these statements do not start a new
transaction.

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

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-12

Implementing a Microsoft® SQL Server® 2008 R2 Database

Transaction Recovery

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

Checkpoints
As each Transact-SQL statement is executed, it is recorded to the transaction log on disk before it is
written to the database and before the user is notified that the transaction was committed successfully.
SQL Server performs checkpoints at defined intervals. Checkpoints are marked in the transaction log to
identify which transactions have already been applied to the database. When a new checkpoint occurs, all
data pages in memory that have been modified since the last checkpoint are written to the database.

Transaction Recovery
If any errors occur during a transaction, the instance of SQL Server uses the information in the log file to
roll back the transaction. This rollback does not affect the work of any other users working in the database
at the same time. Usually, the error is returned to the application, and if the error indicates a possible
problem with the transaction, the application issues a ROLLBACK statement.
Some errors, such as a 1205 deadlock error, roll back a transaction automatically. If anything stops the
communication between the client and an instance of SQL Server while a transaction is active, the instance
rolls back the transaction automatically when notified of the stoppage by the network or operating
system. This could happen if the client application terminates, if the client computer is shut down or
restarted, or if the client network connection is broken. In all of these error conditions, any outstanding
transaction is rolled back to protect the integrity of the database.

System Failures and Restarts
The recovery process runs automatically every time that SQL Server starts, such as after an intended
shutdown or a power failure. The automatic recovery process uses the transaction log to roll forward any

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-13

committed transactions and roll back any incomplete transactions. The log uses the last checkpoint as a
starting marker knowing that all transactions committed before this were written to the database and that
all transactions that started before this, but were still active, need to be rolled back as the changes where
already written to the data files.
In the slide example:


Transaction 1 is committed before the checkpoint, so it is reflected in the database.
Transactions 2 and 4 were committed after the checkpoint, so they must be reconstructed from the
log (rolled forward).
Transactions 3 and 5 were not committed, so SQL Server rolls them back.

Question: A server crash occurs while two transactions are running. Transaction A is an autocommit
transaction that has been written to the transaction log, but not written to the disk. Transaction B is an
explicit transaction that has not been committed, though a checkpoint was written while Transaction B
was running. What will happen to each transaction when the server is recovered?

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-14

Implementing a Microsoft® SQL Server® 2008 R2 Database

Considerations for using Transactions

Key Points
There are a number of general considerations that need to be kept in mind when working with
transactions.

Keep transactions as short as possible
Transactions should be as short as possible. Longer transactions increase the likelihood that users will not
be able to access locked data. Some methods to keep transactions short include the following:



Do not require input from users during a transaction. Address issues that require user interaction
before you start the transaction. For example, if you are updating a customer record, obtain the
necessary information from the user before you begin the transaction. A golden rule here is to never
hold a transaction across a user interaction.
Do not open a transaction while browsing through data, if at all possible. Transactions should not
start until all preliminary data analysis has been completed.
INSERT, UPDATE, and DELETE should be the primary statements in a transaction, and they should be
written to affect the fewest number of rows. A transaction should never be smaller than a logical unit
of work.
Access the least amount of data possible while in a transaction. This decreases the number of locked
rows and reduces contention.
Ensure appropriate indexing is in place as this reduces the number of pages that need to be accessed
and locked.

Try to access resources in the same order
Accessing resources in the same order within transactions tends to naturally serialize your access to the
database and can help to avoid deadlocks. However, doing this is not always possible.
Note that deadlocks will be discussed later in the module.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-15

Considerations for nested transactions
Consider the following issues regarding nested transactions:


You should use nesting carefully, if at all, because the failure to commit or roll back a transaction
leaves locks in place indefinitely.
You can use the @@trancount global variable to determine whether any open transactions exist and
how deeply they are nested
While SQL Server's syntax appears to support transaction nesting, a commonly misunderstood aspect
of SQL Server transaction handling is that a ROLLBACK operation that occurs in a nested transaction
will roll back all current transactions, not just the current level.

Question: When would nested transactions be appropriate?

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-16

Implementing a Microsoft® SQL Server® 2008 R2 Database

Demonstration 1A: Transactions

Key Points
In this demonstration you will see:

How transactions work
How blocking affects other users
Note that blocking is discussed further in the next lesson

Demonstration Steps
1.

Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.

2.

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_11_PRJ\6232B_11_PRJ.ssmssln and click Open.

3.

Open and execute the 00 – Setup.sql script file from within Solution Explorer.

4.

Open the 11 – Demonstration 1A.sql script file.

5.

Open the 12 – Demonstration 1A 2nd Window.sql script file.

6.

Follow the instructions contained within the comments of the script file.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Highly Concurrent SQL Server 2008 R2 Applications

11-17

Lesson 2

Introduction to Locks

SQL Server (and many other database engines) makes extensive use of locks when ensuring isolation
between users and consistency of transactions. It is important to have an understanding of how locking
works and to understand how locking differs from blocking.

Objectives
After completing this lesson, you will be able to:






Detail different methods of Concurrency Control
Explain what locks are
Differentiate between blocking vs locking
Describe what concurrency problems are prevented by locking
Detail SQL Server's lockable resources
Describe the types of locks that are available
Explain lock compatibility

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

guarantees or conditions. or resell this content. The Licensed Content is licensed "as-is. redistribute. and provided to you by QuickStart Intelligence. pessimistic and optimistic. when an update is performed. Question: Can you think of an application in your organization that might work well with optimistic concurrency control? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and the user must start over. the transaction rolls back. SQL Server checks to determine whether the underlying data was changed since it initially read it. Other users cannot then perform actions that would alter the underlying data until the user who applied the lock is done with the data. Rather. Pessimistic Concurrency Control Pessimistic concurrency control locks data when data is read in preparation for an update. Optimistic concurrency control works well where a low level of contention for data exists. If so. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Users specify the type of concurrency control by specifying the transaction isolation level for a connection. Optimistic Concurrency Control Optimistic concurrency control does not hold locks on data after the data is initially read. Concurrency control ensures that modifications made by one person do not adversely affect modifications that others make. Concurrency Control SQL Server supports a wide range of optimistic and pessimistic concurrency control mechanisms.QuickStart Intelligence 11-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Methods of Concurrency Control Key Points Concurrency control is system of controls that administers many people trying to access the same data at the same time so they do not adversely affect each other. the user receives an error. There are two types of concurrency control. . It is illegal to reprint.com or by calling +1 800-785-3448.

com or by calling +1 800-785-3448. such as by reading or modifying the data. The transaction does this by requesting a lock on the piece of data. Write locks stop others from reading or writing. The lock mode defines the level of dependency the transaction has on the data. Read locks allow others to read but not write data. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the instance of the Database Engine will pause the requesting transaction until the first lock is released. it must protect itself from the effects of another transaction modifying the same data. and provided to you by QuickStart Intelligence. these locks are implemented via different locking modes. No transaction can be granted a lock that would conflict with the mode of a lock already granted on that data to another transaction. In SQL Server. it holds the lock protecting the modification until the end of the transaction. redistribute. how might locks play a role in that application? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-19 What are Locks? Key Points Locking is a mechanism used by the Database Engine to synchronize access by multiple users to the same piece of data at the same time. Question: If a doctor's office uses a database application to manage patient records. Locking Behavior Before a transaction acquires a dependency on the current state of a piece of data. such as shared or exclusive. guarantees or conditions. It is illegal to reprint. When a transaction modifies a piece of data. All locks held by a transaction are released when the transaction completes (either commits or rolls back). . If a transaction requests a lock mode that conflicts with a lock that has already been granted on the same data. How long a transaction holds the locks acquired to protect read operations depends on the transaction isolation level setting. The Licensed Content is licensed "as-is.

QuickStart Intelligence 11-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Blocking vs. or resell this content. redistribute. The Licensed Content is licensed "as-is. Question: What symptoms do you imagine that "excessive" blocking might relate to? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Locking Locking is the action of taking and holding locks that is used to implement concurrency control. . Blocking is a normal occurrence for systems that use locking. Locking Key Points The two terms locking and blocking are not the same thing and are often confused for each other." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Blocking Blocking is what happens to one process while it needs to wait for a resource that another process has locked. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. It is only excessive blocking that is a problem. guarantees or conditions. It is illegal to reprint.

Inconsistent analysis is similar to uncommitted dependency in that another transaction is changing the data that a second transaction is reading.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-21 What Concurrency Problems are Prevented by Locking? Key Points Users modifying data can affect other users who are reading or modifying the same data at the same time. If another user changes the index key column of the row during your read. The transaction's first read of the range of rows shows a row that no longer exists in the second or succeeding read as a result of a deletion by a different transaction. the data read by the second transaction was committed by the transaction that made the change. If a data storage system has no concurrency control. the row might appear again if the key change moved the row to a position ahead of your scan. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. Similarly. which results in lost data. The second transaction is reading data that has not been committed yet and may be changed by the transaction updating the row. Common Concurrency-related Problems Lost updates occur when two or more transactions select the same row and then update the row based on the value originally selected.com or by calling +1 800-785-3448. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. The Licensed Content is licensed "as-is. Similarly. Uncommitted dependency (or dirty read) occurs when a second transaction selects a row that is being updated by another transaction. the row might not appear if the key change moved the row to a position in the index that you had already read. Please report any unauthorized use of this content to piracy@microsoft. Each transaction is unaware of the other transactions. The last update overwrites updates made by the other transactions. users could see the side effects listed on the slide. Phantom reads occur when an insert or delete action is performed against a row that belongs to a range of rows being read by a transaction. redistribute. in inconsistent analysis. It occurs when a second transaction accesses the same row several times and reads different data each time. . Inconsistent analysis is also known as non-repeatable reads. However. the transaction's second or succeeding read shows a row that did not exist in the original read as the result of an insertion by a different transaction. and provided to you by QuickStart Intelligence. These users are said to be accessing the data concurrently.

. The Licensed Content is licensed "as-is. It is illegal to reprint.QuickStart Intelligence 11-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Question: Has your organization experienced concurrency problems with database applications? If so. what behavior did you see? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. redistribute. guarantees or conditions.

Question: If a database needs to lock several rows of data at once. guarantees or conditions. and provided to you by QuickStart Intelligence. To minimize the cost of locking. redistribute. SQL Server automatically locks resources at a level that is appropriate to the task. or resell this content. what resources might be locked? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. the number of locks that SQL Server maintains must be balanced with the amount of data that each lock holds. . The Licensed Content is licensed "as-is.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-23 Lockable Resources Key Points For optimal performance." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. It is illegal to reprint.

redistribute. • A transaction cannot acquire a shared lock on a resource that has an exclusive lock. data cannot be modified. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. If SQL Server has applied a shared lock to a resource. • A transaction cannot acquire an exclusive lock on a resource until all shared locks are released. Basic Locks In general.com or by calling +1 800-785-3448. • Shared locks. or resell this content. Consider the following facts about exclusive locks: • Only one transaction can acquire an exclusive lock on a resource. Special Situation Locks Depending on the situation." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. SQL Server has two main types of locks: basic locks and locks for special situations. a second transaction also can acquire a shared lock. Exclusive locks. guarantees or conditions. • A shared lock will exist until all rows that satisfy the query have been returned to the client. Consider the following facts about shared locks: • • They are used for read-only operations.QuickStart Intelligence 11-24 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of Locks Key Points SQL Server locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions. Please report any unauthorized use of this content to piracy@microsoft. SQL Server typically uses shared (read) locks for operations that neither change nor update data. SQL Server uses exclusive (write) locks for the INSERT. SQL Server can use other types of locks: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • SQL Server releases shared locks on a record as soon as the next record is read. even though the first transaction has not completed. UPDATE. and write operations acquire exclusive locks. and DELETE data modification statements. read operations acquire shared locks. .

For example. SQL Server uses intent locks internally to minimize locking conflicts. or its schema modified. guarantees or conditions. Intent locks include intent share (IS). It is illegal to reprint. which ensures that a resource is not dropped. Update locks are: • • Acquired during the initial portion of an update operation when the pages are first being read. SQL Server provides two types of schema locks: • • Schema stability (Sch-S). Before it modifies the page. Consider the following facts about update locks. SQL Server uses update locks when it will modify a page at a later point. Intent locks establish a locking hierarchy so that other transactions cannot acquire locks at more inclusive levels. intent exclusive (IX). redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Schema locks. The Licensed Content is licensed "as-is. SQL Server uses these to enable processes to bulk copy data concurrently into the same table while preventing other processes that are not bulk-copying data from accessing the table.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications • 11-25 Intent locks. or resell this content. Bulk update locks. SQL Server uses these to ensure that a table or index is not dropped. • Update locks. . • Compatible with shared locks. SQL Server uses bulk update locks when either of the following is used: the TABLOCK hint or the table lock on bulk load option. which ensures that other sessions do not reference a resource that is under modification. if a transaction has an exclusive row-level lock on a specific customer record. Please report any unauthorized use of this content to piracy@microsoft. Question: What happens if a query tries to read data from a row that is currently locked by an exclusive (X) lock? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and shared with intent exclusive (SIX). SQL Server promotes the update page lock to an exclusive page lock to prevent locking conflicts. the intent lock prevents another transaction from acquiring an exclusive lock at the table-level.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. • Schema modification (Sch-M). when it is referenced by another session.

For example. It is illegal to reprint.QuickStart Intelligence 11-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Lock Compatibility Key Points Some locks are compatible with other locks. Please report any unauthorized use of this content to piracy@microsoft. compatibility for schema locks is as follows: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Lock Compatibility Locks have a compatibility matrix that shows which locks are compatible with other locks that are established on the same resource. guarantees or conditions. Existing granted lock Requested Lock IS S U IX SIX X Intent shared (IS) Yes Yes Yes Yes Yes No Shared (S) Yes Yes Yes No No No Update (U) Yes Yes No No No No Intent exclusive (IX) Yes No No Yes No No Shared with intent exclusive (SIX) Yes No No No No No Exclusive (X) No No No No No No In addition. The locks in the following table are listed in order from the least restrictive (shared) to the most restrictive (exclusive). The locks shown in the slide are the most common forms. redistribute.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. and some locks are not. or resell this content. The Licensed Content is licensed "as-is. but only one update lock can be issued on a piece of data at any one time. two users can both hold shared locks on the same data at the same time.

• The schema stability lock (Sch-S) is compatible with all locks except the schema modification lock (Sch-M).QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications • The schema modification lock (Sch-M) is incompatible with all locks. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. guarantees or conditions. . It is illegal to reprint.com or by calling +1 800-785-3448. 11-27 Question: Can you think of situations where lock compatibility is important? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.

com or by calling +1 800-785-3448. . The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. redistribute. and provided to you by QuickStart Intelligence. or resell this content. Objectives After completing this lesson. it may be desirable in some situations to exert control over locking behavior. However.QuickStart Intelligence 11-28 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 3 Management of Locking Locking behavior in SQL Server mostly operates without any need for management or application intervention. It is illegal to reprint. guarantees or conditions. you will be able to: • • • • • Explain locking timeout Describe lock escalation Explain what deadlocks are Describe locking-related table hints Describe methods to view locking information This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

LOCK_TIMEOUT is a session-level setting that determines (in milliseconds) the number of seconds to wait for any lock to be released before rolling back the statement (note not necessarily the transaction) and returning an error. It is illegal to reprint. Locking Timeout The length of time that it is reasonable to wait for a lock to be released is totally dependent upon the design requirements of the application. By default. A key decision is how long an application should wait for a lock to be released. or resell this content. redistribute. READPAST tells SQL Server to ignore any rows that it can't read as they are locked. Question: Can you think of any situations where READPAST might be useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. Setting a lock timeout at the session level is not common as most applications implement query timeouts. It is rarely used. guarantees or conditions. . and provided to you by QuickStart Intelligence. SQL Server will wait forever for a lock.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-29 Locking Timeout Key Points Applications might need to wait some time for locks held by other applications to be released. The default value of -1 indicates that SQL Server should wait forever.

reducing system overhead while increasing the probability of concurrency contention. SQL Server Lock Escalation As the SQL Server Database Engine acquires low-level locks. for example. In addition to intent lock on the object. the database engine attempts to change the intent lock on the table to the corresponding full lock. or resell this content. then all heap or B-tree. When locking rows or index key ranges. redistribute. intent page locks are requested on the following objects: • Leaf-level pages of nonclustered indexes • Data pages of clustered indexes • Heap data pages The database engine might do both row and page locking for the same statement to minimize the number of locks and reduce the likelihood that lock escalation will be necessary. To escalate locks. If the lock escalation attempt succeeds and the full table lock is acquired. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. . changing an intent exclusive (IX) lock to an exclusive (X) lock. guarantees or conditions. When locking pages. For example. the database engine places an intent lock on the higher level objects that contain the pages. it also places intent locks on the objects that contain the lower-level objects. the database engine could place page locks on a nonclustered index (if enough contiguous keys in the index node are selected to satisfy the query) and row locks on the data. Please report any unauthorized use of this content to piracy@microsoft. page (PAGE). The Licensed Content is licensed "as-is. or row-level (RID) locks held by the transaction on the This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint.QuickStart Intelligence 11-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Lock Escalation Key Points Lock escalation is the process of converting many fine-grain locks into fewer coarse-grain locks. the database engine places an intent lock on the pages that contain the rows or keys. or an intent shared (IS) lock to a shared (S) lock)." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

no lock escalation happens at that time and the database engine will continue to acquire row. It is illegal to reprint. key. and provided to you by QuickStart Intelligence. Question: Why do you imagine that SQL Server might find escalating locks worthwhile? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or page locks. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Partition-level lock escalation can be set on a per-table basis. The Licensed Content is licensed "as-is. or resell this content.com or by calling +1 800-785-3448. This allows for data in other partitioned to be available.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-31 heap or index are released. If the full lock cannot be acquired. so that the entire table is not locked. redistribute. Please report any unauthorized use of this content to piracy@microsoft. . Partition-level escalation can be set on a per-table basis. Partitioned tables can have locks escalated to the partition level before escalating to the table level.

or resell this content. SQL Server gives priority to the transaction that has been processing the longest. Each transaction must wait for the other to release the lock. Transaction B holds a shared lock on row 2. in which you cannot necessarily control the order of processing. • Rolls back the transaction of the deadlock victim  In a deadlock. How SQL Server Ends a Deadlock SQL Server ends a deadlock by automatically terminating one of the transactions. but it cannot be granted until Transaction A releases the share lock. The process SQL Server uses is in the following list. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 11-32 Implementing a Microsoft® SQL Server® 2008 R2 Database What are Deadlocks? Key Points Deadlocks occur when demands for resources are not able to be resolved by waiting for locks to be released. such as a join. It is illegal to reprint. no matter how long the processes involved wait. and provided to you by QuickStart Intelligence. redistribute. guarantees or conditions. A deadlock also can occur as a result of the order in which the optimizer processes a complex query.com or by calling +1 800-785-3448. For example: • • • • Transaction A holds a shared lock on row 1. The Licensed Content is licensed "as-is. SQL Server rolls back the transaction with the least amount of time invested. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Transaction A requests an exclusive lock on row 2. Deadlocks The most simple example of a deadlock occurs when two transactions have locks on separate objects and each transaction requests a lock on the other transaction’s object." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. but it cannot be granted until Transaction B releases the share lock. that transaction prevails. A deadlock can also occur when several long-running transactions execute concurrently in the same database. Transaction B requests an exclusive lock on row 1.

The Licensed Content is licensed "as-is. the application should attempt the transaction again. The message returned for error 1205 is highly emotive sounding. how did you determine that deadlocks were a problem. . and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. People don't like to see they have been "chosen as a deadlock victim"." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Question: Have you experienced deadlocking problems in your current environment? If so. guarantees or conditions. If error 1205 is found. and how was it resolved? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. Emotive words can cause emotive reactions.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications • Notifies the deadlock victim’s application (with message number 1205) • Cancels the deadlock victim’s current request • Allows other transactions to continue 11-33 Error 1205 is one of the errors that should be specifically checked for by applications. It is illegal to reprint. Error 1205 is also a good example of why database engine errors should not be passed directly to end users. or resell this content. redistribute.

QuickStart Intelligence 11-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Locking-related Table Hints Key Points The available locking hints are listed here for completeness." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. redistribute. guarantees or conditions. . it is important to realize that they should rarely be used and only with extreme caution. or resell this content. Question: Why would you ever take an exclusive table-lock? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. While a wide range of locking hints are available. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. The Licensed Content is licensed "as-is.

It is illegal to reprint. . which provide a detailed profile of server events. or resell this content. Amongst the more useful are: Dynamic Management View sys. You can use this profile to This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Each row returned describes a currently granted lock or a requested lock.dm_tran_locks dynamic management view to retrieve information about the locks currently held by an instance of the Database Engine. You can use SQL Server Profiler to obtain information on a specific set of transactions.com or by calling +1 800-785-3448. You can also use Reliability and Performance Monitor to display SQL Server locking histories. Please report any unauthorized use of this content to piracy@microsoft.dm_tran_locks sys." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.dm_tran_session_transactions sys.dm_tran_current_transaction You can query the sys. and provided to you by QuickStart Intelligence. and the request group which describes the lock request. Dynamic Management Views Many DMVs are available for viewing locking information. The columns returned are divided into two main groups.dm_tran_active_transactions sys. the resource group which describes the resource on which the request is made. guarantees or conditions.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-35 Methods to View Locking Information Key Points Typically. redistribute. The Licensed Content is licensed "as-is. You can collect information about a variety of events by creating traces. SQL Server Profiler SQL Server Profiler is a tool that monitors server activities. you use SQL Server Management Studio to display a report of active locks.

Use the Locks Event Category to capture locking information in a trace. or resell this content. It is illegal to reprint. Reliability and Performance Monitor You can view SQL Server locking information by using Reliability and Performance Monitor in Windows. . and correct deadlock problems. Question: When would you want to choose one method of viewing locks over another? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. monitor login attempts and connections. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 11-36 Implementing a Microsoft® SQL Server® 2008 R2 Database analyze and resolve server resource issues. Use the SQLServer:Locks objects to retrieve this information. redistribute.

or resell this content.com or by calling +1 800-785-3448. From the File menu. click SQL Server Management Studio.sql script file from within Solution Explorer. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Open. redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.sql script file.sql script file. Follow the instructions contained within the comments of the script file. click Start. Open the 32 – Demonstration 3A 2nd Window.ssmssln and click Open. click Project/Solution. click All Programs. and provided to you by QuickStart Intelligence. It is illegal to reprint. Open the 33 – Demonstration 3A 3rd Window. 5. Open the 31 – Demonstration 3A. .QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-37 Demonstration 3A: Viewing Locking Information Key Points In this demonstration you will see how: • • View lock information using Activity Monitor Use dynamic management views to view lock info Demonstration Steps 1. navigate to D:\6232B_Labs\6232B_11_PRJ\6232B_11_PRJ. Please report any unauthorized use of this content to piracy@microsoft.sql script file. 2. type Proseware in the Server name text box and click Connect. • In the virtual machine. 3. In the Connect to Server window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. click Microsoft SQL Server 2008 R2. The Licensed Content is licensed "as-is. guarantees or conditions. • Open and execute the 00 – Setup. 4.

you will be able to: • • • Describe SQL Server transaction isolation levels Explain the role of the read committed snapshot database option Detail isolation-related table hints This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. This is not totally possible but appropriate use of transaction isolation levels can help in this regard. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. It was mentioned earlier that a role of any database engine is to give each user the best possible illusion that they are the only user on the system. Objectives After completing this lesson. guarantees or conditions.QuickStart Intelligence 11-38 Implementing a Microsoft® SQL Server® 2008 R2 Database Lesson 4 Transaction Isolation Levels The final important concept that needs to be understood when working with concurrency in SQL Server is transaction isolation levels. It is illegal to reprint. redistribute. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.

you are sacrificing consistency in favor of high concurrency. you specify the default locking behavior for all statements in your session. This is at the cost of locks being held for longer. SET TRANSACTION ISOLATION LEVEL {READ COMMITTED | READ UNCOMMITTED | REPEATABLE READ | SERIALIZABLE | SNAPSHOT} READ UNCOMMITTED is the lowest isolation level. the lower the risk of data integrity problems. It is not safe to use NOLOCK on queries that are accessing data currently being changed.com or by calling +1 800-785-3448. . Use the transaction isolation level to set the isolation level for all transactions during a session. With READ UNCOMMITTED. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. These locks ensure that the rows touched by the query This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. READ COMMITTED acquires short lived share locks before reading data and released after the processing is complete. redistribute. The ability to read uncommitted data can lead to many inconsistencies. Transaction Isolation Levels Setting transaction isolation levels allows programmers to accept increased risk of integrity problems in exchange for greater concurrent access to data. It is illegal to reprint. The Licensed Content is licensed "as-is. and only ensures that corrupt data is not read. Even rows that do not qualify for the query result remain locked. and provided to you by QuickStart Intelligence. guarantees or conditions.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-39 SQL Server Transaction Isolation Levels Key Points An isolation level protects a transaction from the effects of other concurrent transactions. or resell this content. REPEATABLE READ retains locks on every row it touches until the end of the transaction. NOLOCK was commonly used in reporting applications before SNAPSHOT isolation level became available. You can set the transaction isolation level for a session by using the SET statement. You can override a session-level isolation level in individual statements by using lock specification. and the locks themselves being more restrictive with respect to concurrent transactions. You also can use locking hints to specify transaction isolation for a statement. The higher the isolation level. This is equivalent to a NOLOCK table hint. Dirty reads cannot occur but non-repeatable reads can occur. This is the SQL Server default. When you set the isolation level.

com or by calling +1 800-785-3448. The situation where this can lead to a problem is where the application then attempts to update the version of the row in the row version table. The Licensed Content is licensed "as-is. If the modification to the original table row is committed. . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint.QuickStart Intelligence 11-40 Implementing a Microsoft® SQL Server® 2008 R2 Database cannot be updated or deleted by a concurrent session until the current transaction completes (whether it is committed or rolled back). Please report any unauthorized use of this content to piracy@microsoft. SNAPSHOT tries to avoid one process blocking another when only one is performing updates.one transaction must wait for the other to complete and two transactions can deadlock. SQL Server creates a copy of the row in a row version table (actually held in tempdb) and allows the update to proceed. redistribute. and provided to you by QuickStart Intelligence. or resell this content. As an example. Note that before SNAPSHOT isolation level can be used. SERIALIZABLE ensures consistency by assuming that two transactions might try to update the same data and uses locks to ensure that they do not but at a cost of reduced concurrency . it needs to be enabled via a database option. if a transaction attempts to modify a row that another transaction is holding a shared lock on. The transaction with the shared lock will read from the row in the row version table instead of the table row. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Transactions are completely isolated from one another. this second modification will then fail with a concurrency violation.

you cannot experience dirty reads. With the read committed This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. causes DML statements to start generating row versions. The Licensed Content is licensed "as-is. The data is not protected from updates made by other transactions but the transaction will not be blocked while reading the data. It is illegal to reprint. The behavior of the READ COMMITTED option depends on the setting of the READ_COMMITTED_SNAPSHOT database option. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. or resell this content. Option Description READ COMMITTED with READ_COMMITTED_SNAPSHOT OFF Directs SQL Server to use shared locks while reading. even when no transaction is using snapshot isolation. which can be ON or OFF. READ COMMITTED with READ_COMMITTED_SNAPSHOT ON Directs SQL Server to use row versioning instead of locking.com or by calling +1 800-785-3448. when enabled. this was commonly dealt with via NOLOCK hints. Transactions that specify read committed are automatically altered to use row versioning rather than locking.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-41 Read Committed Snapshot Key Points Not every application can use snapshot isolation level as it needs to be specified when beginning a transaction. All statements see a snapshot of data as it existed at the start of the statement. redistribute. It is important to note though that the read committed snapshot database option does not achieve exactly the same outcome as the snapshot isolation level set at the session level." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The following table describes the locking isolation level options. Read Committed Snapshot Read Committed Snapshot is a database option that. . Many existing reporting applications cause excessive blocking. At this level. Often this requires a change to the application code. Prior to SQL Server 2005. guarantees or conditions.

not for the duration of the transaction. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. or resell this content.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. snapshots are only present for the duration of each statement. Database Configuration Before either snapshot isolation level or the read committed snapshot database option can be used. .QuickStart Intelligence 11-42 Implementing a Microsoft® SQL Server® 2008 R2 Database snapshot database option. the database needs to be configured to allow snapshot isolation.

They are listed here for completeness. Isolation-related Table Hints Similar to the locking hints. It is illegal to reprint. these should in general be avoided. The Licensed Content is licensed "as-is. This could be useful in specialized situations. guarantees or conditions.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute. . However. and provided to you by QuickStart Intelligence. they do provide a way to override the default behavior on an individual table basis within a statement." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the isolation-level table hints can be applied to override the default transaction isolation level. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-43 Isolation-related Table Hints Key Points Similar to the way table hints can be applied to control locking. or resell this content.

or resell this content. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click the Ctrl-Alt-Delete menu item. you will use the available virtual machine environment. In the Virtual Machines list. if the user is not already logged on: • On the Action menu. click Revert." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and then click Other User. • In the Virtual Machine Connection window. • Right-click 623XB-MIA-DC and click Connect. click Start. if the virtual machine 623XB-MIA-SQL is not started: • Right-click 623XB-MIA-SQL and click Start. In the Virtual Machines list. If you are prompted to confirm that you want to revert. wait until the Press CTRL+ALT+DELETE to log on message appears. Wait for the revert action to complete. 2. • In the Virtual Machine Connection window. and then click Hyper-V Manager. guarantees or conditions.QuickStart Intelligence 11-44 Implementing a Microsoft® SQL Server® 2008 R2 Database Lab 11: Creating Highly Concurrent SQL Server Applications Lab Setup For this lab. • Click Switch User. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. The Licensed Content is licensed "as-is. 5. • Right-click 623XB-MIA-SQL and click Connect. and provided to you by QuickStart Intelligence. On the host computer. In Virtual Machine Connection window. redistribute. you must complete the following steps: 1. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. 6. 3. 4. . click on the Revert toolbar icon. and then close the Virtual Machine Connection window.com or by calling +1 800-785-3448. Before you begin the lab. In the Virtual Machine Connection window. Maximize the Hyper-V Manager window. wait until the Press CTRL+ALT+DELETE to log on message appears. 7. point to Administrative Tools.

com or by calling +1 800-785-3448.sql. or resell this content. . In the File menu.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications • 11-45 Log on using the following credentials: i. In the Open Project window. In Connect to Server window. and click Project/Solution. Please report any unauthorized use of this content to piracy@microsoft. In the virtual machine. 9. and provided to you by QuickStart Intelligence. click Full Screen Mode. Lab Scenario In this lab. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. User name: AdventureWorks\Administrator ii. You are trying to determine an appropriate transaction isolation level for a new application. Password: Pa$$w0rd 8. select Windows Authentication and click Connect. The Licensed Content is licensed "as-is. click Execute on the toolbar. 11. click Open. When the query window opens." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. you will perform basic investigation of a deadlock situation. In the Authentication drop-down list box.ssmssln. check the Do not show me this console at logon check box and close the Server Manager window. click Microsoft SQL Server 2008 R2. double-click the query 00-Setup. and click SQL Server Management Studio. If you have time. redistribute. in the Virtual Machine Connection window. From the View menu. type Proseware in the Server name text box. If the Server Manager window appears. click Start. 15. In Solution Explorer. 12. 13. click All Programs. 14. guarantees or conditions. 10. open the project D:\6232B_Labs\6232B_11_PRJ\6232B_11_PRJ. you will investigate the trade-off between concurrency and consistency.

guarantees or conditions. or resell this content. The main tasks for this exercise are as follows: 1. Start and configure SQL Server Profiler. Stop the trace and review the deadlock graph. you will explore typical causes of deadlocks and learn to view them in SQL Server Profiler traces.sql.sql script • Review the script • Execute 51 – Lab Exercise 1.sql script • Review the script • Open the 52 – Lab Exercise 1 2nd Window. You will observe how this can be traced in SQL Server Profiler This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Load and execute the test scripts. 3.QuickStart Intelligence 11-46 Implementing a Microsoft® SQL Server® 2008 R2 Database Exercise 1: Detecting Deadlocks Scenario In this exercise. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. It is illegal to reprint. 2.  Task 1: Start and configure SQL Server Profiler • Start SQL Server Profiler and create a new trace called Deadlock Detection • Add Deadlock Graph to the events • Remove all other events • Start the trace in Profiler  Task 2: Load and execute the test scripts • Open the 51 – Lab Exercise 1. redistribute.sql and then immediately execute 52 – Lab Exercise 1 2nd Window. you have executed queries that create a deadlock situation. . The Licensed Content is licensed "as-is. Wait for both to complete  Task 3: Stop the trace and review the deadlock graph • Stop the trace • Review the deadlock graph Results: After this exercise.

The main tasks for this exercise are as follows: 1. redistribute. or resell this content. you will have seen how transaction isolation levels work." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Load the scripts Execute the code  Task 1: Load the scripts • Open the 62 – Lab Exercise 2 2nd Window. .sql script  Task 2: Execute the code • Execute the code step by step. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. by following the step by step instructions Results: After this exercise.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 2.sql script • Open the 61 – Lab Exercise 2. The Licensed Content is licensed "as-is. you will execute a supplied set of T-SQL scripts that demonstrate how different transaction isolation levels work. guarantees or conditions. It is illegal to reprint. making sure to highlight and execute just the required code blocks in each script window.QuickStart Intelligence Creating Highly Concurrent SQL Server 2008 R2 Applications 11-47 Challenge Exercise 2: Investigating Transaction Isolation Levels (Only if time permits) Scenario In this exercise.

Common examples are Component Services and BizTalk adapters. The Licensed Content is licensed "as-is. Many Microsoft-supplied components default to Serializable transactional isolation level but do not need to be run at that level. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. make sure that all the queries that are involved are executing quickly. blocking issues disappear. 2. Before spending too much time investigating blocking issues. Often when query performance issues are resolved. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. Why is snapshot isolation level helpful? What is the difference between a shared lock and an exclusive lock? Why would you use read committed snapshot rather than snapshot isolation level? Best Practices 1. This usually involves making sure that appropriate indexes are in place. It is illegal to reprint. redistribute. 3. 2. 3. guarantees or conditions.com or by calling +1 800-785-3448. Always use the lowest transaction isolation level possible to avoid blocking and to avoid the chance of deadlocks.QuickStart Intelligence 11-48 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Review and Takeaways Review Questions 1. .

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.QuickStart Intelligence Handling Errors in T-SQL Code 12-1 Module 12 Handling Errors in T-SQL Code Contents: Lesson 1: Understanding T-SQL Error Handling 12-3 Lesson 2: Implementing T-SQL Error Handling 12-13 Lesson 3: Implementing Structured Exception Handling 12-23 Lab 12: Handling Errors in T-SQL Code 12-31 This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. .com or by calling +1 800-785-3448. redistribute. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. It is illegal to reprint. The Licensed Content is licensed "as-is.

. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. A large number of myths surround how error handling in T-SQL works. Please report any unauthorized use of this content to piracy@microsoft. appropriate handling of errors is critically important. In this module. and provided to you by QuickStart Intelligence. you will explore T-SQL error handling. look at how it has traditionally been implemented and how structured exception handling can be used. Objectives After completing this lesson. redistribute. guarantees or conditions.QuickStart Intelligence 12-2 Implementing a Microsoft® SQL Server® 2008 R2 Database Module Overview When creating applications for SQL Server using the T-SQL language.com or by calling +1 800-785-3448. It is illegal to reprint. you will be able to: • • • Design T-SQL error handling Implement T-SQL error handling Implement structured exception handling This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

or resell this content. it is important to gain an understanding of the nature of errors. of where they can occur when T-SQL is being executed. and provided to you by QuickStart Intelligence.QuickStart Intelligence Handling Errors in T-SQL Code 12-3 Lesson 1 Understanding T-SQL Error Handling Before delving into the coding that deals with error handling in T-SQL. Objectives After completing this lesson. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is. you will be able to: • • • • Explain where T-SQL errors occur Describe types of errors Explain what values are returned by an error Describe different levels of error severities This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. the data that is returned by errors and the severities that errors can exhibit. redistribute.

no error would be returned.com or by calling +1 800-785-3448. SQL Server would first look for an table named "Custommer" in the default schema of the user executing the code. the objects referenced by name in the T-SQL statements are resolved to underlying object IDs." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. At this phase errors occur if the statements do not conform to the rules of the language. . the syntax of a statement is checked. To avoid ambiguity at this point. Object Resolution In the second phase of execution. or resell this content. During the syntax checking phase. During the syntax checking phase that the objects referred to may not actually exist yet still no errors would be returned. Single part names are resolved to specific objects at this point. Errors can occur at each phase. redistribute. If no such table exists. If no such table existed in the dbo schema. Some errors could potentially be handled by the database engine. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. multi-part names should be used for objects except in rare circumstances. The rules of the T-SQL language have been followed. Errors occur at this phase if the objects do not exist. and provided to you by QuickStart Intelligence. SQL Server would then look for the table "dbo. Syntax Check In the first phase of execution. imagine the execution of a statement where the word "Customer" was misspelled: SELECT * FROM Custommer. an error would then be returned. For example. In the example above.QuickStart Intelligence 12-4 Implementing a Microsoft® SQL Server® 2008 R2 Database Where T-SQL Errors Occur Key Points T-SQL statements go through multiple phases during their execution.Custommer" ie: it would next look in the dbo schema. There is nothing incorrect about this from a syntax point of view. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Other errors will need to be passed back to the calling application. guarantees or conditions. The Licensed Content is licensed "as-is.

Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. For example." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Some errors can be handled in the database engine but other errors will need to be handled by client applications.com or by calling +1 800-785-3448. You could also have more basic errors occurring at this point such as an attempt to divide by a zero value. redistribute. the statement is executed. Client applications always need to be written with error handling in mind.QuickStart Intelligence Handling Errors in T-SQL Code 12-5 Statement Execution In the third phase of execution. At this phase. Question: Can you suggest a reason why you might want to catch errors in a client application rather than allowing the errors to be seen by the end users? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. the user may not have permission to SELECT from the table specified or an INSERT statement might fail because a constraint was going to be violated. guarantees or conditions. The Licensed Content is licensed "as-is. runtime errors can occur. It is illegal to reprint. or resell this content.

Note that the syntax of the entire batch of statements being executed is checked before the execution of any statement within the batch is attempted. and provided to you by QuickStart Intelligence. It is illegal to reprint. redistribute. Line 1 Incorrect syntax near the keyword 'FROM'.com or by calling +1 800-785-3448. you saw an example of an object resolution error. consider the following statement: SELECT TOP(10) FROM Production. State 1. such as in the following statement: SELECT * FROM SomeNonexistentTable. The Licensed Content is licensed "as-is. Object Resolution Errors In the last topic. For example. Syntax errors are batch terminating errors. no attempt at object name resolution will be made. .QuickStart Intelligence 12-6 Implementing a Microsoft® SQL Server® 2008 R2 Database Types of Errors Key Points A number of different categories of error can occur. Level 15. These errors occur when the object name specified cannot be resolved to an object ID.Product. or resell this content. Mostly they differ by the scope of the termination that occurs when the error is not handled. Syntax Errors Syntax errors occur when the rules of the language are not followed. If you try to execute the statement." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note that if a syntax error occurs. The same issue would occur if the schema for the object was not specified and the object did not exist in the user's default schema or in the dbo schema. you receive the following message: Msg 156. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.

The conflict occurred in database "AdventureWorks2008R2".BillOfMaterials". and provided to you by QuickStart Intelligence.QuickStart Intelligence Handling Errors in T-SQL Code 12-7 Statement Terminating Errors With a statement terminating error. table "Production." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. State 0. It is illegal to reprint.Product WHERE ProductID = 1. column 'ComponentID'. The Licensed Content is licensed "as-is. Fortunately such errors are rare! This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The most serious errors would terminate SQL Server itself. the following is returned: Msg 547. Line 3 The DELETE statement conflicted with the REFERENCE constraint "FK_BillOfMaterials_Product_ComponentID". execution resumes at the next statement following the statement that was in error. the scope (eg: the current stored procedure) or the session to be terminated. Consider the following batch executed against the AdventureWorks2008R2 database: DELETE FROM Production. Hello Note that the PRINT statement was still executed even though the DELETE statement failed because of a constraint violation. The statement has been terminated. guarantees or conditions. Scope. . or resell this content. Session and Server Terminating Errors More serious errors can cause the batch. When this batch is executed. Errors of this nature usually indicate particularly serious hardware errors.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. PRINT 'Hello'. redistribute. Level 16. Batch.

What's in an Error It might not be immediately obvious that a SQL Server error (or sometimes called an exception) is itself an object. Please report any unauthorized use of this content to piracy@microsoft. particularly when searching online for information about the error. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence.QuickStart Intelligence 12-8 Implementing a Microsoft® SQL Server® 2008 R2 Database What's in an Error? Key Points An error is itself an object and has properties as shown in the table. this command returns the following: Note that there are multiple messages with the same message_id.com or by calling +1 800-785-3448. . When executed. It is illegal to reprint.messages ORDER BY message_id. Error messages are localizable and can be returned in a number of languages. Errors return a number of useful properties. The Licensed Content is licensed "as-is. or resell this content. It is described further in the next topic. Severity indicates how serious the error is. Error numbers are helpful when trying to locate information about the specific error. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. A language_id of 1033 is the English version of the message.messages catalog view: SELECT * FROM sys. You can view the list of system-supplied error messages by querying the sys. You can see an English message in the third line of the output above. language_id. redistribute.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In practice. For example. if you were writing a stored procedure that could raise an error for a missing customer and there were five places in the code that this message could occur. line numbers are not very helpful and not always applicable. redistribute. Question: Why is it useful to be able to localize error messages? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. or resell this content. and provided to you by QuickStart Intelligence. This would help later to troubleshoot the error. The Licensed Content is licensed "as-is. . Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.QuickStart Intelligence Handling Errors in T-SQL Code 12-9 State is defined by the author of the code that raised the error. you could assign a different state to each of the places where the message was raised. Procedure name is the name of the stored procedure that that error occurred in and Line Number is the location within that procedure. It is illegal to reprint.

The Licensed Content is licensed "as-is. However." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 12-10 Implementing a Microsoft® SQL Server® 2008 R2 Database Error Severity Key Points The severity of an error indicates the type of problem encountered by SQL Server. Severity 10 is the top of the informational messages. guarantees or conditions. and provided to you by QuickStart Intelligence. consider the following code executed against the AdventureWorks2008R2 database: SELECT COUNT(Color) FROM Production. . Values from 11 to 16 Values from 11 to 16 are considered errors that the user can correct. if you look on the Messages tab in SQL Server Management Studio. the information is returned but no error status information is provided. Error severities occur in ranges: Values from 0 to 10 Values from 0 to 9 are purely informational messages. (1 row(s) affected) Note that no error really occurred but SQL Server is warning you that it ignored NULL values when counting the rows. it returns a count as expected. Low severity values are informational messages and do not indicate true errors. redistribute.Product. When queries that raise these are executed in SQL Server Management Studio. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. When executed. Note that no status information is returned.com or by calling +1 800-785-3448. Here are a few examples of these errors: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Typically they are used for errors where SQL Server assumes that the statement being executed was in error. you will see the following: Warning: Null value is eliminated by an aggregate or other SET operation. For example. It is illegal to reprint.

com or by calling +1 800-785-3448.) Values from 17 to 19 Values from 17 to 19 are considered serious software errors that the user cannot correct. etc. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. disk space. redistribute. and provided to you by QuickStart Intelligence.QuickStart Intelligence Handling Errors in T-SQL Code 12-11 Error Severity Example 11 indicates that an object does not exist 13 indicates a transaction deadlock 14 indicates errors such as permission denied 15 indicates syntax errors 17 indicates that SQL Server has run out of resources (memory. locks. Values above 19 Values above 19 tend to be very serious errors that normally involve errors with either the hardware or SQL Server itself. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. or resell this content. It is common to ensure that all errors above 19 are logged and alerts generated on them. guarantees or conditions. .

2. In the Connect to Server window. Please report any unauthorized use of this content to piracy@microsoft. click SQL Server Management Studio.sql script file. redistribute. navigate to D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ. 4. type Proseware in the Server name text box and click Connect. click Open. In the virtual machine. click All Programs. click Start.QuickStart Intelligence 12-12 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 1A: Error Types and Severity Key Points In this demonstration you will see how to: • • • See how different types of errors are returned from T-SQL statements See the types of messages that are related to severe errors Query the sys. The Licensed Content is licensed "as-is. Open and execute the 00 – Setup. It is illegal to reprint. guarantees or conditions. and provided to you by QuickStart Intelligence. From the File menu. Open the 11 – Demonstration 1A.messages view and note which errors are logged automatically Demonstration Setup 1. . Question: What do you imagine the "is_event_logged" column relates to? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. 5.sql script file from within Solution Explorer. click Microsoft SQL Server 2008 R2. Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. click Project/Solution.com or by calling +1 800-785-3448. Follow the instructions contained within the comments of the script file.ssmssln and click Open. 3." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the next lesson. including how you can raise errors intentionally and how you can set up alerts to fire when errors occur. you will see how to implement a more advanced form of error handling known as structured exception handling. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. it is time to consider how they can be handled or reported in T-SQL. . or resell this content. you will be able to: • • • • • • Raise errors Use the @@ERROR system variable Explain the role of errors and transactions Explain transaction nesting errors Raise custom errors Create alerts that fire when errors occur This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The T-SQL language offers a variety of error handling capabilities. It is illegal to reprint. This lesson covers basic T-SQL error handling.com or by calling +1 800-785-3448. It is important to understand these and how they relate to transactions. redistribute. Objectives After completing this lesson. guarantees or conditions.QuickStart Intelligence Handling Errors in T-SQL Code 12-13 Lesson 2 Implementing T-SQL Error Handling Now that you understand the nature of errors.

guarantees or conditions. the errors raised always have error number 50000. The Licensed Content is licensed "as-is. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. RAISERROR allows applications to raise an error that could then be caught by the calling process. RAISERROR is used to: • • • Help troubleshoot T-SQL code Check the values of data Return messages that contain variable text Note that using a PRINT statement is similar to raising an error of severity 10. as shown in the sample on the slide. and provided to you by QuickStart Intelligence. RAISERROR The ability to raise errors in T-SQL makes error handling in the application easier as it is sent like any other system error. . redistribute. When errors with message strings are raised using this syntax.com or by calling +1 800-785-3448. Substitution Placeholders and Message Number Note that in the message shown in the example on the slide. that %d is a placeholder for a number and %s is a placeholder for a string.QuickStart Intelligence 12-14 Implementing a Microsoft® SQL Server® 2008 R2 Database Raising Errors Key Points Both PRINT and RAISERROR can be used to return information or warning messages to applications. Question: Why might you want to intentionally raise an error in your code? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. Note also that a message number was not mentioned.

. or resell this content. GO You might expect that when it is executed. Note that structured exception handling was introduced in SQL Server 2005 and provides a strong alternative to using @@ERROR." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Handling Errors in T-SQL Code 12-15 Using @@Error Key Points Most traditional error handling code in SQL Server applications has been created using @@ERROR. it returns: Msg 50000.com or by calling +1 800-785-3448. Line 1 Message Error=0 Note that the error was raised but that the message printed was "Error=0". However. A large amount of existing SQL Server error handling code is based on @@ERROR so it is important to understand how to work with it. Please report any unauthorized use of this content to piracy@microsoft. This is because the IF statement that follows the RAISERROR statement was executed successfully and caused the @@ERROR value to be reset. One significant challenge with @@ERROR is that the value it holds is quickly reset as each additional statement is executed. You can see in the first line of the output that the error was actually 50000 as expected with a message passed to RAISERROR. and provided to you by QuickStart Intelligence. Level 16. 16. consider the following code: RAISERROR(N'Message'. redistribute. IF @@ERROR <> 0 PRINT 'Error=' + CAST(@@ERROR AS VARCHAR(8)). It will be discussed in the next lesson. The Licensed Content is licensed "as-is. 1). For example. it would return the error number in a printed string. when the code is executed. @@ERROR @@ERROR is a system variable that holds the error number of the last error that has occurred. State 1. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. It is illegal to reprint.

when working with @@ERROR. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. guarantees or conditions. it returns the following output: Msg 50000. Centralizing Error Handling One other significant issue with using @@ERROR for error handling is that it is difficult to centralize error handling within your T-SQL code. 16. The Licensed Content is licensed "as-is. . Error handling tends to end up scattered throughout the code. Level 16. SET @ErrorValue = @@ERROR. Please report any unauthorized use of this content to piracy@microsoft. RAISERROR(N'Message'. it is important to capture the error number into a variable as soon as it is raised and to then continue processing with the variable. When this code is executed. State 1. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. IF @ErrorValue <> 0 PRINT 'Error=' + CAST(@ErrorValue AS VARCHAR(8)).QuickStart Intelligence 12-16 Implementing a Microsoft® SQL Server® 2008 R2 Database Capturing @@ERROR into a Variable For this reason. Line 2 Message Error=50000 Note that the error number is correctly reported now. 1).com or by calling +1 800-785-3448. or resell this content. It would be possible to somewhat centralized error handling using @@ERROR by using labels and GOTO statements but this would be frowned upon by most developers today as a poor coding practice. Look at the following code that demonstrates this: DECLARE @ErrorValue int. and provided to you by QuickStart Intelligence.

PRINT 'Hello again'. The Licensed Content is licensed "as-is. PRINT 'Hello'. The conflict occurred in database "AdventureWorks2008R2".BillOfMaterials".com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note that this happens even when working within a transaction. State 0.Product WHERE ProductID = 1. Statement Terminating Errors vs Batch/Scope Terminating Errors Most common errors that occur when processing T-SQL are statement terminating errors not batch or scope terminating errors. consider the following code: BEGIN TRAN. guarantees or conditions. The SET XACT_ABORT statement can be used to control this behavior. This means that the statement in error is rolled back and execution then continues with the next statement following the statement in error. DELETE Production. Please report any unauthorized use of this content to piracy@microsoft. Note that when it is executed. For example. and provided to you by QuickStart Intelligence. or resell this content. Hello Hello again This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. The statement has been terminated. . the following output is generated: Msg 547. redistribute. Line 3 The DELETE statement conflicted with the REFERENCE constraint "FK_BillOfMaterials_Product_ComponentID". column 'ComponentID'.QuickStart Intelligence Handling Errors in T-SQL Code 12-17 Errors and Transactions Key Points Many new developers are surprised to find out that a statement that fails even when enclosed in a transaction does not automatically rolled the transaction back. It is illegal to reprint. Level 16. table "Production. COMMIT. only the statement itself.

guarantees or conditions. column 'ComponentID'. Note that when the DELETE statement failed. Level 16.Product WHERE ProductID = 1. PRINT 'Hello again'. The Licensed Content is licensed "as-is. including the transaction that had begun. DELETE Production.com or by calling +1 800-785-3448. it returns: Msg 547." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. table "Production. Please report any unauthorized use of this content to piracy@microsoft. The transaction would have been rolled back. Line 5 The DELETE statement conflicted with the REFERENCE constraint "FK_BillOfMaterials_Product_ComponentID". and provided to you by QuickStart Intelligence. It is illegal to reprint. SET XACT_ABORT ON The SET XACT_ABORT ON statement is used to tell SQL Server that statement terminating errors should become batch terminating errors.QuickStart Intelligence 12-18 Implementing a Microsoft® SQL Server® 2008 R2 Database Note that both PRINT statements still execute even though the DELETE statement failed. the entire batch was terminated. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content.BillOfMaterials". Now consider the same code with SET XACT_ABORT ON present: SET XACT_ABORT ON. State 0. COMMIT. . When executed. BEGIN TRAN. PRINT 'Hello'. The conflict occurred in database "AdventureWorks2008R2". redistribute.

Transaction Nesting Errors SQL Server does not support nested transactions.QuickStart Intelligence Handling Errors in T-SQL Code 12-19 Transaction Nesting Errors Key Points Any ROLLBACK causes all levels of transactions to be rolled back.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. Code that is written to log that a user attempted an action is rolled back as well when the action is rolled back. Please report any unauthorized use of this content to piracy@microsoft. not just the current nesting level. and provided to you by QuickStart Intelligence. If the transaction nesting level differs. . redistribute. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. No matter how deeply you nest transactions. SQL Server does not support autonomous transactions. This is commonly seen when users are attempting to nest transaction rollback. a ROLLBACK rolls back all levels of transaction. error 286 is raised. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Nesting Levels You can determine the current transaction nesting level by querying the @@TRANCOUNT system variable. Typically this limitation arises when trying to construct auditing or logging code. The syntax of the language might appear to support them but they do not operate in a nested fashion. Another rule to be aware of is that SQL Server requires that the transaction nesting level of a stored procedure is the same on entry to the stored procedure and on exit from it. or resell this content. Autonomous transactions are nested transactions that are in a different transaction scope. guarantees or conditions.

Note that raising system errors is not supported. When set to TRUE. The error numbers supplied must be 50000 or above and the user adding them must be a member of the sysadmin or serveradmin fixed server roles. redistribute.QuickStart Intelligence 12-20 Implementing a Microsoft® SQL Server® 2008 R2 Database Raising Custom Errors Key Points Rather than raising system errors. . Any message written to the Windows Application log is also written to the SQL Server error log. based on a language_id value. SQL Server allows users to define custom error messages that have meaning to their applications.messages System View The messages that are added are visible within the sys. The Licensed Content is licensed "as-is. or resell this content. Be judicious with the use of the @with_log option as network and system administrators tend to dislike applications that are "chatty" in the system logs. Raising Custom Errors As well as being able to define custom error messages. members of the sysadmin server role can also use an additional parameter @with_log. Question: What do the DB_ID and DB_NAME functions return? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.messages system view along with the systemsupplied error messages. the error will also be recorded in the Windows Application log.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. Messages can be replaced without the need to delete them first by using the @replace = 'replace' option. sys. guarantees or conditions. It is illegal to reprint. (Note: English messages are language_id 1033). The messages are customizable and different messages can be added for the same error number for multiple languages. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This can even apply to user-defined error messages. redistribute. This means that alerts only work on errors that are logged. Raising Alerts Alerts can be created for specific error messages. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. . Question: Can you suggest an example of an error that would require immediate attention from an administrator? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint. The alerting service works by registering itself as a callback service with the event logging service. There are two ways to make messages be alert-raising. You can use the WITH LOG option when raising the error or the message can be altered to make it logged by executing sp_altermessage. Please report any unauthorized use of this content to piracy@microsoft. Modifying system errors via sp_altermessage is only possible from SQL Server 2005 SP3 or SQL Server 2008 SP1 onwards. For example.QuickStart Intelligence Handling Errors in T-SQL Code 12-21 Creating Alerts When Errors Occur Key Points For certain categories of errors. administrators might wish to be notified as soon as these errors occur.com or by calling +1 800-785-3448. guarantees or conditions. you may wish to raise an alert whenever a customer is deleted. or resell this content. More commonly. alerting is used to bring high-severity errors (such as severity 19 or above) to the attention of administrators.

In the Connect to Server window. type Proseware in the Server name text box and click Connect. click Start. click Project/Solution. From the File menu." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. navigate to D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ. The Licensed Content is licensed "as-is. click SQL Server Management Studio. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.sql script file. 2. . guarantees or conditions. Open the 21 – Demonstration 2A. and provided to you by QuickStart Intelligence.sql script file. • In the virtual machine. Open the 22 – Demonstration 2A 2nd Window. or resell this content. 3. Question: Why is the ability to substitute values in error messages useful? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. click Open.ssmssln and click Open. • Open and execute the 00 – Setup.com or by calling +1 800-785-3448. Follow the instructions contained within the comments of the script file. 4.sql script file from within Solution Explorer. click All Programs.QuickStart Intelligence 12-22 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 2A: T-SQL Error Handling Key Points In this demonstration you will see: • • • • • • • How to raise errors How severity affects errors How to add a custom error message How to raise a custom error message That custom error messages are instance-wide How to use @@ERROR That system error messages cannot be raised Demonstration Steps 1. redistribute. It is illegal to reprint. click Microsoft SQL Server 2008 R2.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Objectives After completing this lesson. The Licensed Content is licensed "as-is. You will see how to use it and evaluate its benefits and limitations. Please report any unauthorized use of this content to piracy@microsoft. redistribute. . Structured exception handling was introduced in SQL Server 2005. you will be able to: • • • • • Explain TRY CATCH block programming Describe the role of error handling functions Describe catchable vs non-catchable errors Explain how TRY CATCH relates to transactions Explain how errors in managed code are surfaced This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. and provided to you by QuickStart Intelligence. guarantees or conditions.QuickStart Intelligence Handling Errors in T-SQL Code 12-23 Lesson 3 Implementing Structured Exception Handling Now that you have an understanding of the nature of errors and of basic error handling in T-SQL. it is time to look at a more advanced form of error handling. It is illegal to reprint.

QuickStart Intelligence 12-24 Implementing a Microsoft® SQL Server® 2008 R2 Database TRY CATCH Block Programming Key Points Structured exception handling has been part of high level languages for some time. Please report any unauthorized use of this content to piracy@microsoft. TRY Block and CATCH Block When using structured exception handling. Note that while BEGIN CATCH and END TRY are separate statements. Current Limitations High level languages often offer a try/catch/finally construct. There is currently no mechanism for rethrowing errors and only errors above 50000 can be thrown manually.com or by calling +1 800-785-3448. It allows you to prevent code from being littered with error handling code and to centralize that error handling code. and provided to you by QuickStart Intelligence. TRY CATCH Block Programming Structured exception handling is more powerful than error handling based on the @@ERROR system variable. The CATCH block is a series of T-SQL statements enclosed by BEGIN CATCH and END CATCH statements. Centralization of error handling code also allows you to focus more on the purpose of the code rather than on the error handling in the code. redistribute. the BEGIN CATCH statement must immediately follow the END TRY statement. SQL Server 2005 introduced structured exception handling to the T-SQL language. or resell this content. . guarantees or conditions. Should a catchable error occur (most errors can be caught). It is illegal to reprint. code that might raise an error is placed within a TRY block. There is no equivalent FINALLY block in TSQL. Question: In what situation might it have been useful to be able to raise a system error? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. This means that you cannot raise a system error within a CATCH block. execution control moves to the CATCH block." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. TRY blocks are enclosed by BEGIN TRY and END TRY statements. The Licensed Content is licensed "as-is.

guarantees or conditions.com or by calling +1 800-785-3448. . Please report any unauthorized use of this content to piracy@microsoft. Another key advantage of structured exception handling in T-SQL is that a series of error handling functions have been provided and these functions retain their values throughout the CATCH block. It is illegal to reprint. including in sub-scopes such as stored procedures run from within the CATCH block." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Handling Errors in T-SQL Code 12-25 Error Handling Functions Key Points CATCH blocks make the error related information available throughout the duration of the CATCH block. The Licensed Content is licensed "as-is. redistribute. the value held by the @@ERROR system variable was reset as soon as the next statement was executed. Separate functions are provided to provide each of the properties of an error that has been raised. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. or resell this content. Error Handling Functions Recall that when programming with @@ERROR. and provided to you by QuickStart Intelligence. This means that you can write generic error handling stored procedures and they can still access the error related information.

For example. and provided to you by QuickStart Intelligence. For example. . however you are likely to be able to catch that error in a TRY/CATCH block in the code that called the stored procedure where the error occurred. The Licensed Content is licensed "as-is. redistribute. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Often the errors that cannot be caught in the same scope can be caught in a surrounding scope. Question: Given the earlier discussion on the phases of execution of T-SQL statements. Statement level recompilation issues which usually relate to deferred name resolution. you could create a stored procedure that refers to an unknown table. Non-catchable Errors Key Points It is important to realize that while TRY…CATCH blocks allow you to catch a much wider range of errors than you could catch with @@ERROR.QuickStart Intelligence 12-26 Implementing a Microsoft® SQL Server® 2008 R2 Database Catchable vs.com or by calling +1 800-785-3448. how could a syntax error occur once a batch has already started executing? This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. Catchable vs Non-catchable Errors Not all errors can be caught by TRY/CATCH blocks within the same scope that the TRY/CATCH block exists in. guarantees or conditions. you cannot catch all types of errors. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. Common Non-catchable Errors Common examples of non-catchable errors are: • • Compile errors can occur such as syntax errors that prevent a batch from compiling. you might not be able to catch an error within the stored procedure that contains the TRY/CATCH block. An error is only thrown when the procedure actually tries to resolve the name of the table to an objectid.

instead of terminating the batch as usual. When TRY/CATCH blocks are used in conjunction with transactions and SET XACT_ABORT is on. In this example. However. You saw how SET XACT_ABORT ON was used to deal with that issue. XACT_STATE() Look at the code in the slide example. updates may be made to the database. Please report any unauthorized use of this content to piracy@microsoft. If XACT_ABORT is ON." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the transaction may or may not have actually started. It is important to consider that when the CATCH block is entered. . a statement terminating error will cause the code in the CATCH block to be executed. or resell this content. TRY/CATCH and Transactions New SQL Server developers are often surprised that a statement terminating error that occurs within a transaction does not automatically roll that transaction back. A value of 0 indicates that there is no active transaction. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint.com or by calling +1 800-785-3448. the transaction is not automatically rolled back. @@TRANCOUNT is being used to determine if there is a transaction in progress and to roll back if there is one. Note that at this point. The XACT_STATE() function can be used to determine the state of the transaction: A value of 1 indicates that there is an active transaction.QuickStart Intelligence Handling Errors in T-SQL Code 12-27 TRY CATCH and Transactions Key Points If a transaction is current at the time an error occurs. After the rollback however. no further work that would need to be committed is permitted until a rollback has been performed. and provided to you by QuickStart Intelligence. redistribute. Another option is to use the XACT_STATE() function which provides more detailed information in this situation. the statement that caused the error is rolled back. The transaction is considered to be "doomed". The Licensed Content is licensed "as-is. the execution jumps to the CATCH block. guarantees or conditions. such as logging the error.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. or resell this content. and provided to you by QuickStart Intelligence. guarantees or conditions. It is illegal to reprint. .QuickStart Intelligence 12-28 Implementing a Microsoft® SQL Server® 2008 R2 Database A value of -1 indicates that there is a current transaction but that it is doomed. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The only action permitted within the transaction is to roll it back. Please report any unauthorized use of this content to piracy@microsoft.

High level . This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is important to realize though that any errors that are not handled in the managed code are passed back to the calling T-SQL code. it will appear to be a 6522 error. you may wish to catch errors as much as possible within managed code. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448.QuickStart Intelligence Handling Errors in T-SQL Code 12-29 Errors in Managed Code Key Points SQL CLR Integration allows for the execution of managed code within SQL Server. (Managed code is discussed in Module 16). and provided to you by QuickStart Intelligence. Errors in Managed Code In general. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. Whenever any error that occurs in managed code is returned to SQL Server.NET try/catch/finally blocks. It is illegal to reprint.NET languages such as C# and VB have detailed exception handling available to them. guarantees or conditions. Another rare but possible cause of errors in managed code would be that the code could execute a RAISERROR T-SQL statement via a SqlCommand object. . Errors can be caught using standard . The Licensed Content is licensed "as-is. Errors can be nested and that error will be wrapping the real cause of the error.

This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. • In the virtual machine. click Start. type Proseware in the Server name text box and click Connect.com or by calling +1 800-785-3448. In the Connect to Server window. Follow the instructions contained within the comments of the script file. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. navigate to D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ. From the File menu. click Project/Solution. 3. Open the 31 – Demonstration 3A.sql script file from within Solution Explorer.QuickStart Intelligence 12-30 Implementing a Microsoft® SQL Server® 2008 R2 Database Demonstration 3A: Deadlock Retry Key Points In this demonstration you will see how to use structured exception handling to retry deadlock errors. Demonstration Steps 1. click Microsoft SQL Server 2008 R2. The Licensed Content is licensed "as-is. click Open.sql script file. Open the 32 – Demonstration 3A 2nd Window. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. redistribute. 2. • Open and execute the 00 – Setup. If Demonstration 1A was not performed: • Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system. 4. click All Programs.sql script file. click SQL Server Management Studio.ssmssln and click Open. . guarantees or conditions.

com or by calling +1 800-785-3448. Before you begin the lab. • In the Virtual Machine Connection window. and then click Other User. click Start. 7. 5. you must complete the following steps: 1. Maximize the Hyper-V Manager window. 6. if the virtual machine 623XB-MIA-DC is not started: • Right-click 623XB-MIA-DC and click Start. If you are prompted to confirm that you want to revert. you will use the available virtual machine environment. Please report any unauthorized use of this content to piracy@microsoft. In Virtual Machine Connection window. click on the Revert toolbar icon. In the Virtual Machines list. if the user is not already logged on: • On the Action menu. • Right-click 623XB-MIA-SQL and click Connect. On the host computer. In the Virtual Machines list. or resell this content. • Log on using the following credentials: This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. 2.QuickStart Intelligence Handling Errors in T-SQL Code 12-31 Lab 12: Handling Errors in T-SQL Code Lab Setup For this lab." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 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. redistribute. The Licensed Content is licensed "as-is. It is illegal to reprint. click Revert. . and provided to you by QuickStart Intelligence. • Right-click 623XB-MIA-DC and click Connect. wait until the Press CTRL+ALT+DELETE to log on message appears. • In the Virtual Machine Connection window. In the Virtual Machine Connection window. wait until the Press CTRL+ALT+DELETE to log on message appears. 4. point to Administrative Tools. guarantees or conditions. • Click Switch User. and then click Hyper-V Manager. 3. click the Ctrl-Alt-Delete menu item. and then close the Virtual Machine Connection window.

. From the View menu. guarantees or conditions. In the Open Project window. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. In the virtual machine. click Microsoft SQL Server 2008 R2. Lab Scenario In this lab. If time permits. 10. 11. If the Server Manager window appears. click Execute on the toolbar. The Licensed Content is licensed "as-is.sql. In the Authentication drop-down list box. He has heard that structured exception handling is more powerful and wishes to use it instead. type Proseware in the Server name text box. you will also design and implement changes to a stored procedure to provide for automated retry on deadlock errors.QuickStart Intelligence 12-32 Implementing a Microsoft® SQL Server® 2008 R2 Database i. and click SQL Server Management Studio. Password: Pa$$w0rd 8. double-click the query 00-Setup. click Start. in the Virtual Machine Connection window. The code was written some time back and uses simple T-SQL error handling. click Full Screen Mode. When the query window opens.com or by calling +1 800-785-3448. 15. In Solution Explorer. click Open. click All Programs. check the Do not show me this console at logoncheck box and close the Server Manager window. In the File menu. User name: AdventureWorks\Administrator ii." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and click Project/Solution. 12. 13. It is illegal to reprint. select Windows Authentication and click Connect. Please report any unauthorized use of this content to piracy@microsoft. open the project D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ. a company developer asks you for assistance with some code he is modifying. In Connect to Server window. 9.ssmssln. redistribute. 14. or resell this content. and provided to you by QuickStart Intelligence.

The Licensed Content is licensed "as-is. calling the rewritten stored procedure Marketing.com or by calling +1 800-785-3448. . 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you need to modify his code to use structured exception handling. Review the existing code Rewrite the stored procedure to use structured exception handling Test that the procedure  Task 1: Review the existing code • Review the existing code in the procedure Marketing.MoveCampaignBalance_Test. 3. guarantees or conditions.  Task 3: Test the stored procedure • Test that the stored procedure still works as expected Results: After this exercise. you have created a stored procedure that uses structured exception handling. It is illegal to reprint. The main tasks for this exercise are as follows: 1. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. redistribute.MoveCampaignBalance  Task 2: Rewrite the stored procedure to use structured exception handling • Rewrite the stored procedure to use structured exception handling. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. or resell this content.QuickStart Intelligence Handling Errors in T-SQL Code 12-33 Exercise 1: Replace @@ERROR based error handling with structured exception handling Scenario In this exercise.

MoveCampaignBalance_Test stored procedure to re-try on deadlock up to five times  Task 2: Test the stored procedure • Test that the procedure still works as expected Results: After this exercise. To assist them. you have modified a stored procedure to automatically retry code for deadlock errors. .QuickStart Intelligence 12-34 Implementing a Microsoft® SQL Server® 2008 R2 Database Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits) Scenario In this exercise. The Licensed Content is licensed "as-is. The main tasks for this exercise are as follows: 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. the operations team have mentioned that the same stored procedure also seems to routinely fail with deadlock errors. redistribute. Modify the code to re-try on deadlock Test the stored procedure  Task 1: Modify the code to re-try on deadlock • Modify the code for the Marketing. 2. It is illegal to reprint. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. make further modifications to your new procedure to add automatic retry code for deadlock errors.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. and provided to you by QuickStart Intelligence.

QuickStart Intelligence 12-35 Module Review and Takeaways Review Questions 1. What is the purpose of the SET XACT_ABORT ON statement? Why should retry logic be applied to deadlock handling? Give an example of an error that retries would not be useful for. guarantees or conditions. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. 2. Otherwise. The Licensed Content is licensed "as-is. attempt to perform the work and commit the transaction." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . do not assume that database operations will always occur without error. Best Practices a) b) When designing client-side database access code. This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence. 3. retry step b). Instead of a pattern like: • Start a transaction • Do some work • Commit the transaction Consider instead a pattern like: • Reset the retry count • While the transaction is not committed and the retry count is not exhausted. redistribute. It is illegal to reprint. • If an error occurs and it is an error that retries could apply to. return the error to the calling code.com or by calling +1 800-785-3448.

or resell this content. Please report any unauthorized use of this content to piracy@microsoft. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. . guarantees or conditions. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.QuickStart Intelligence 12-36 Implementing a Microsoft® SQL Server® 2008 R2 Database This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. It is illegal to reprint.

redistribute. . guarantees or conditions. It is illegal to reprint. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. or resell this content.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Notes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . or resell this content. It is illegal to reprint. The Licensed Content is licensed "as-is. redistribute.QuickStart Intelligence Notes This is a unique copy of the course material identified by code 2cdcc42b-1308-4fde-9163-f0e56003def8. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.