Sei sulla pagina 1di 480

OFFICIAL

MICROSOFT

6232B

L EARNING

OFFICIAL MICROSOFT 6232B L EARNING PRODUCT Implementing a Microsoft® SQL Server® 2008 R2 Database Volume 1

PRODUCT

Implementing a Microsoft® SQL Server® 2008 R2 Database

Volume 1

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

MICROSOFT LICENSE TERMS OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER EDITION Pre-Release and Final Release Versions

These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to the Licensed Content named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft

updates,

supplements,

Internet-based services, and

support services

for this Licensed Content, unless other terms accompany those items. If so, those terms apply.

By using the Licensed Content, you accept these terms. If you do not accept them, do not use the Licensed Content.

If you comply with these license terms, you have the rights below.

1. DEFINITIONS.

a. Academic Materialsmeans the printed or electronic documentation such as manuals, workbooks, white papers, press releases, datasheets, and FAQs which may be included in the Licensed Content.

b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions location, an IT Academy location, or such other entity as Microsoft may designate from time to time.

c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and conducted at or through Authorized Learning Centers by a Trainer providing training to Students solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or “MOC”) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions Courseware). Each Authorized Training Session will provide training on the subject matter of one (1) Course.

d. Course” means one of the courses using Licensed Content offered by an Authorized Learning Center during an Authorized Training Session, each of which provides training on a particular Microsoft technology subject matter.

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

f. Licensed Contentmeans the materials accompanying these license terms. The Licensed Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student Content, (iii) classroom setup guide, and (iv) Software. There are different and separate components of the Licensed Content for each Course.

g. Softwaremeans the Virtual Machines and Virtual Hard Disks, or other software applications that may be included with the Licensed Content.

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

i. “Student Content” means the learning materials accompanying these license terms that are for use by Students and Trainers during an Authorized Training Session. Student Content may include labs, simulations, and courseware files for a Course.

j. Trainer(s)means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer and b) such other individual as authorized in writing by Microsoft and has been engaged by an Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its behalf.

k. Trainer Contentmeans the materials accompanying these license terms that are for use by Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and demonstration guides and script files for a Course.

l. Virtual Hard Disks” means Microsoft Software that is comprised of virtualized hard disks (such as a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single computer or other device in order to allow end-users to run multiple operating systems concurrently. For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”.

and a configuration file setting the parameters of the virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”.

n. youmeans the Authorized Learning Center or Trainer, as applicable, that has agreed to these license terms.

2. OVERVIEW.

Licensed Content. The Licensed Content includes Software, Academic Materials (online and electronic), Trainer Content, Student Content, classroom setup guide, and associated media.

License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center location or per Trainer basis.

3. INSTALLATION AND USE RIGHTS.

a. Authorized Learning Centers and Trainers:

For each Authorized Training Session, you may:

i. either install individual copies of the relevant Licensed Content on classroom Devices only for use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided that the number of copies in use does not exceed the number of Students enrolled in and the Trainer delivering the Authorized Training Session, OR

ii. install one copy of the relevant Licensed Content on a network server only for access by classroom Devices and only for use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided that the number of Devices accessing the Licensed Content on such server does not exceed the number of Students enrolled in and the Trainer delivering the Authorized Training Session.

iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to use the Licensed Content that you install in accordance with (ii) or (ii) above during such Authorized Training Session in accordance with these license terms.

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

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

b. Trainers:

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

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

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

B. Portable Device. You may install another copy on a portable device solely for your own personal training Use and for preparation of an Authorized Training Session.

4. PRE-RELEASE VERSIONS. If this is a pre-release (“beta”) version, in addition to the other provisions in this agreement, these terms also apply:

a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not contain the same information and/or work the way a final version of the Licensed Content will. We may change it for the final, commercial version. We also may not release a commercial version. You will clearly and conspicuously inform any Students who participate in each Authorized Training Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with any further content, including but not limited to the final released version of the Licensed Content for the Course.

b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to Microsoft, without charge, the right to use, share and commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with any specific parts of a Microsoft software, Licensed Content, or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software or documentation to third parties because we include your feedback in them. These rights survive this agreement.

i.

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

ii. Survival. Your duty to protect confidential information survives this agreement.

iii. Exclusions. You may disclose confidential information in response to a judicial or governmental order. You must first give written notice to Microsoft to allow it to seek a protective order or otherwise protect the information. Confidential information does not include information that

becomes publicly known through no wrongful act;

you received from a third party who did not breach confidentiality obligations to Microsoft or its suppliers; or

you developed independently.

d. Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs you is the end date for using the beta version, or (ii) the commercial release of the final release version of the Licensed Content, whichever

is first (“beta term”).

e. Use. You will cease using all copies of the beta version upon expiration or termination of the beta term, and will destroy all copies of same in the possession or under your control and/or in the possession or under the control of any Trainers who have received copies of the pre-released version.

f. Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you for such copies and distribution.

5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.

a. Authorized Learning Centers and Trainers:

i. Software.

ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced Server and/or other Microsoft products which are provided in Virtual Hard Disks.

A. If the Virtual Hard Disks and the labs are launched through the Microsoft Learning Lab Launcher, then these terms apply:

Time-Sensitive Software. If the Software is not reset, it will stop running based upon the time indicated on the install of the Virtual Machines (between 30 and 500 days after you install it). You will not receive notice before it stops running. You may not be able to access data used or information saved with the Virtual Machines when it stops running and may be forced to reset these Virtual Machines to their original state. You must remove the Software from the Devices at the end of each Authorized Training Session and reinstall and launch it prior to the beginning of the next Authorized Training Session.

B. If the Virtual Hard Disks require a product key to launch, then these terms apply:

Microsoft will deactivate the operating system associated with each Virtual Hard Disk. Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized Training Session, you will obtain from Microsoft a product key for the operating system software for the Virtual Hard Disks and will activate such Software with Microsoft using such product key.

C. These terms apply to all Virtual Machines and Virtual Hard Disks:

You may only use the Virtual Machines and Virtual Hard Disks if you comply with the terms and conditions of this agreement and the following security requirements:

o

You may not install Virtual Machines and Virtual Hard Disks on portable Devices or Devices that are accessible to other networks.

o

You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at the end of each Authorized Training Session, except those held at Microsoft Certified Partners for Learning Solutions locations.

o

You must remove the differencing drive portions of the Virtual Hard Disks from all classroom Devices at the end of each Authorized Training Session at Microsoft Certified Partners for Learning Solutions locations.

o

You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or downloaded from Devices on which you installed them.

o

You will strictly comply with all Microsoft instructions relating to installation, use, activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.

o

You may not modify the Virtual Machines and Virtual Hard Disks or any contents thereof.

o

You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.

ii .

Classroom Setup Guide. You will assure any Licensed Content installed for use during an Authorized Training Session will be done in accordance with the classroom set-up guide for the Course.

iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip art, animations, sounds, music, shapes, video clips and templates provided with the Licensed Content solely in an Authorized Training Session. If Trainers have their own copy of the Licensed Content, they may use Media Elements for their personal training use.

iv. iv

Evaluation Software. Any Software that is included in the Student Content designated as “Evaluation

Software” may be used by Students solely for their personal training outside of the Authorized Training Session.

b. Trainers Only:

i.

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

ii .

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

iii.

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

The use of the Academic Materials will be only for your personal reference or training use

You will not republish or post the Academic Materials on any network computer or broadcast in any media;

You will include the Academic Material’s original copyright notice, or a copyright notice to Microsoft’s benefit in the format provided below:

Form of Notice:

© 2010 Reprinted for personal reference use only with permission by Microsoft Corporation. All rights reserved.

Microsoft, Windows, and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the US and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.

6. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed Content. It may change or cancel them at any time. You may not use these services in any way that could harm them or impair anyone else’s use of them. You may not use the services to try to gain unauthorized access to any service, data, account or network by any means.

7. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this agreement. In doing so, you must comply with any

technical limitations in the Licensed Content that only allow you to use it in certain ways.

You may not

install more copies of the Licensed Content on classroom Devices than the number of Students and the Trainer in the Authorized Training Session;

allow more classroom Devices to access the server than the number of Students enrolled in and the Trainer delivering the Authorized Training Session if the Licensed Content is installed on a network server;

copy or reproduce the Licensed Content to any server or location for further reproduction or distribution;

disclose the results of any benchmark tests of the Licensed Content to any third party without Microsoft’s prior written approval;

work around any technical limitations in the Licensed Content;

reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent that applicable law expressly permits, despite this limitation;

make more copies of the Licensed Content than specified in this agreement or allowed by applicable law, despite this limitation;

publish the Licensed Content for others to copy;

transfer the Licensed Content, in whole or in part, to a third party;

access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not been authorized by Microsoft to access and use;

rent, lease or lend the Licensed Content; or

use the Licensed Content for commercial hosting services or general business purposes.

Rights to access the server software that may be included with the Licensed Content, including the Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft intellectual property in software or devices that may access the server.

8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the Licensed Content. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting.

9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed Content marked as “NFR” or “Not for Resale.”

10. ACADEMIC EDITION. You must be a “Qualified Educational User” to use Licensed Content marked as “Academic Edition”

or “AE.”

the Microsoft affiliate serving your country.

If you do not know whether you are a Qualified Educational User, visit www.microsoft.com/education or contact

11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail to comply with the terms and conditions of these license terms. In the event your status as an Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this agreement, you must destroy all copies of the Licensed Content and all of its component parts.

12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the Licensed Content and support services.

13. APPLICABLE LAW.

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

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

15. DISCLAIMER OF WARRANTY.

The Licensed Content is licensed “as-is.” You bear the risk of using it.

Microsoft gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this agreement cannot change. To the extent permitted under your local laws, Microsoft excludes the implied warranties of merchantability, fitness for a particular purpose and non- infringement.

16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.

This limitation applies to

anything related to the Licensed Content, software, services, content (including code) on third party Internet sites, or third party programs; and

claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.

It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages.

Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this agreement are provided below in French.

Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.

EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.

LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.

Cette limitation concerne:

tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et

les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.

Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard.

EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.

Implementing a Microsoft® SQL Server® 2008 R2 Database

ix

Implementing a Microsoft® SQL Server® 2008 R2 Database ix

x

Implementing a Microsoft® SQL Server® 2008 R2 Database

Acknowledgements

Microsoft Learning would like to acknowledge and thank the following for their contribution towards developing this title. 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.

Implementing a Microsoft® SQL Server® 2008 R2 Database

xi

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

xii

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

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

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

About This Course

xiii

About This Course

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

Course Description

This five-day instructor-led course is intended for Microsoft® SQL Server database developers who are responsible for implementing a database on SQL Server 2008 R2. In this course, 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.

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. To be successful in this course, the student should have knowledge of basic relational database concepts and writing T-SQL queries.

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, students will be able to:

Understand the product, its components, 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, covering indexes, and included columns

Design and implement stored procedures

Implement table types, table valued parameters, and the MERGE statement

Describe transactions, transaction isolation levels, and application design patterns for highly- concurrent applications

Design and implement T-SQL error handling and structured exception handling

Design and implement scalar and table-valued functions

Design and implement constraints

xiv

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, “Introduction to SQL Server 2008 R2 and its Toolset” introduces you to the entire SQL Server platform and its major tools. This module also covers editions, versions, basics of network listeners, and concepts of services and service accounts.

Module 2, “Working with Data Types” describes the data types supported by SQL Server and how to work with them.

Module 3, “Designing and Implementing Tables” describes the design and implementation of tables.

Module 4, “Designing and Implementing Views” describes the design and implementation of views.

Module 5, “Planning for SQL Server 2008 R2 Indexing” describes the concept of an index and discusses selectivity, density, and statistics. This module also covers appropriate data type choices and choices around composite index structures.

Module 6, “Implementing Table Structures in SQL Server 2008 R2” covers clustered indexes and heaps.

Module 7, “Reading SQL Server 2008 R2 Execution Plans” introduces the concept of reading execution plans.

Module 8, “Improving Performance through Nonclustered Indexes” covers non-clustered indexes, covering indexes and included columns.

Module 9, “Designing and Implementing Stored Procedures” describes the design and implementation of stored procedures.

Module 10, “Merging Data and Passing Tables” covers table types, table valued parameters and the MERGE statement as used in stored procedures.

Module 11, “Creating Highly Concurrent SQL Server 2008 R2 Applications” covers transactions, isolation levels, and designing for concurrency.

Module 12, “Handling Errors in T-SQL Code” describes structured exception handling and gives solid examples of its use within the design of stored procedures.

Module 13, “Designing and Implementing User-Defined Functions” describes the design and implementation of functions, both scalar and table-valued.

Module 14, “Ensuring Data Integrity through Constraints” describes the design and implementation of constraints.

Module 15, “Responding to Data Manipulation via Triggers” describes the design and implementation of triggers.

Module 16, “Implementing Managed Code in SQL Server 2008 R2” describes the implementation of and target use-cases for SQL CLR integration.

About This Course

xv

Module 17, “Storing XML Data in SQL Server 2008 R2” covers the XML data type, schema collections, typed and untyped columns and appropriate use cases for XML in SQL Server.

Module 18, “Querying XML Data in SQL Server 2008 R2” covers the basics of FOR XML and XPath Queries.

Module 19, “Working with SQL Server 2008 R2 Spatial Data” describes spatial data and how this data can be implemented within SQL Server.

Module 20, “Working with Full-Text Indexes and Queries” covers full text indexes and queries.

xvi

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, tightly-focused format, which is just right for an effective in-class learning experience.

Lessons: Guide you through the learning objectives and provide the key points that are critical to the success of the in-class learning experience.

Labs: Provide a real-world, hands-on platform for you to apply the knowledge and skills learned in the module.

Module Reviews and Takeaways: Provide improved on-the-job reference material to boost knowledge and skills retention.

Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips when it’s needed.

Course Companion Content on the http://www.microsoft.com/learning/companionmoc/ Site: http://www.microsoft.com/learning/companionmoc/ Site:

Searchable, easy-to-navigate digital content with integrated premium on-line resources designed to supplement the Course Handbook.

Modules: Include companion content, such as questions and answers, detailed demo steps and additional reading links, for each lesson. Additionally, they include Lab Review questions and answers and Module Reviews and Takeaways sections, which contain the review questions and answers, best practices, common issues and troubleshooting tips with answers, and real-world issues and scenarios with answers.

Resources: Include well-categorized additional resources that give you immediate access to the most up-to-date premium content on TechNet, MSDN®, Microsoft Press®

Student Course files on the http://www.microsoft.com/learning/companionmoc/ Site: Includes the Allfiles.exe, a self-extracting executable file that http://www.microsoft.com/learning/companionmoc/ Site: Includes the Allfiles.exe, a self-extracting executable file that contains all the files required for the labs and demonstrations.

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

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

About This Course

xvii

Virtual Machine Environment

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

Virtual Machine Configuration

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

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 - 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. The lab files are located in the folder D:\6232B_Labs on the student computers.

Classroom Setup

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

Course Hardware Level

To ensure a satisfactory student experience, Microsoft Learning requires a minimum equipment configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft Learning Product courseware are taught.

xviii

About This Course

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

1-2

Implementing a Microsoft® SQL Server® 2008 R2 Database

Module Overview

a Microsoft® SQL Server® 2008 R2 Database Module Overview Before beginning to work with SQL Server

Before beginning to work with SQL Server in either a development or an administration role, it is important to understand the overall SQL Server platform. In particular, it is useful to understand that SQL Server is not just a database engine but it is a complete platform for managing enterprise data.

Along with a strong platform, SQL Server provides a series of tools that make the product easy to manage and good target for the application development.

Individual components of SQL Server can operate within separate security contexts. Correctly configuring SQL Server services is important where enterprises are operating with a policy of least possible permissions.

Objectives

After completing this lesson, you will be able to:

Describe the SQL Server Platform

Work with SQL Server Tools

Configure SQL Server Services

Introduction to SQL Server 2008 R2 and its Toolset

1-3

Lesson 1

Introduction to the SQL Server Platform

1-3 Lesson 1 Introduction to the SQL Server Platform SQL Server is a platform for developing

SQL Server is a platform for developing business applications that are data focused. Rather than being a single monolithic application, SQL Server is structured as a series of components. It is important to understand the use of each of the components.

More than a single copy of SQL Server can be installed on a server. Each of these copies is called an instance and can be separately configured and managed.

SQL Server is shipped in a variety of editions, each with a different set of capabilities. 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 a stable and robust platform.

Objectives

After completing this lesson, 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

1-4

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Architecture

SQL Server® 2008 R2 Database SQL Server Architecture Key Points SQL Server is an integrated and

Key Points

SQL Server is an integrated and enterprise-ready platform for data management that offers a low total cost of ownership.

Question: Which other database platforms have you worked with?

Enterprise Ready

While SQL Server is much more than a relational database management system, it provides a very secure, robust, and stable relational database management system. SQL Server is used to manage organizational data and to provide analysis and insights into that data.

The database engine is one of the highest performing database engines available and regularly features in the top of industry performance benchmarks. You can review industry benchmarks and scores at www.tpc.org.

High Availability

Impressive performance is necessary but not at the cost of availability. Organizations need constant access to their data. Many enterprises are now finding a need to have 24 hour x 7 day access available. The SQL Server platform was designed with the highest levels of availability in mind. As each version of the product has been released, more and more capabilities have been added to minimize any potential downtime.

Security

Utmost in the minds of enterprise managers is the need to secure organizational data. Security is not able to be retrofitted after an application or a product is created. SQL Server has been built from the ground up with the highest levels of security as a goal.

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. SQL Server scales from the smallest needs to the largest via a series of editions with increasing capabilities.

Cost of Ownership

Many competing database management systems are expensive to both purchase and to maintain. SQL Server offers very low total cost of ownership. SQL Server tooling (both management and development) builds on existing Windows knowledge. Most users tend to become familiar with the tools quite quickly. The productivity achieved when working with the tools is enhanced by the high degree of integration between the tools. For example, many of the SQL Server tools have links to launch and preconfigure other SQL Server tools.

1-6

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Components

SQL Server® 2008 R2 Database SQL Server Components Key Points SQL Server is a very good

Key Points

SQL Server is a very good relational database engine but as a data platform, it offers much more than a relational database engine.

SQL Server Components

SQL Server is a platform comprising many components, each designed to enhance data management capabilities.

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, power users, and business analysts to quickly analyze large volumes of data from different locations

Replication

Allows moving data between servers to suit data distribution needs

Introduction to SQL Server 2008 R2 and its Toolset

1-7

Question: Which components of SQL Server have you worked with?

1-8

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Instances

SQL Server® 2008 R2 Database SQL Server Instances Key Points It is sometimes useful to install

Key Points

It is sometimes useful to install more than a single copy of a SQL Server component on a single server. Many SQL Server components can be installed more than once as separate instances.

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. Each instance of SQL Server is separately manageable and securable.

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. Each instance of SQL Server is separately configurable.

Application databases might need to be supported with different levels of service, particularly in relation to availability. SQL Server instances can be used to separate workloads with differing service level agreements (SLAs) that need to be met.

Different versions of SQL Server might need to be supported.

Applications might require different server-level collations. While each database can have different collations, an application might be dependent on the collation of the tempdb database when the application is using temporary objects.

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. This can assist when testing upgrade scenarios or performing upgrades.

Default and Named Instances

Prior to SQL Server 2000, only a single copy of SQL Server could be installed on a server system. SQL Server was addressed by the name of the server. To maintain backward compatibility, this mode of connection is still supported and is known as a "default" instance.

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.

Not all components of SQL Server are able to be installed in more than one instance. In particular, SQL Server Integration Services is installed once per server.

There is no need to install SQL Server tools and utilities more than once. A single installation of the tools is able to manage and configure all instances.

1-10

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Editions

SQL Server® 2008 R2 Database SQL Server Editions Key Points SQL Server is available in a

Key Points

SQL Server is available in a wide variety of editions, with different price points and different levels of capability.

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

Uses massively parallel processing (MPP) to execute queries against vast amount of data quickly. Parallel Data Warehouse systems are sold as a complete "appliance" rather than via standard software licenses

Warehouse

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, 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, optimized for a very small memory footprint

Developer

Allows building, testing, and demonstrating all SQL Server functionality

Introduction to SQL Server 2008 R2 and its Toolset

1-11

Workgroup

Runs branch applications with secure remote synchronization and management capabilities

Web

Provides a secure, 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

Question: What would be a good business case example for using a cloud-based service?

1-12

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Versions

SQL Server® 2008 R2 Database SQL Server Versions Key Points SQL Server is a platform with

Key Points

SQL Server is a platform with a rich history of innovation achieved while maintaining strong levels of stability. SQL Server has been available for many years, yet it is rapidly evolving new capabilities and features.

Early Versions

The earliest versions (1.0 and 1.1) were based on the OS/2 operating system.

Versions 4.2 and later moved to the Windows operating system, initially on the Windows NT operating system.

Later Versions

Version 7.0 saw a significant rewrite of the product. Substantial advances were made in reducing the administration workload for the product. OLAP Services (which later became Analysis Services) was introduced.

SQL Server 2000 featured support for multiple instances and collations. It also introduced support for data mining. SQL Server Reporting Services was introduced after the product release as an add-on enhancement to the product, along with support for 64-bit processors.

SQL Server 2005 provided another significant rewrite of many aspects of the product. It introduced support for:

Non-relational data stored and queried as XML.

SQL Server Management Studio was released to replace several previous administrative tools.

SQL Server Integration Services replaced a former tool known as Data Transformation Services (DTS).

Another key addition to the product was the introduction of support for objects created using the Common Language Runtime (CLR).

The T-SQL language was substantially enhanced, including structured exception handling.

Introduction to SQL Server 2008 R2 and its Toolset

1-13

Dynamic Management Views and Functions were introduced to enable detailed health monitoring, performance tuning, and troubleshooting.

Substantial high availability improvements were included in the product. Database mirroring was introduced.

Support for column encryption was introduced.

SQL Server 2008 also provided many enhancements:

The "SQL Server Always On" technologies were introduced to reduce potential downtime.

Filestream support improved the handling of structured and semi-structured data.

Spatial data types were introduced.

Database compression and encryption technologies were added.

Specialized date- and time-related data types were introduced, including support for timezones within datetime data.

Full-text indexing was integrated directly within the database engine. (Previously full-text indexing was based on interfaces to operating system level services).

A policy-based management framework was introduced to assist with a move to more declarative- based management practices, rather than reactive practices.

A PowerShell provider for SQL Server 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.

The introduction of advanced analytic capabilities with PowerPivot.

Improved multi-server management capabilities were added.

Support for managing reference data was provided with the introduction of Master Data Services.

StreamInsight provides the ability to query data that is arriving at high speed, before storing the data in a database.

Data-Tier applications assist with packaging database applications as part of application development projects.

Upcoming Versions

The next version of SQL Server has been announced. This version will enable the efficient delivery of mission-critical solutions through a highly scalable and available platform. Additional productivity tools and features will assist developers and the reach of business intelligence tooling to end-users will be enhanced.

Question: Which versions of SQL Server have you worked with?

1-14

Implementing a Microsoft® SQL Server® 2008 R2 Database

Lesson 2

Working with SQL Server Tools

2008 R2 Database Lesson 2 Working with SQL Server Tools Working effectively with SQL Server requires

Working effectively with SQL Server requires familiarity with the tools that are used in conjunction with SQL Server. Before any tool can connect to SQL Server, it needs to make a network connection to the server. In this lesson, you will see how these connections are made, then look at the tools that are most commonly used when working with SQL Server.

Objectives

After completing this lesson, 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

Introduction to SQL Server 2008 R2 and its Toolset

1-15

Connecting from Clients and Applications

its Toolset 1-15 Connecting from Clients and Applications Key Points Client applications connect to endpoints. A

Key Points

Client applications connect to endpoints. A variety of communication protocols are available for making connections. Also, users need to be identified before they are permitted to use the server.

Connectivity

The protocol that client applications use when connecting to the SQL Server relational database engine is known as Tabular Data Stream (TDS). It defines how requests are issued and how results are returned.

Other components of SQL Server use alternate protocols. For example, clients to SQL Server Analysis Services communicate via the XML for Analysis (XML/A) protocol. However, in this course, you are primarily concerned with the relational database engine.

TDS is a high-level protocol that is transported by lower-level protocols. It is most commonly transported by the TCP/IP protocol, the Named Pipes protocol, or implemented over a shared memory connection. 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.

Authentication

For the majority of applications and organizations, data must be held securely and access to the data is based on the identity of the user attempting to access the data. The process of verifying the identity of a user (or more formally, of any principal), is known as authentication. SQL Server supports two forms of authentication. It can store the login details for users directly within its own system databases. These logins are known as SQL Logins. Alternately, it can be configured to trust a Windows authenticator (such as Active Directory). In that case, a Windows user can be granted access to the server, either directly or via his/her Windows group memberships.

When a connection is made, the user is connected to a specific database, known as their "default" database.

1-16

Implementing a Microsoft® SQL Server® 2008 R2 Database

Software Layers for Connections

Server® 2008 R2 Database Software Layers for Connections Key Points Connections to SQL Server are made

Key Points

Connections to SQL Server are made through a series of software layers. It is important to understand how each of these layers interacts. This knowledge will assist you when you need to perform configuration or troubleshooting.

Client Libraries

Client applications use programming libraries to simplify their access to databases such as SQL Server.

Open Database Connectivity (ODBC) is a commonly used library. It operates as a translation layer that shields the application from some details of the underlying database engine. By changing the ODBC configuration, an application could be altered to work with a different database engine, without the need for application changes.

OLEDB originally stood for Object Linking and Embedding for Databases, however, that meaning is now not very relevant. OLEDB is a library that does not translate commands. When an application sends a SQL command, OLEDB passes it to the database server without modification.

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. This primarily involves wrapping the commands and results in the TDS protocol.

Network Libraries

SQL Server exposes endpoints that client applications can connect to. The endpoint is used to pass commands and data to/from the database engine.

SNAC connects to these endpoints via network libraries such as TCP/IP, Named Pipes, or VIA. Please note that the use of the VIA protocol with SQL Server is now deprecated. For client applications that are

Introduction to SQL Server 2008 R2 and its Toolset

1-17

executing on the same computer as the SQL Server service, a special "shared memory" network connection is also available.

SQL Server Software Layers

SQL Server receives commands via endpoints and sends results to clients via endpoints. Clients interact with the Relational engine which in turn utilizes the Storage engine to manage the storage of databases. 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.

1-18

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Management Studio

SQL Server® 2008 R2 Database SQL Server Management Studio Key Points SQL Server Management Studio (SSMS)

Key Points

SQL Server Management Studio (SSMS) is the primary tool supplied by Microsoft for interacting with SQL Server services.

SQL Server Management Studio

SSMS is an integrated environment that has been created within the Microsoft Visual Studio platform shell. SSMS shares many common features with Visual Studio.

SSMS is used to execute queries and return results but it is also capable of helping users to analyze queries. It offers rich editors for a variety of document types (.sql files, .xml files, etc.). When working with .sql files, SSMS provides IntelliSense to assist with writing queries.

While all SQL Server relational database management tasks can be performed using the T-SQL language, many users prefer graphical administration tools as they are typically easier to use than the T-SQL commands. SSMS provides graphical interfaces for configuring databases and servers.

SSMS is capable of connecting to a variety of SQL Server services including the database engine, Analysis Services, Integration Services, Reporting Services, and SQL Server Compact Edition.

Introduction to SQL Server 2008 R2 and its Toolset

1-19

Demonstration 2A: SQL Server Management Studio

1-19 Demonstration 2A: SQL Server Management Studio Key Points In this demonstration you will see how

Key Points

In this demonstration you will see how to work with SQL Server Management Studio.

Demonstration Setup

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

2. In Hyper-V Manager, in the Virtual Machines pane, right-click 623XB-MIA-SQL1 and click Revert.

3. If you are prompted to confirm that you want to revert, click Revert.

4. If you do not already have a Virtual Machine Connection window, right-click 623XB-MIA-SQL1 and click Connect.

Demonstration Steps

1. In the Virtual Machine, Click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.

2. In the Connect to Server window, ensure that Server Type is set to Database Engine.

3. In the Server name text box, type (local).

4. In the Authentication drop-down list, select Windows Authentication, and click Connect.

5. From the View menu, click Object Explorer.

6. In Object Explorer, expand Databases, expand AdventureWorks2008R2, and Tables. Review the database objects.

7. Right-click the AdventureWorks2008R2 database and choose New Query.

8. Type the query shown in the snippet below.

1-20

Implementing a Microsoft® SQL Server® 2008 R2 Database

9. Note the use of Intellisense while entering it, and then click Execute on the toolbar. Note how the results can be returned.

10. From the File menu click Save SQLQuery1.sql. Note this saves the query to a file.

11. In the Results tab, right-click on the cell for ProductID 1 (first row and first cell) and click Save Results As…. In the FileName textbox, type Demonstration2AResults and click Save. Note this saves the query results to a file.

12. From the Query menu, click Display Estimated Execution Plan. Note that SSMS is capable of more than simply executing queries.

13. From the Tools menu, and click Options.

14. In the Options pane, expand Query Results, expand SQL Server, and expand General. Review the available configuration options and click Cancel.

15. From the File menu, click Close. In the Microsoft SQL Server Management Studio window, click No.

16. In the File menu, click Open, and click Project/Solution.

17. In the Open Project window, open the project

D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ.ssmssln.

18. From the View menu, click Solution Explorer. Note the contents of Solution Explorer. SQL Server projects have been supplied for each module of the course and contain demonstration steps and suggested lab solutions, along with any required setup/shutdown code for the module.

19. In the Solution Explorer, click the X to close it.

20. In Object Explorer, from the Connect toolbar icon, note the other SQL Server components that connections can be made to:

Database Engine

Analysis Services

Integration Services

Reporting Services

SQL Server Compact

21. From the File menu, click New, and click Database Engine Query to open a new connection.

22. In the Connect to Database Engine window, type (local) in the Server name text box.

23. In the Authentication drop-down list, select Windows Authentication, and click Connect.

24. In the Available Databases drop-down list, click tempdb database. Note this will change the database that the query is executed against.

25. Right-click in the query window and click Connection, and click Change Connection… Note: this will reconnect the query to another instance of SQL Server.

26. From the View menu, click Registered Servers.

27. In the Registered Servers window, expand Database Engine, right-click Local Server Groups, and click New Server Group…

28. In the New Server Group Properties window type Dev Servers in the Group name textbox and click OK.

Introduction to SQL Server 2008 R2 and its Toolset

1-21

30. In the New Server Registration window, click Server name drop-down list, type (local) and click Save.

31. Right-click Dev Servers and click New Server Registration…

32. In the New Server Registration window, click Server name drop-down list, type .\MKTG and click Save.

33. In the Registered Servers window, right-click the Dev Servers group and choose New Query.

34. Type the query as shown in the snippet below and click Execute toolbar icon.

SELECT @@version;

Question: When would displaying an estimated execution plan be helpful?

1-22

Implementing a Microsoft® SQL Server® 2008 R2 Database

Business Intelligence Development Studio

2008 R2 Database Business Intelligence Development Studio Key Points The SQL Server platform comprises a number

Key Points

The SQL Server platform comprises a number of components. Projects for several of the Business Intelligence related components are created and modified using Business Intelligence Development Studio (BIDS).

Business Intelligence Development Studio

BIDS is a series of project templates that have been added to the Microsoft Visual Studio 2008 environment. The templates allow the creation and editing of projects for Analysis Services, Integration Services, and Reporting Services.

Visual Studio does not need to be installed before SQL Server. If an existing installation of Visual Studio 2008 is present, SQL Server installation will add project templates into that environment. If no existing Visual Studio 2008 installation is present, SQL Server installation will first install the "partner" edition of Visual Studio 2008 and then add the required project templates. The Partner edition of Visual Studio 2008 is essentially an empty Visual Studio shell with a template for a "blank solution".

BIDS in SQL Server 2008 R2 is based on Visual Studio 2008. If Visual Studio 2010 is already installed, SQL Server will install the partner edition of Visual Studio 2008 side-by-side with the existing Visual Studio 2010 installation.

Introduction to SQL Server 2008 R2 and its Toolset

1-23

Demonstration 2B: Business Intelligence Development Studio

Demonstration 2B: Business Intelligence Development Studio Key Points In this demonstration you will see how to

Key Points

In this demonstration you will see how to work with SQL Server Business Intelligence Development Studio.

Demonstration Steps

1. If Demonstration 2A was not performed:

Revert the 623XB-MIA-SQL1 virtual machine using Hyper-V Manager on the host system, and connect to the Virtual Machine.

2. In the Virtual Machine, Click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Business Intelligence Development Studio (BIDS). From the File menu, expand New, and click Project. Note the available project templates(If other languages are installed, note how they are still present as well).

3. In the Templates pane, click Report Server Project, and click OK.

4. In Solution Explorer, right-click Reports and click Add New Report.

5. In the Report Wizard window, click Next.

6. In the Select the Data Source window, click Edit.

7. In the Connection Properties window, type (local) for the Server name and in the Connect to a database drop-down list, select AdventureWorks2008R2, and click OK.

8. In the Select the Data Source window, click Next.

9. In the Design the Query window, for the Query string textbox, type the following query as shown in snippet below and click Next.

SELECT ProductID, Name, Color, Size FROM Production.Product ORDER BY ProductID;

1-24

Implementing a Microsoft® SQL Server® 2008 R2 Database

11. In the Design the Table window, click Details four times, and click Finish>>|.

12. In the Completing the Wizard window, click Finish.

13. In the Report1.rdl [Design] tab, click Preview and note the report that is rendered.

14. Click on the Design tab, from the File menu click Exit. Note do not save the changes.

Question: Can you suggest a situation where the ability to schedule the execution of a report would be useful?

Introduction to SQL Server 2008 R2 and its Toolset

1-25

Books Online

to SQL Server 2008 R2 and its Toolset 1-25 Books Online Key Points Books Online (BOL)

Key Points

Books Online (BOL) is the primary reference for SQL Server. 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).

Books Online

BOL should be regarded as the primary technical reference for SQL Server.

A common mistake when installing BOL locally on a SQL Server installation is to neglect to update BOL regularly. To avoid excess download file sizes, BOL is not included in SQL Server service pack and cumulative update packages. BOL is regularly updated and a regular check should be made for updates.

For most T-SQL commands, many users will find the examples supplied easier to follow than the formal syntax definition. Note that when viewing the reference page for a statement, the formal syntax is shown at the top of the page and the examples are usually at the bottom of the page.

BOL is available for all supported versions of SQL Server. It is important to make sure you are working with the pages designed for the version of SQL Server that you are working with. Many pages in BOL provide links to related pages from other versions of the product.

1-26

Implementing a Microsoft® SQL Server® 2008 R2 Database

Demonstration 2C: Books Online

SQL Server® 2008 R2 Database Demonstration 2C: Books Online Key Points In this demonstration you will

Key Points

In this demonstration you will see how to work with SQL Server Business Books Online.

Demonstration Steps

1. If Demonstration 2A was not performed:

Revert the 623XB-MIA-SQL1 virtual machine using Hyper-V Manager on the host system, and connect to the Virtual Machine.

2. In the Virtual Machine, Click Start, click All Programs, click Microsoft SQL Server 2008 R2, click Documentation and Tutorials, and click SQL Server Books Online.

3. In the Contents window, click SQL Server 2008 R2 Books Online. Note the basic navigation options available within BOL.

4. In the Virtual Machine, Click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.

5. In the Connect to Server window, ensure that Server Type is set to Database Engine.

6. In the Server name text box, type (local).

7. In the Authentication drop-down list, select Windows Authentication, and click Connect.

8. From the File menu, click New, and click Query with Current Connection.

9. In the SQLQuery1.sql tab, type the query as shown in the snippet below and click Execute toolbar icon.

SELECT SUBSTRING('test string',2,7);

Introduction to SQL Server 2008 R2 and its Toolset

1-27

11. In the Online Help Settings window, ensure Use local Help as primary source option button, and click OK. Note the content of the page and scroll to the bottom to see the examples.

12. From the File menu, click Exit.

13. In the host system, open Internet Explorer and browse to the SQL Server Books Online page:

http://msdn.microsoft.com/en-us/library/ms130214.aspx and note the available online options.

1-28

Implementing a Microsoft® SQL Server® 2008 R2 Database

Lesson 3

Configuring SQL Server Services

2008 R2 Database Lesson 3 Configuring SQL Server Services Each SQL Server service can be configured

Each SQL Server service can be configured individually. The ability to provide individual configuration for services assists organizations that aim to minimize the permissions assigned to service accounts, as part of a policy of least privilege execution. SQL Server Configuration Manager is used to configure services, including the accounts that the services operate under, and the network libraries used by the SQL Server services.

SQL Server also ships with a variety of tools and utilities. It is important to know what each of these tools and utilities is used for.

Objectives

After completing this lesson, 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

Introduction to SQL Server 2008 R2 and its Toolset

1-29

SQL Server Configuration Manager

R2 and its Toolset 1-29 SQL Server Configuration Manager Key Points SQL Server Configuration Manager (SSCM)

Key Points

SQL Server Configuration Manager (SSCM) is used to configure SQL Server services, to configure the network libraries exposed by SQL Server services, 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.

Managing Server Protocols – It is possible to configure the endpoints that are exposed by the SQL Server services. This includes the protocols and ports used.

Managing Client Protocols – When client applications (such as SSMS) are installed on a server, there is a need to configure how connections from those tools are made to SQL Server. SSCM can be used to configure the protocols required and can be used to create aliases for the servers to simplify connectivity.

Question: Why would a server system need to have a client configuration node?

1-30

Implementing a Microsoft® SQL Server® 2008 R2 Database

SQL Server Services

SQL Server® 2008 R2 Database SQL Server Services Key Points SQL Server Configuration Manager can be

Key Points

SQL Server Configuration Manager can be used to configure the individual services that are provided by SQL Server. Many components provided by SQL Server are implemented as operating system services. The components of SQL Server that you choose during installation determine which of the SQL Server services are installed.

SQL Server Services

These services operate within a specific Windows identity. If there is a need to alter the assigned identity for a service, SSCM should be used to make this change. A common error is to use the Services applet in the server's administrative tools to change the service identity. 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. When service identities are modified from within SSCM, the required permissions and access control lists are also modified.

Each service has a start mode. This mode can be set to Automatic, Manual, or Disabled. Services that are set to the Automatic start mode are automatically started when the operating system starts. Services that are set to the Manual start mode can be manually started. Services that are set to the Disabled start mode cannot be started.

Instances

Many SQL Server components are instance-aware and can be installed more than once on a single server. When SSCM lists each service, it shows the associated instance of SQL Server in parentheses after the name of the service.

In the example shown in the slide, there are two instances of the database engine installed. PARTNER is the name of a named instance of the database engine. MSSQLSERVER is the default name allocated to the default instance of the SQL Server database engine.

Introduction to SQL Server 2008 R2 and its Toolset

1-31

Network Ports and Listeners

2008 R2 and its Toolset 1-31 Network Ports and Listeners Key Points SQL Server Configuration Manager

Key Points

SQL Server Configuration Manager can be used to configure both server and client protocols and ports.

Network Ports and Listeners

SSCM provides two sets of network configurations. Each network endpoint that is exposed by an instance of SQL Server can be configured. This includes the determination of which network libraries are enabled and, for each library, the configuration of the network library. Typically, this will involve settings such as protocol port numbers. You should discuss the required network protocol configuration of SQL Server with your network administrator.

Many protocols provide multiple levels of configuration. For example, the configuration for the TCP/IP protocol allows for different settings on each configured IP address if required, or a general set of configurations that are applied to all IP addresses.

Client Configurations

Every computer that has SNAC installed needs the ability to configure how that library will access SQL Server services.

SNAC is installed on the server as well as on client systems. When SSMS is installed on the server, it uses the SNAC library to make connections to the SQL Server services that are on the same system. The client configuration nodes within SSCM can be used to configure how those connections are made. Note that two sets of client configurations are provided. One set is used for 32-bit applications; the other set is used for 64-bit applications. SSMS is a 32-bit application, even when SQL Server is installed as a 64-bit application.

1-32

Implementing a Microsoft® SQL Server® 2008 R2 Database

Creating Server Aliases

SQL Server® 2008 R2 Database Creating Server Aliases Key Points Connecting to a SQL Server service

Key Points

Connecting to a SQL Server service can involve multiple settings such as server address, protocol, and port. To make this easier for client applications and to provide a level of available redirection, aliases can be created for servers.

Aliases

Hard-coding connection details for a specific server, protocol, and port within an application is not desirable as these might need to change over time.

A server alias can be created and associated with a server, protocol, and port (if required). Client

applications can then connect to the alias without being concerned about how those connections are

made.

Each client system that utilizes SNAC (including the server itself) can have one or more aliases configured. Aliases for 32-bit applications are configured independently of the aliases for 64-bit applications.

In the example shown in the slide, the alias "Marketing" has been created for the local server "." and

utilizing the named pipes protocol "np" and named pipe address that is based on the name of the computer or the value "." for the local computer. The client then only needs to connect to the name "Marketing".

Introduction to SQL Server 2008 R2 and its Toolset

1-33

Other SQL Server Tools

Server 2008 R2 and its Toolset 1-33 Other SQL Server Tools Key Points SQL Server provides

Key Points

SQL Server provides a rich set of tools and utilities to make working with the product easier.

The most commonly used tools are listed in the following table:

Tool

Purpose

SQL Server Profiler

Trace activity from client applications to SQL Server. Supports both the database engine and Analysis Services.

Database Engine Tuning Advisor

Design indexes and statistics to improve database performance, based on analysis of trace workloads.

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 Reporting

Configure the level of automated reporting back to the SQL Server product team about errors that occur and on usage of different aspects of the product.

PowerShell Provider

Allow configuring and querying SQL Server using PowerShell.

SQL Server Management Objects (SMO)

Provide a detailed .NET based library for working with management aspects of SQL Server directly from application code.

1-34

Implementing a Microsoft® SQL Server® 2008 R2 Database

Demonstration 3A: SQL Server Profiler

2008 R2 Database Demonstration 3A: SQL Server Profiler Key Points In this demonstration you will see

Key Points

In this demonstration you will see how SQL Server Profiler can capture traces of statements executed.

Demonstration Steps

1. If Demonstration 2A was not performed:

Revert the 623XB-MIA-SQL1 virtual machine using Hyper-V Manager on the host system, and connect to the Virtual Machine.

2. In the Virtual Machine, Click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.

3. In the Connect to Server window, ensure that Server Type is set to Database Engine.

4. In the Server name text box, type (local).

5. In the Authentication drop-down list, select Windows Authentication, and click Connect.

6. From the Tools menu, click SQL Server Profiler.

7. In the Connect to Server window, ensure that Server Type is set to Database Engine.

8. In the Server name text box, type (local).

9. In the Authentication drop-down list, select Windows Authentication, and click Connect.

10. In the Trace Properties window, click Run. Note this will start a new trace with the default options.

11. Switch to SSMS, click New Query toolbar icon.

12. In the Query window, type the query as shown in the snippet below, and click Execute toolbar icon.

Introduction to SQL Server 2008 R2 and its Toolset

1-35

GO

13. Switch to SQL Server Profiler. Note the statement trace occurring in SQL Server Profiler.

14. From the File menu and click Stop Trace.

15. In the Results grid, click individual statements to see the detail shown in the lower pane.

Question: What could you use captured trace files for?

1-36

Implementing a Microsoft® SQL Server® 2008 R2 Database

Lab 1: Introduction to SQL Server and its Toolset

Database Lab 1: Introduction to SQL Server and its Toolset Lab Setup For this lab, you

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

3. In the Virtual Machines list, right-click 623XB-MIA-DC and click Start.

4. Right-click 623XB-MIA-DC and click Connect.

5. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, then close the Virtual Machine Connection window.

6. In Hyper-V Manager, in the Virtual Machines list, right-click 623XB-MIA-SQL1 and click Start.

7. Right-click 623XB-MIA-SQL1 and click Connect.

8. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.

9. On the Action menu, click the Ctrl+Alt+Delete menu item.

10. Click Switch User, then click Other User.

11. Log on using the following credentials:

User name: AdventureWorks\Administrator

Password: Pa$$w0rd

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

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

Lab Scenario

AdventureWorks is a global manufacturer, wholesaler and retailer of cycle products. The owners of the company have decided to start a new direct marketing arm of the company. It has been created as a new company named Proseware, Inc. Even though it has been set up as a separate company, it will receive

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. 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. In this lab, you are ensuring that the additional instance of SQL Server has been configured appropriately and making a number of additional required configuration changes.

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. It will be used by the new direct marketing company. The SQL Server named instance is called MKTG. In the first exercise, you need to verify that the required SQL Server components have been installed.

The main tasks for this exercise are as follows:

1. Check that Database Engine and Reporting Services have been installed for the MKTG instance.

2. Note the services that are installed for the default instance and that Integration Services is not installed on a per instance basis.

3. Ensure that all required services including SQL Server Agent are started and set to autostart for both instances.

Task 1: Check that Database Engine and Reporting Services have been installed for the MKTG instance

Open SQL Server Configuration Manager.

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.

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 that Integration Services has no instance name shown as it is not installed on a per-instance basis.

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. (Ignore the Full Text Filter Daemon at this time).

Ensure that all the services for the default instance are set to autostart. (Ignore the Full Text Filter Daemon at this time).

Results: After this exercise, you have checked that the required SQL Server services are installed, started, and configured to autostart.

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. In this exercise, you will configure the services to execute under the AdventureWorks\PWService service account.

The main tasks for this exercise are as follows:

1. Change the service account for the MKTG database engine.

2. Change the service account for the MKTG SQL Server Agent.

3. Change the service account for the MKTG Reporting Services service.

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.

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.

Results: After this exercise, you have configured the service accounts for the MKTG instance.

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. In this exercise, you will enable the named pipes protocol for both database engine instances.

The main tasks for this exercise are as follows:

1. Enable the named pipes protocol for the default instance.

2. Enable the named pipes protocol for the MKTG instance.

3. Restart database engine services for both instances.

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.

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.

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, you should have enabled the named pipes protocol for both database engine instances.

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. In this exercise, you will configure aliases for both the default instance (AdventureWorks) and for the MKTG instance (Proseware). Both 32-bit and 64-bit aliases should be configured. You will use SQL Server Management Studio to test the aliases once they have been configured.

The main tasks for this exercise are as follows:

1. Create a 32-bit alias (AdventureWorks) for the default instance.

2. Create a 32-bit alias (Proseware) for the MKTG instance.

3. Create a 64-bit alias (AdventureWorks) for the default instance.

4. Create a 64-bit alias (Proseware) for the MKTG instance.

5. Use SQL Server Management Studio to connect to both aliases to ensure they work as expected.

Task 1: Create a 32-bit alias (AdventureWorks) for the default instance

Create a 32-bit alias for the default instance. Call the alias AdventureWorks and connect via named pipes. Use the servername ".".

Task 2: Create a 32-bit alias (Proseware) for the MKTG instance

Create a 32-bit alias for the MKTG instance. Call the alias Proseware and connect via named pipes. Use the servername ".\MKTG".

Task 3: Create a 64-bit alias (AdventureWorks) for the default instance

Create a 64-bit alias for the default instance. Call the alias AdventureWorks and connect via named pipes. Use the servername ".".

Task 4: Create a 64-bit alias (Proseware) for the MKTG instance

Create a 64-bit alias for the MKTG instance. Call the alias Proseware and connect via named pipes. Use the servername ".\MKTG".

Task 5: Use SQL Server Management Studio to connect to both aliases to ensure they work as expected

Open SQL Server Management Studio.

Connect to the Proseware alias.

In Object Explorer, connect also to the AdventureWorks alias.

Results: After this exercise, you should have created and tested aliases for both database engine instances.

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. As their connections will need to traverse a firewall, the port used for connections cannot be configured as a dynamic port. The port number must not change. Corporate policy at AdventureWorks is that named instances should be accessed via fixed TCP ports and the SQLBrowser service should be disabled. In this exercise, you will make configuration changes to comply with these requirements. A firewall exception has already been created for port 51550, for use with the MKTG database engine instance.

The main tasks for this exercise are as follows:

1. Configure the TCP port for the MKTG database engine instance to 51550.

Disable the SQLBrowser service.

Task 1: Configure the TCP port for the MKTG database engine instance to 51550

Using the property page for the TCP/IP server protocol, configure the use of the fixed port 51550. (Make sure that you clear the dynamic port)

Restart the MKTG database engine instance.

Ensure that the MKTG database engine instance has been restarted successfully.

Task 2: Disable the SQLBrowser service

Stop the SQLBrowser service.

Set the Start Mode for the SQL Browser service to Disabled.

Results: After this exercise, you will have configured a fixed TCP port for the MKTG database engine instance and disabled the SQLBrowser service.

Introduction to SQL Server 2008 R2 and its Toolset

1-43

Module Review and Takeaways

2008 R2 and its Toolset 1-43 Module Review and Takeaways Review Questions 1. What is the

Review Questions

1. What is the difference between a SQL Server version and an edition?

2. What is the purpose of the Business Intelligence Development Studio?

3. Does Visual Studio need to be installed before BIDS?

Best Practices

1. Ensure that developer edition licenses are not used in production environments.

2. Develop using the least privileges possible, to avoid accidentally building applications that will not run for standard users.

3. If using an offline version of Books Online, ensure it is kept up to date.

1-44

Implementing a Microsoft® SQL Server® 2008 R2 Database

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

2-2

Implementing a Microsoft® SQL Server® 2008 R2 Database

Module Overview

a Microsoft® SQL Server® 2008 R2 Database Module Overview One of the most important decisions that

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. The data type of a column determines the type and range of values that can be stored in the column. Other objects in SQL Server such as variables and parameters also use these same data types.

A

very common design error is to use inappropriate data types. As an example, while you can store a date

in

a string column, doing so is rarely a good idea. In this module, you will see the range of data types that

are available within SQL Server and receive advice on where each should be used.

Objectives

After completing this lesson, you will be able to:

Work with data types

Work with character data

Convert between data types

Use specialized data types

Working with Data Types

2-3

Lesson 1

Using Data Types

Working with Data Types 2-3 Lesson 1 Using Data Types The most basic types of data

The most basic types of data that get stored in database systems are numbers, dates, and strings. There are a range of data types that can be used for each of these. In this lesson, you will see the available range of data types that can be used for numeric and date-related data. You will also see how to determine if a data type should be nullable or not. In the next lesson, you will see how to work with string data types.

Objectives

After completing this lesson, 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

2-4

Implementing a Microsoft® SQL Server® 2008 R2 Database

Introducing Data Types

SQL Server® 2008 R2 Database Introducing Data Types Key Points Data types determine what can be

Key Points

Data types determine what can be stored in locations within SQL Server such as columns, variables, and parameters. For example, a tinyint column can only store values from 0 to 255. They also determine the types of values that can be returned from expressions.

Constraining Values

Data types are a form of constraint that is placed on the values that can be stored in a location. For example, if you choose a numeric data type, you will not be able to store text in the location.

As well as constraining the types of values that can be stored, data types also constrain the range of values that can be stored. For example, if you choose a smallint data type, you can only store values between -32768 and 32767.

Query Optimization

When SQL Server knows that the value in a column is an integer, it may be able to come up with an entirely different query plan to one where it knows the location is holding text values.

The data type also determines which sorts of operations are permitted on that data and how those operations work.

Self-Documenting Nature

Choosing an appropriate data type provides a level of self-documentation. 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, it's likely that you would need to store documentation about what sort of values can be stored in the sql_variant locations.

Working with Data Types

2-5

Data Types

There are three basic sets of data types:

System Data Type - SQL Server provides a large number of built-in (or intrinsic) data types. Examples of these would be integer, varchar, and date.

Alias 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. An example of an alias data type would be to define the name PhoneNumber as being equivalent to nvarchar(16). Alias data types can help provide consistency of data type usage across applications and databases.

User-defined Data Type - With managed code via SQL Server CLR integration, 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. Managed code is discussed later in Module 16.

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"?

2-6

Implementing a Microsoft® SQL Server® 2008 R2 Database

Exact Numeric Data Types

SQL Server® 2008 R2 Database Exact Numeric Data Types Key Points Numeric data types can be

Key Points

Numeric data types can be exact or approximate. Exact data types are the most common data type used in business applications.

Integer Data Types

SQL Server offers a range of integer data types that are used for storing whole numbers, based upon the size of the storage location for each:

tinyint is stored in a single byte (that is, 8 bits) and can be used to store the values 0 to 255. Note that tinyint cannot store any negative values unlike the other integer data types.

smallint is stored in two bytes (that is, 16 bits) and stores values from

int is stored in four bytes (that is, 32 bits) and stores values from -2147483648 to 2147483647. It is a very commonly used data type. SQL Server uses the full word "integer" as a synonym for "int".

bigint is stored in eight bytes (that is, 64 bits) and stores very large integer values. While it is easy to refer to a 64-bit value, it is hard to comprehend how large these values are. 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, you would not reach the maximum value for many months.

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). A decimal(12,5) location can store up to 12 digits with up to 5 digits after the decimal point. 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.

numeric is a data type that is functionally equivalent to decimal.

money and smallmoney are SQL Server specific data types that have been present since the early days of the platform. They were used to store currency values with a fixed precision of four decimal places.

-32768 to 32767.

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. In general, use decimal for monetary values.

bit Data Type

bit is a data type that is stored in a single bit. The storage of the bit data type is optimized. If there are 8 or less bit columns in a table, they are stored in a single byte. bit values are commonly used to store the equivalent of Boolean values in higher-level languages.

Note that there is not literal string format for bits in SQL Server. The string values TRUE and FALSE can be converted to bit values, as can the integer values 1 and 0. TRUE is converted to 1 and FALSE is converted to 0.

Higher level programming languages differ about how they store true values in Boolean columns. Some languages store true values as 1; others store true values as -1. In 2's complement notation (which is the encoding used to store smallint, int, and bigint), a one bit value would range from -1 to 0.

To avoid any chance of mismatch, in general when working with bits in applications, 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, as this will provide more reliable code.

Another aspect that surprises new users is that bit, along with other data types, is also nullable. That means that a bit location can be in three states: NULL, 0, or 1.

Question: What would be a suitable data type for storing the value of a check box that can be 0 for unchecked, 1 for checked, or -1 for disabled?

2-8

Implementing a Microsoft® SQL Server® 2008 R2 Database

Working with IDENTITY

SQL Server® 2008 R2 Database Working with IDENTITY Key Points It is common to require a

Key Points

It is common to require a series of numbers to be automatically provided for an integer column. 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.

IDENTITY

IDENTITY is a property typically associated with integer or bigint columns that provide automated generation of values during insert operations. You may be familiar with auto-numbering systems or sequences in other database engines. While not identical to these, IDENTITY columns can be used to replace the functionality from those other database engines.

When specifying the IDENTITY property, you specify a seed and an increment. The seed is the starting value. The increment is how much the value goes up by each time. Both seed and increment default to a value of 1 if they are not specified.

Although explicit inserts are not normally allowed to columns with an IDENTITY property, it is possible to explicitly insert values. The ability to insert into an IDENTITY column can be enabled temporarily using a connection option. 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.

Having the IDENTITY property on a column does not in itself ensure that the column is unique. Unless there is also a unique constraint on the column, there is no guarantee that values in a column with the IDENTITY property will be unique.

Retrieving the Inserted Identity Value

After inserting a row into a table, it is common to need to know the value that was placed into the column with the IDENTITY property. The system variable @@IDENTITY returns the last identity value used within the session, in any scope. This can be a problem with triggers that perform inserts on another table with an IDENTITY column as part of an INSERT statement.

Working with Data Types

2-9

For example, if you insert a row into a customer table, the customer might be assigned a new identity value. However, if a trigger on the customer table caused an entry to be written into an audit logging table when inserts are performed, the @@IDENTITY variable would return the identity value from the logging table, rather than the one from the customer table.

To deal effectively with this, the SCOPE_IDENTITY() function was introduced. It provides the last identity value within the current scope only. In the previous example, it would return the identity value from the customer table.

Another complexity relates to multi-row inserts. These were introduced in SQL Server 2008. In this situation, you may want to retrieve the IDENTITY column value for more than one row at a time. Typically, this would be implemented by the use of the OUTPUT clause on the INSERT statement.

2-10

Implementing a Microsoft® SQL Server® 2008 R2 Database

Approximate Numeric Data Types

SQL Server® 2008 R2 Database Approximate Numeric Data Types Key Points SQL Server provides two approximate

Key Points

SQL Server provides two approximate numeric data types. They are used more commonly in scientific applications than in business applications. 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.

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.

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. Even though a range of values are provided for in the syntax, the current SQL Server implementation of the float data type is that if the scale value is from 1 to 24, then the scale is implemented as 24. For any larger value, a scale of 53 is used.

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. This causes rounding and processing errors. A "code smell" for picking new developers is to have columns of numbers that do not exactly add up to the displayed totals. It is common to have small rounding errors creep into calculations, that is, a total that is out by 1 cent in dollar or euro based currencies.

The inappropriate use of numeric data types can cause processing errors. Look at the following code and decide how many times the PRINT statement would be executed:

DECLARE @Counter float; SET @Counter = 0; WHILE (@Counter <> 1.0) BEGIN SET @Counter += 0.1; PRINT @Counter;

Working with Data Types

2-11

END;

It might surprise you that this query would never stop running and would need to be cancelled. After cancelling the query, if you look at the output you would see the following:

0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7

What has happened? The problem is that the value 0.1 cannot be stored exactly in a float or real data type.

Consider how you would write the answer to 1 / 3 in decimal. The answer isn't 0.3, it's 0.3333333 recurring. There is no way in decimal to write 1 / 3 as an exact decimal fraction. You have to eventually settle for an approximate value.

The same problem occurs in binary fractions; it just occurs at different values. 0.1 ends up being stored as the equivalent of 0.099999 recurring. 0.1 in decimal is a non-terminating fraction in binary. So, when you put the system in a loop adding 0.1 each time, the value never exactly equals 1.0, which does happen to be able to be stored precisely.

2-12

Implementing a Microsoft® SQL Server® 2008 R2 Database

Date and Time Data Types

SQL Server® 2008 R2 Database Date and Time Data Types Key Points SQL Server supports a

Key Points

SQL Server supports a rich set of data types for working with date- and time-related values. It is important to be very careful when working with string literal representations of these values and with their precision (or accuracy). SQL Server also provides a large number of functions for working with dates and times.

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. This format is the same as the ISO8601 definition for DATE. date has a range of values from 0001-01-01 to 9999-12-31 with an accuracy of one day.

The time data type is aligned to the SQL standard form of hh:mm:ss with optional decimal places up to hh:mm:ss.nnnnnnn. Note that you need to specify the number of decimal places when defining the data type such as time(4). The format that SQL Server uses is similar to the ISO 8601 definition for TIME.

The ISO 8601 standard also allow using 24:00:00 to represent midnight and a leap second over 59. These are not supported in the SQL Server implementation.

The datetime2 data type is a combination of a date data type and a time 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. A common error is to not allow for the 3ms accuracy of the data type. For example, with the datetime data type, executing the following code:

DECLARE @When datetime; SET @When = '20101231 23:59:59.999';

would cause the value '20110101 00:00:00.000' to actually be stored.

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

It is important to understand that this behaviour does not happen with the new date data type, 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.

Timezones

The datetimeoffset data type is a combination of a datetime2 data type and a timezone offset. Note that the data type is not timezone aware, it is simply capable of storing and retrieving timezone values.

Note that the timezone offset values extend for more than a full day (range of -14:00 to +14:00). A range of system functions has been provided for working with timezone values, as well as with all the date and time related data types.

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?

2-14

Implementing a Microsoft® SQL Server® 2008 R2 Database

Unique Identifiers

Microsoft® SQL Server® 2008 R2 Database Unique Identifiers Key Points Globally unique identifiers (GUIDs) have become

Key Points

Globally unique identifiers (GUIDs) have become common in application development. 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.

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. GUIDs were introduced to avoid the need for anyone to function as the "number allocator". 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, very high degree of probability.

This is achieved by using very, very large values. When discussing the bigint data type earlier, you learned that the 64-bit bigint values were really large. GUIDs are 128-bit values. The magnitude of a 128-bit value is well beyond our capabilities of comprehension.

uniqueidentifier Data Type

The uniqueidentifier data type in SQL Server is typically used to store globally unique identifiers. Standard arithmetic operators such as =, <> (or !=), <, >, <=, and >= are supported along with NULL and NOT NULL checks.

The IDENTITY property is not used with uniqueidentifier columns. New values are not calculated by code in your process. They are calculated by calling system functions that generate a value for you. In SQL Server, this function is the NEWID() function.

The random nature of GUIDs has also caused significant problems in current storage subsystems. SQL Server 2005 introduced the NEWSEQUENTIALID() function to attempt to get around the randomness of the values generated by NEWID(). However, the function does so at the expense of some guarantee of uniqueness.

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. If you need to request a value from the database via NEWSEQUENTIALID(), you usually would have been better to use an IDENTITY column instead.

A very common development error is to store GUIDs in string values rather than in uniqueidentifier columns.

in string values rather than in uniqueidentifier columns. Note: uniqueidentifier columns are also commonly used by

Note: uniqueidentifier columns are also commonly used by replication systems. Replication is an advanced topic beyond the scope of this course.

Question: The slide mentions that a common error is to store GUIDs as strings. What would be wrong with this?

2-16

Implementing a Microsoft® SQL Server® 2008 R2 Database

NULL or NOT NULL Columns

SQL Server® 2008 R2 Database NULL or NOT NULL Columns Key Points Nullability determines if a

Key Points

Nullability determines if a value must be present or not. Assigning inappropriate nullability of columns is another very common design error.

NULL

NULL is a state that a column is in, rather than a type of value that is stored in a column. You do not say that a value equals NULL; you say that a value is NULL. This is why in T-SQL, you do not check whether a value is NULL with the equality operator.

You do not write code that says:

WHERE Color = NULL;

Instead, you write code that says:

WHERE Color IS NULL;

Common Errors

New developers will often confuse NULL values with zero, blank (or space), zero-length strings, etc. This is exasperated by other database engines that treat NULL and zero-length strings or zeroes as identical. NULL indicates the absence of a value.

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. (Often this is referred to as whether or not a column is mandatory).

Look at the NULL and NOT NULL declarations on the slide and decide why each decision might have been made.

Working with Data Types

2-17

Question: When should a value be nullable?

2-18

Implementing a Microsoft® SQL Server® 2008 R2 Database

Demonstration 1A: Working with Numeric Data Types

Database Demonstration 1A: Working with Numeric Data Types Key Points In this demonstration you will see:

Key Points

In this demonstration you will see:

Work with IDENTITY values

Work with NULL

Insert GUIDs into a table

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_02_PRJ\6232B_02_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. Follow the instructions contained within the comments of the script file.

Working with Data Types

2-19

Lesson 2

Working with Character Data

with Data Types 2-19 Lesson 2 Working with Character Data In the last lesson, you saw

In the last lesson, you saw that the most basic types of data that get stored in database systems today are numbers, dates, and strings. There are a range of data types that can be used for each of these. You also looked at the available range of data types that can be used for numeric and date-related data. In this lesson, you will now look at the other very common category of data: the string-related data types.

Another common class of design and implementation errors relates to collations. Collations define how string data is sorted. In this lesson, you will also see how collations are defined and used.

Objectives

After completing this lesson, you will be able to:

Explain the role of Unicode encoding

Use character data types

Work with collations

2-20

Implementing a Microsoft® SQL Server® 2008 R2 Database

Understanding Unicode

SQL Server® 2008 R2 Database Understanding Unicode Key Points Traditionally, most computer systems stored one

Key Points

Traditionally, most computer systems stored one character per byte. This only allowed for 256 different character values, which is not enough to store characters from many languages.

Multi-byte Character Issues

Consider Asian languages such as Chinese or Japanese that need to store thousands of characters. 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. One option is to have an English-like version of the language that can be used for entry. Japanese does in fact have a language form called Romaji that uses English-like characters for representing words. Chinese has a form called pinyin that is also somewhat English-like.

If a Chinese writer enters a pinyin word like "ma" on a keyboard, the following list of options appears:

on a keyboard, the following list of options appears: They can then enter the number beside

They can then enter the number beside the character to select the intended word. It might not seem important to an English-speaking person but given that the first option means "horse", the second option is like a question mark, and the third option means "mother", there is definitely a need to select the correct option!

Character Groups

An alternate way to enter the characters is via radical groupings. Please note the third character in the screenshot above. The left-hand part of that character, , means "woman". Rather than entering English- like characters (that could be quite unfamiliar to the writers), select a group of characters based on what is known as a radical. If you select the woman radical, you see this list:

Working with Data Types

2-21

Working with Data Types 2-21 Please note that the character representing "mother" is the first character

Please note that the character representing "mother" is the first character on the second line. For this sort of keyboard entry to work, the characters must be in appropriate groups, not just stored as one large sea of characters. An additional complexity is that the radicals themselves are also in groups. You can see in the screenshot that the woman radical was part of the third group of radicals.

Unicode

In the 1980s, 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. The answer was three bytes. 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, 16 bit) computer systems.

Unicode introduced a two-byte character set that attempts to fit the values from the three bytes into two bytes. Inevitably then, trade-offs had to occur.

Unicode allows any combination of characters that are drawn from any combination of languages to exist in a single document. There are multiple encodings for Unicode with UTF-7, UTF-8, UTF-16, and UTF-32. (UTF is universal text format). SQL Server currently implements double-byte characters for its Unicode implementation.

For string literal values, an N prefix on a string allows the entry of double-byte characters into the string rather than just single-byte characters. (N stands for "National" in "National Character Set").

When working with character strings, the LEN function returns the number of characters (Unicode or not) whereas DATALENGTH returns the number of bytes.

Question: Do you recognize either of the phrases on the slide?

2-22

Implementing a Microsoft® SQL Server® 2008 R2 Database

Character Data Types

SQL Server® 2008 R2 Database Character Data Types Key Points SQL Server provides a range of

Key Points

SQL Server provides a range of string data types for storing characters. They differ by length and by character encoding.

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. It is important to realize that if you specify char(50) then 50 characters will be stored and retrieved. char is for single-byte character sets and nchar is designed for double-byte Unicode characters. When retrieving values from char and nchar data, it is common to need to trim the trailing characters. By default, these characters will be spaces (or blanks). Look at the following code:

DECLARE @String1 char(10); DECLARE @String2 char(10); SET @String1 = 'Hello'; SET @String2 = 'There'; SELECT @String1 + @String2;

When executed, it returns:

"Hello

There

"

Note the trailing spaces. 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, for example, state codes in the U.S.A.

varchar and nvarchar Data Types

The varchar and nvarchar data types are the "varying" equivalents of the char and nchar data types. They are used for strings where a maximum length is specified but where the length varies. Rather than allocating a location of a fixed size and allocating the whole location regardless of the length of the string, these data types incur the overhead of storing the length of the string separately to the string itself. This is

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.

The varchar and nvarchar data types are limited to 8000 and 4000 characters, respectively. This is roughly what fits in a data page in a SQL Server database.

varchar(max) and nvarchar(max) Data Types

It has become common to store even longer string values. The varchar(max) and nvarchar(max) data types are used for this. They each allow up to around 2GB of data to be stored.

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.

sysname Data Type

You will often see object names in SQL Server referred to as being of sysname data type. sysname is an alias data type that is currently mapped to nvarchar(128).

Question: Why would you use the sysname data type rather than the nvarchar(128) data type?

2-24

Implementing a Microsoft® SQL Server® 2008 R2 Database

Understanding Collations

SQL Server® 2008 R2 Database Understanding Collations Key Points Collations in SQL Server are used to

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.

Code Pages

It was mentioned earlier that computer systems traditionally stored one byte per character. This allowed

for 256 possible values, with a range from 0 to 255. The values from 0 to 31 were reserved for "control characters" such as backspace (character 8) and tab (character 9). Character 32 was allocated for a space and so on, up to the Delete character which was assigned the value 127.

For values above 127 though, standards were initially not very clear. It was common to store characters such as line drawing characters or European characters with accents or graves in these codes.

In fact, a number of computer systems only used 7 bits to store characters instead of 8 bits. (As an

example, the DEC10 system from Digital Equipment Corporation stored 5 characters of 7 bits each per 36-

bit computer "word". It used the final bit as a parity check bit).

Problems did arise when different vendors used the upper characters for different purposes. In the 1970's,

it was not uncommon to type a character on your screen and see a different character when that

document was printed, as the screen and the printer were using different characters in the values above

127.

A number of standard character sets that described what should be in the upper code values did appear.

The MSDOS operating system categorized these as "code pages". What a code page really defines is which characters are used for the values from 128 to 255.

Both the operating systems and SQL Server support a range of code pages.

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. For example, is the value "mcdonald" equal to the value "McDonald"? Does the letter "á" (that is, with an accent) equal the letter "a" (without an accent)? If they are not equal, 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. There are two types of collations: SQL Server collations and Windows collations. SQL Server collations are retained for backward compatibility but you are encouraged to make use of Windows collations instead.

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. For curious historic reasons, CP1 specifies code page 1252 but for all others the number indicates the code page, for example, CP850 specifies code page 850.

ComparisonStyle

Either BIN for binary or a combination of case and accent sensitivity. CI is case- insensitive, CS is case-sensitive. AI is accent-insensitive, AS is accent-sensitive.

As an example, the collation SQL_Latin1_General_Pref_CP850_CI_AS indicates that it is a SQL collation, Latin1_General is the alphabet being used, there is a preference for upper-case, the code page is 850, and sorting is performed case-insensitive and accent-sensitive.

Windows collations have similar naming but with less fields. For example, Windows collation Latin1_General_CI_AS refers to Latin1_General as the alphabet being used, case-insensitive and accent- sensitive.

Collation Issues

The main issues with collations occur when you try to compare values that are stored with different collations. It is possible to set default collations for servers, databases, and even columns.

When comparing values from different collations, you need to then specify which collation (which could yet another collation) will be used for the comparison.

Another use of this is as shown in the example in the slide. In this case, you are forcing the query to perform a case-sensitive comparison between the string '%ball%' and the value in the column. If the column contained 'Ball', it would not then match.

Question: What are the code page and sensitivity values for the collation QL_Scandinavian_Cp850_CI_AS?

2-26

Implementing a Microsoft® SQL Server® 2008 R2 Database

Demonstration 2A: Working with Character Data

R2 Database Demonstration 2A: Working with Character Data Key Points In this demonstration you will see

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. 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_02_PRJ\6232B_02_PRJ.ssmssln and click Open.

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

2. Open the 21 – Demonstration 2A.sql script file.

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

Working with Data Types

2-27

Lesson 3

Converting Data Types

Working with Data Types 2-27 Lesson 3 Converting Data Types Now that you have learned about

Now that you have learned about the most common data types, you need to consider that data is not always already in an appropriate data type. For example, you may have received data from another system and you may need to convert the data from one data type to another. You can control how this is done or you can try to let SQL Server do the conversions implicitly. There are a number of issues that can arise when making conversions between data types. You will learn about these issues in this lesson.

Objectives