Introduction to ArtificiaI Intelligence in Higher Education
6232 a implementing a microsoft sql server 2008 database
1. OFFICIAL MICROSOFT LEARNING PRODUCT
6232A
Implementing a Microsoft®
SQL Server® 2008 Database
Be sure to access the extended learning content on your
Course Companion CD enclosed on the back cover of the book.
3. MICROSOFT LICENSE TERMS
OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER
EDITION – Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They
apply to the Licensed Content named above, which includes the media on which you received it, if any. The
terms also apply to any Microsoft
• updates,
• supplements,
• Internet-based services, and
• support services
for this Licensed Content, unless other terms accompany those items. If so, those terms apply.
By using the Licensed Content, you accept these terms. If you do not accept them, do not use
the Licensed Content.
If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. “Academic Materials” means the printed or electronic documentation such as manuals,
workbooks, white papers, press releases, datasheets, and FAQs which may be included in the
Licensed Content.
b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions
location, an IT Academy location, or such other entity as Microsoft may designate from time to time.
c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and
conducted at or through Authorized Learning Centers by a Trainer providing training to Students
solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or
“MOC”) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions
Courseware). Each Authorized Training Session will provide training on the subject matter of one
(1) Course.
d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning
Center during an Authorized Training Session, each of which provides training on a particular
Microsoft technology subject matter.
e. “Device(s)” means a single computer, device, workstation, terminal, or other digital electronic or
analog device.
f. “Licensed Content” means the materials accompanying these license terms. The Licensed
Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student
Content, (iii) classroom setup guide, and (iv) Software. There are different and separate
components of the Licensed Content for each Course.
g. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that
may be included with the Licensed Content.
h. “Student(s)” means a student duly enrolled for an Authorized Training Session at your location.
4. i. “Student Content” means the learning materials accompanying these license terms that are for
use by Students and Trainers during an Authorized Training Session. Student Content may include
labs, simulations, and courseware files for a Course.
j. “Trainer(s)” means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer
and b) such other individual as authorized in writing by Microsoft and has been engaged by an
Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its
behalf.
k. “Trainer Content” means the materials accompanying these license terms that are for use by
Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content
may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and
demonstration guides and script files for a Course.
l. “Virtual Hard Disks” means Microsoft Software that is comprised of virtualized hard disks (such as
a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single
computer or other device in order to allow end-users to run multiple operating systems concurrently.
For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”.
m. “Virtual Machine” means a virtualized computing experience, created and accessed using
Microsoft® Virtual PC or Microsoft® Virtual Server software that consists of a virtualized hardware
environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the
virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard
Disks will be considered “Trainer Content”.
n. “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
license terms.
2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and
electronic), Trainer Content, Student Content, classroom setup guide, and associated media.
License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center
location or per Trainer basis.
3. INSTALLATION AND USE RIGHTS.
a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may:
i. either install individual copies of the relevant Licensed Content on classroom Devices only for
use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided
that the number of copies in use does not exceed the number of Students enrolled in and the
Trainer delivering the Authorized Training Session, OR
ii. install one copy of the relevant Licensed Content on a network server only for access by
classroom Devices and only for use by Students enrolled in and the Trainer delivering the
Authorized Training Session, provided that the number of Devices accessing the Licensed
Content on such server does not exceed the number of Students enrolled in and the Trainer
delivering the Authorized Training Session.
iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to
use the Licensed Content that you install in accordance with (ii) or (ii) above during such
Authorized Training Session in accordance with these license terms.
5. i. Separation of Components. The components of the Licensed Content are licensed as a single
unit. You may not separate the components and install them on different Devices.
ii. Third Party Programs. The Licensed Content may contain third party programs. These license
terms will apply to the use of those third party programs, unless other terms accompany those
programs.
b. Trainers:
i. Trainers may Use the Licensed Content that you install or that is installed by an Authorized
Learning Center on a classroom Device to deliver an Authorized Training Session.
ii. Trainers may also Use a copy of the Licensed Content as follows:
A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for
your own personal training Use and for preparation of an Authorized Training Session.
B. Portable Device. You may install another copy on a portable device solely for your own
personal training Use and for preparation of an Authorized Training Session.
4. PRE-RELEASE VERSIONS. If this is a pre-release (“beta”) version, in addition to the other provisions
in this agreement, these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not
contain the same information and/or work the way a final version of the Licensed Content will. We
may change it for the final, commercial version. We also may not release a commercial version.
You will clearly and conspicuously inform any Students who participate in each Authorized Training
Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with
any further content, including but not limited to the final released version of the Licensed Content
for the Course.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to
Microsoft, without charge, the right to use, share and commercialize your feedback in any way and
for any purpose. You also give to third parties, without charge, any patent rights needed for their
products, technologies and services to use or interface with any specific parts of a Microsoft
software, Licensed Content, or service that includes the feedback. You will not give feedback that is
subject to a license that requires Microsoft to license its software or documentation to third parties
because we include your feedback in them. These rights survive this agreement.
c. Confidential Information. The Licensed Content, including any viewer, user interface, features
and documentation that may be included with the Licensed Content, is confidential and proprietary
to Microsoft and its suppliers.
i. Use. For five years after installation of the Licensed Content or its commercial release,
whichever is first, you may not disclose confidential information to third parties. You may
disclose confidential information only to your employees and consultants who need to know
the information. You must have written agreements with them that protect the confidential
information at least as much as this agreement.
ii. Survival. Your duty to protect confidential information survives this agreement.
iii. Exclusions. You may disclose confidential information in response to a judicial or
governmental order. You must first give written notice to Microsoft to allow it to seek a
6. protective order 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:
7. 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.
9. • transfer the Licensed Content, in whole or in part, to a third party;
• access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not
been authorized by Microsoft to access and use;
• rent, lease or lend the Licensed Content; or
• use the Licensed Content for commercial hosting services or general business purposes.
• Rights to access the server software that may be included with the Licensed Content, including the
Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft
intellectual property in software or devices that may access the server.
8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and
regulations. You must comply with all domestic and international export laws and regulations that apply
to the Licensed Content. These laws include restrictions on destinations, end users and end use. For
additional information, see www.microsoft.com/exporting.
9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed
Content marked as “NFR” or “Not for Resale.”
10. ACADEMIC EDITION. You must be a “Qualified Educational User” to use Licensed Content marked as
“Academic Edition” or “AE.” If you do not know whether you are a Qualified Educational User, visit
www.microsoft.com/education or contact the Microsoft affiliate serving your country.
11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you
fail to comply with the terms and conditions of these license terms. In the event your status as an
Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is
terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this
agreement, you must destroy all copies of the Licensed Content and all of its component parts.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-
based services and support services that you use, are the entire agreement for the Licensed
Content and support services.
13. APPLICABLE LAW.
a. United States. If you acquired the Licensed Content in the United States, Washington state law
governs the interpretation of this agreement and applies to claims for breach of it, regardless of
conflict of laws principles. The laws of the state where you live govern all other claims, including
claims under state consumer protection laws, unfair competition laws, and in tort.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws
of that country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the
laws of your country. You may also have rights with respect to the party from whom you acquired the
Licensed Content. This agreement does not change your rights under the laws of your country if the
laws of your country do not permit it to do so.
15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed “as-is.” You bear the risk of
using it. Microsoft gives no express warranties, guarantees or conditions. You may have
additional consumer rights under your local laws which this agreement cannot change. To
the extent permitted under your local laws, Microsoft excludes the implied warranties of
merchantability, fitness for a particular purpose and non-infringement.
10. 16. LIMITATION 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.
11. Implementing a Microsoft SQL Server 2008 Database xi
Acknowledgement
Microsoft Learning would like to acknowledge and thank the following for their
contribution towards developing this title. Their effort at various stages in the
development has ensured that you have a good classroom experience.
Peter Lammers – Lead Developer
Peter Lammers joined Aeshen in 2002 as a Product Analyst, and he has been a
Lead Product Analyst since 2005, working on Microsoft TechNet Content,
Webcasts, White Papers, and Microsoft Learning Courses. Prior to that he has been
a computer programmer and network technician with a 14-year background in
troubleshooting, training, modifying and supporting a software application;
network administration, troubleshooting, and server, desktop, and firewall
support.
Sean Masters – Content Developer
Mr. Masters joined Aeshen in 2007. He has worked in SMB technical operations for
nearly 10 years including 4 years as manager of information technology at a
property management firm and 4 years as a private consultant to various legal and
financial firms in the New England area.
Sunni Brock – Content Developer
Sunni has been working with Aeshen as a content developer since 2006. In her 20-
year career, she spent 15 years at Microsoft as a Lead Program Manager in the
Windows Product Group and as a Technical Support lead replicating customer
configuration scenarios. Prior to joining Aeshen, she served as a Technical Account
Manager for Sonic Solutions/Roxio acting as liaison to Adobe, Microsoft, Sony, and
other technology leaders.
Seth Wolf – Content Developer
Seth Wolf has been working with computing technology for over 20 years. His
background includes programming, database design, Web site design, network
management, hardware troubleshooting, and user support. He remembers the
good old days of dBase and Btrieve.
Jerry Knowles – Content Developer
Mr. Knowles joined Aeshen in 2008 as an Application Analyst. He has worked in
Information Technology since 1989 as an instructor, application developer, SQL
database administrator, and consultant.
12. xii Implementing a Microsoft SQL Server 2008 Database
Karl Middlebrooks - Subject Matter Expert
Mr. Middlebrooks is a Product Analyst with Aeshen, and joined in 2004. He has
over 20 years experience in IT and Operations management, network
administration, and database administration.
Geoff Black – Technical Reviewer
Geoff is the Principal MCT for IT Training Solutions in Brisbane, Australia. He
holds a degree in Computational Physics with Distinction and multiple Developer
and Infrastructure certifications. With more than 20 years experience in
Information Technology, he has become a demonstrated leader in the field
through pioneering many new and innovative technologies.
13. Implementing a Microsoft SQL Server 2008 Database xiii
Contents
Module 1: Creating Databases and Database Files
Lesson 1: Creating Databases 1-3
Lesson 2: Creating Filegroups 1-11
Lesson 3: Creating Schemas 1-15
Lesson 4: Creating Database Snapshots 1-19
Lab: Creating Databases and Database Files 1-25
Module 2: Creating Data Types and Tables
Lesson 1: Creating Data Types 2-3
Lesson 2: Creating Tables 2-8
Lesson 3: Creating Partitioned Tables 2-17
Lab: Creating Data Types and Tables 2-23
Module 3: Creating and Tuning Indexes
Lesson 1: Planning Indexes 3-3
Lesson 2: Creating Indexes 3-8
Lesson 3: Optimizing Indexes 3-21
Lab: Creating and Optimizing Indexes 3-29
Module 4: Implementing Data Integrity by Using Constraints and Triggers
Lesson 1: Data Integrity Overview 4-3
Lesson 2: Implementing Constraints 4-7
Lesson 3: Implementing Triggers 4-14
Lab: Implementing Data Integrity by Using Constraints and Triggers 4-27
14. xiv Implementing a Microsoft SQL Server 2008 Database
Module 5: Using XML
Lesson 1: Using the XML Data Type 5-3
Lesson 2: Retrieving XML by Using FOR XML 5-12
Lesson 3: Shredding XML by Using OPENXML 5-21
Lab 5A: Using XML 5-27
Lesson 4: Introducing XQuery 5-37
Lesson 5: Creating XML Indexes 5-43
Lesson 6: Implementing XML Schemas 5-48
Lab 5B: Using XML 5-54
Module 6: Implementing Views
Lesson 1: Introduction to Views 6-3
Lesson 2: Creating and Managing Views 6-9
Lesson 3: Optimizing Performance by Using Views 6-19
Lab: Implementing Views 6-24
Module 7: Implementing Stored Procedures
Lesson 1: Using Stored Procedures 7-3
Lesson 2: Creating Parameterized Stored Procedures 7-12
Lesson 3: Working with Execution Plans 7-17
Lesson 4: Handling Exceptions 7-24
Lab: Implementing Stored Procedures 7-28
Module 8: Implementing Functions
Lesson 1: Introducing Functions 8-3
Lesson 2: Working with Functions 8-9
Lesson 3: Controlling Execution Context 8-13
Lab: Implementing Functions 8-17
15. Implementing a Microsoft SQL Server 2008 Database xv
Module 9: Implementing Managed Code in a Database
Lesson 1: Introduction to the SQL Server® Common Language Runtime 9-4
Lesson 2: Importing and Configuring Assemblies 9-10
Lesson 3: Creating Managed Database Objects 9-15
Lab: Implementing Managed Code in a Database 9-20
Module 10: Managing Transactions and Locks
Lesson 1: Overview of Transactions and Locks 10-3
Lesson 2: Managing Transactions 10-11
Lesson 3: Understanding SQL Server Locking Architecture 10-25
Lesson 4: Managing Locks 10-34
Lab: Managing Transactions and Locks 10-49
Module 11: Using Service Broker
Lesson 1: Service Broker Overview 11-3
Lesson 2: Creating Service Broker Objects 11-14
Lesson 3: Sending and Receiving Messages 11-22
Lab: Using Service Broker 11-27
Lab Answer Keys
16.
17. About This Course xvii
MCT USE ONLY. STUDENT USE PROHIBITED
About This Course
This section provides you with a brief description of the course, audience,
suggested prerequisites, and course objectives.
Course Description
This five-day instructor-led course provides students with the knowledge and skills
to implement a Microsoft SQL Server 2008 database. The course focuses on
teaching individuals how to use SQL Server 2008 product features and tools
related to implementing a database.
Audience
The primary audience for this course is IT Professionals who want to become
skilled on SQL Server 2008 product features and technologies for implementing a
database.
The secondary audiences for this course are individuals who are developers from
other product platforms or previous versions of SQL Server looking to become
skilled in the implementation of a SQL Server 2008 database.
Student Prerequisites
This course requires that you meet the following prerequisites:
• Working knowledge of Transact-SQL.
• Working knowledge of Relational databases.
• Core Windows Server skills.
• Database design skills.
• Basic knowledge of XML and XML schemas.
• SQL Server skills – ability to write Transact-SQL queries or completed Course
2778: Writing Queries Using Microsoft SQL Server 2008 Transact-SQL.
18. xviii About This Course
MCT USE ONLY. STUDENT USE PROHIBITED
Course Objectives
After completing this course, students will be able to:
• Create databases and database files.
• Create data types and tables.
• Plan, create, and optimize indexes.
• Implement data integrity in Microsoft SQL Server 2008 databases by using
constraints.
• Implement data integrity in Microsoft SQL Server 2008 by using triggers.
• Use XML-related features in Microsoft SQL Server 2008.
• Implement views.
• Implement stored procedures.
• Implement functions.
• Implement managed code in the database.
• Manage transactions and locks.
• Use Service Broker to build a messaging-based solution.
19. About This Course xix
MCT USE ONLY. STUDENT USE PROHIBITED
Course Outline
This section provides an outline of the course:
Module 1: Creating Databases and Database Files
This module introduces one of the most fundamental tasks that a database
developer must perform, the creation of a database and its major components,
such as creating databases, setting database options, creating filegroups, schemas,
and database snapshots.
Module 2: Creating Data Types and Tables
This module introduces the system-supplied data types in SQL Server 2008. The
students will learn how to define custom Transact-SQL data types and also
describes how to create tables and how to use partitioned tables to organize data
into multiple partitions.
Module 3: Creating and Tuning Indexes
This module describes how to plan, create, and optimize indexes to attain optimal
performance benefits.
Module 4: Implementing Data Integrity by Using Constraints and Triggers
This module explains implementing data integrity in SQL Server 2008 by using
constraints. They will also implement data integrity by using triggers.
Module 5: Using XML
This module describes how to work with XML, including use of the FOR XML
clause, the OPENXML function, XQuery expressions, and the xml native data type.
The students will learn the considerations you must take into account when
creating XML indexes and the syntax used to create the XML indexes. They will
also learn what XML schemas and XML schema collections are as well how to use
them to implement typed XML data.
Module 6: Implementing Views
This module explains the different types of views available in Microsoft SQL Server
2008 which provide a convenient way to access data through a predefined query.
Module 7: Implementing Stored Procedures
This module describes the design and implementation of stored procedures to
enforce business rules or data consistency, or to modify and maintain existing
stored procedures written by other developers.
20. xx About This Course
MCT USE ONLY. STUDENT USE PROHIBITED
Module 8: Implementing Functions
This module discusses the design and implementation of user-defined functions
that enforce business rules or data consistency, or to modify and maintain existing
functions written by other developers.
Module 9: Implementing Managed Code in the Database
This module describes how to use managed code to implement database objects,
such as stored procedures, user-defined data types, user-defined functions, and
triggers.
Module 10: Managing Transactions and Locks
This module describes how to use transactions and SQL Server locking
mechanisms to meet the performance and data integrity requirements of their
applications.
Module 11: Using Service Broker
In this module you will learn more about Service Broker, how to create Service
Broker objects, and how to use Service Broker to send and receive messages.
21. About This Course xxi
MCT USE ONLY. STUDENT USE PROHIBITED
Course Materials
The following materials are included with your kit:
• Course Handbook. A succinct classroom learning guide that provides all the
critical technical information in a crisp, tightly-focused format, which is just
right for an effective in-class learning experience.
• Lessons: Guide you through the learning objectives and provide the key points
that are critical to the success of the in-class learning experience.
• Labs: Provide a real-world, hands-on platform for you to apply the knowledge
and skills learned in the module.
• Module Reviews and Takeaways: Provide improved on-the-job reference
material to boost knowledge and skills retention.
• Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips
when it’s needed.
• Course Companion CD. Searchable, easy-to-navigate digital content with
integrated premium on-line resources designed to supplement the Course
Handbook.
• Lessons: Include detailed information for each topic, expanding on the
content in the Course Handbook.
• Labs: Include complete lab exercise information and answer keys in digital
form to use during lab time.
• Resources: Include well-categorized additional resources that give you
immediate access to the most up-to-date premium content on TechNet,
MSDN®, Microsoft Press®
• Student Course Files: Include the Allfiles.exe, a self-extracting executable file
that contains all the files required for the labs and demonstrations.
Note: To access the full course content, insert the Course Companion CD into the CD-
ROM drive, and then in the root directory of the CD, double-click StartCD.exe.
• Course evaluation. At the end of the course, you will have the opportunity to
complete an online evaluation to provide feedback on the course, training
facility, and instructor.
22. xxii About This Course
MCT USE ONLY. STUDENT USE PROHIBITED
To provide additional comments or feedback on the course, send e-mail to
support@mscourseware.com. To inquire about the Microsoft Certification
Program, send e-mail to mcphelp@microsoft.com.
Virtual Machine Environment
This section provides the information for setting up the classroom environment to
support the business scenario of the course.
Virtual Machine Configuration
In this course, you will use Microsoft Virtual Server 2005 R2 with SP1 to perform
the labs.
Important: At the end of each lab, you must close the virtual machine and must not
save any changes. To close a virtual machine without saving the changes, perform
the following steps: 1. On the virtual machine, on the Action menu, click Close. 2. In
the Close dialog box, in the What do you want the virtual machine to do? list, click
Turn off and delete changes, and then click OK.
The following table shows the role of each virtual machine used in this course:
Virtual machine Role
6232A-NY-SQL-01 SQL Server for Adventure Works
Software Configuration
The following software is installed on each VM:
• Windows Server 2008 Enterprise Edition
• SQL Server 2008
Course Files
There are files associated with the labs in this course. The lab files are located in
the folder E:Labfiles on the student computers.
23. About This Course xxiii
MCT USE ONLY. STUDENT USE PROHIBITED
Classroom Setup
Each classroom computer will have the same virtual machine configured in the
same way.
Course Hardware Level
To ensure a satisfactory student experience, Microsoft Learning requires a
minimum equipment configuration for trainer and student computers in all
Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which
Official Microsoft Learning Product courseware are taught.
This course requires that you have a computer that meets or exceeds hardware
level 5.5, which specifies a 2.4–gigahertz (GHz) (minimum) Pentium 4 or
equivalent CPU, at least 2 gigabytes (GB) of RAM, 16 megabytes (MB) of video
RAM, and two 7200 RPM 40-GB hard disks.
25. Implementing a Microsoft SQL Server 2008 Database 1-1
MCT USE ONLY. STUDENT USE PROHIBITED
Module 1
Creating Databases and Database Files
Contents:
Lesson 1: Creating Databases 1-3
Lesson 2: Creating Filegroups 1-11
Lesson 3: Creating Schemas 1-15
Lesson 4: Creating Database Snapshots 1-19
Lab: Creating Databases and Database Files 1-25
26. 1-2 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Module Overview
Databases in Microsoft® SQL Server® 2008 are made up of a collection of tables
that store a specific set of structured data. Every SQL Server database has a primary
filegroup that contains the primary data file and any secondary files. Inside every
database is a schema, or a container that holds tables, views, and procedures. A
database snapshot is a read-only, static view of a database used for reporting and
recovery.
In this module you will learn how to create databases, filegroups, schemas, and
database snapshots using SQL Server Management Studio.
27. Implementing a Microsoft SQL Server 2008 Database 1-3
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 1
Creating Databases
A database in SQL Server is made up of a collection of tables that stores a specific
set of structured data. A table contains a collection of rows, also referred to as
records or tuples, and columns, also referred to as attributes. It is important to
consider the database type, table structure, and collation type when designing a
database. In addition, every SQL Server 2008 database has a transaction log that
records all transactions and the database modifications made by each transaction.
The transaction log is a critical component of the database and, if there is a system
failure, the transaction log might be required to bring your database back to a
consistent state. Several database-level options that determine the characteristics of
the database can be set for each database. These options are unique to each
database and do not affect other databases. In this lesson you will learn several
considerations for creating a database. You will also learn about transaction
logging, database options, and data compression.
28. 1-4 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Considerations for Creating a Database
Key Points
Before creating a database, there are several things that must be taken into
consideration.
• Online Transaction Processing (OLTP) relational databases typically have
several users performing transactions at the same time and changing real-time
data, so you must determine the likely access patterns of the data and plan to
combine frequently accessed data together.
• Online Analytical Processing (OLAP) databases require you to take into
account the cubes, measures and measure groups, dimensions, attributes, and
hierarchies, as well as the perspectives and translations required by your
organization.
29. Implementing a Microsoft SQL Server 2008 Database 1-5
MCT USE ONLY. STUDENT USE PROHIBITED
• Collation settings, which include character set, sort order, and other locale-
specific settings, are fundamental to the structure and function of Microsoft
SQL Server databases. When you select a collation for your server or database
you are assigning certain characteristics to your data that will affect the results
of many operations in your database.
• When you design a database, you must first decide the tables that it needs, the
type of data that goes in each table, and the users that can access each table.
Question: What table characteristics should you take into account before creating
an OLTP database and its objects?
30. 1-6 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Transaction Logging
Key Points
Every SQL Server 2008 database has a transaction log that records all transactions
and the database modifications made by each transaction. Note that the transaction
log is a critical component of the database and, if there is a system failure, the
transaction log might be required to bring your database back to a consistent state.
Therefore it is vital to know at least what the transaction log is and how it operates
before you create a database.
• If an application issues a ROLLBACK statement, or if the Database Engine
detects an error such as the loss of communication with a client, transaction
log records are used to roll back the modifications made by an incomplete
transaction.
31. Implementing a Microsoft SQL Server 2008 Database 1-7
MCT USE ONLY. STUDENT USE PROHIBITED
• When an instance of SQL Server is started, it runs a recovery of each database.
Every modification recorded in the log which may not have been written to the
data files is rolled forward. Every incomplete transaction found in the
transaction log is then rolled back to make sure the integrity of the database is
preserved.
• The Log Reader Agent monitors the transaction log of each database
configured for transactional replication and copies the transactions marked for
replication from the transaction log into the distribution database.
• The standby-server solutions, database mirroring, and log shipping, rely
heavily on the transaction log.
• The Transaction Log supports the following operations.
• Recovery of individual transactions.
• Recovery of all incomplete transactions when SQL Server is started.
• Rolling a restored database, file, filegroup, or page forward to the point of
failure.
• Transactional replication.
• Standby-server solutions.
• The characteristics of the Transaction Log are:
• A log cache that is managed separately from the buffer cache for data
pages.
• The format of log records and pages is not constrained to follow the
format of data pages.
• Transaction logs can expand across multiple files.
Question: How can you roll a restored database, file, filegroup, or page forward to
the point of failure?
32. 1-8 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Database Options
Key Points
Several database-level options that determine the characteristics of the database
can be set for each database. These options are unique to each database and do not
affect other databases.
• After you set a database option, a checkpoint is automatically issued that
causes the modification to take effect immediately.
• Many database options can be changed using ALTER DATABASE (T-SQL) or
through the database properties window in SQL Server Management Studio.
Question: How are server-wide settings set in SQL Server?
33. Implementing a Microsoft SQL Server 2008 Database 1-9
MCT USE ONLY. STUDENT USE PROHIBITED
Data Compression
Key Points
The new data compression feature in SQL Server 2008 reduces the size of tables,
indexes or a subset of their partitions by storing fixed-length data types in variable
length storage format and by reducing the redundant data.
• ROW compression enables storing fixed length types in variable length storage
format. Since column values are stored as variable length, an additional 4-bit
length code is stored for each field within the row.
• PAGE compression minimizes storage of redundant data on the page by
storing commonly occurring byte patterns on the page once and then
referencing these values for respective columns.
• The relative CPU overhead with ROW is less than for PAGE, but PAGE
compression can provide better compression.
34. 1-10 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating Databases
Question: What various options are available when creating a database?
Question: How can you generate scripts in SQL Server Management Studio?
35. Implementing a Microsoft SQL Server 2008 Database 1-11
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 2
Creating Filegroups
Every database has a primary filegroup. This filegroup contains the primary data
file and any secondary files that are not put into other filegroups. User-defined
filegroups can be created to group data files together for administrative, data
allocation, and placement purposes. In this lesson you will learn what filegroups
are and what information you need to know about when to create filegroups.
36. 1-12 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
What Are Filegroups?
Key Points
Filegroups are named collections of files and are used to simplify data placement
and administrative tasks such as backup and restore operations.
• Using files and filegroups can improve performance.
• The primary filegroup contains the primary data file and any secondary files
that are not put into other filegroups, and the system tables of the user
database.
• A user-defined filegroup is any filegroup that is specifically created by the user
when the user first creates or later modifies the database.
• When objects are created in the database without specifying which filegroup
they belong to, they are assigned to the default filegroup.
37. Implementing a Microsoft SQL Server 2008 Database 1-13
MCT USE ONLY. STUDENT USE PROHIBITED
Improving Database Performance by Using Filegroups
Key Points
Using files and filegroups can improve database performance by letting a database
span multiple disks, multiple disk controllers, or RAID (redundant array of
independent disks) systems.
• For tables that must not be modified, such as historical data, put them on
filegroups and then mark the filegroup as read-only. This prevents accidental
updates.
• SQL Server backup and restore operations support compressed filegroups. No
modifications to the backup and restore implementation are required.
• Databases made up of multiple filegroups can be restored in stages by a
process known as piecemeal restore, which can be performed either online or
offline. Piecemeal restore works with all recovery models, but is more flexible
for the full and bulk-logged models than for the simple model.
38. 1-14 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating Filegroups
Question: What is the file and filegroup fill strategy used by the SQL Server
Database Engine?
Question: How can using filegroups improve database performance?
39. Implementing a Microsoft SQL Server 2008 Database 1-15
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 3
Creating Schemas
A database schema is a distinct namespace that is separate from a database user.
Think of a schema as a container of objects. In this lesson you will learn about
schemas and how object name resolution works in SQL Server 2008.
40. 1-16 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
What Are Schemas?
Key Points
A schema is a container that holds tables, views, procedures, and so on. It is inside
a database, which is inside a server.
• These entities fit together like nested boxes. The server is the outermost box,
and the schema is the innermost box.
• Schemas can be created and altered in a database, and users can be granted
access to a schema. A schema can be owned by any user, and schema
ownership is transferable.
Question: How are schemas in SQL Server 2008 different from those in SQL
Server 2005 and SQL Server 2000?
41. Implementing a Microsoft SQL Server 2008 Database 1-17
MCT USE ONLY. STUDENT USE PROHIBITED
How Object Name Resolution Works
Key Points
In order to resolve the names of securables that are not fully qualified names, SQL
Server uses name resolution to check the schema owned by the calling database
user and the schema owned by dbo.
• The default schema can be set and changed by using the DEFAULT_SCHEMA
option of CREATE USER or ALTER USER. If DEFAULT_SCHEMA is left
undefined, the database user will have dbo as its default schema.
• It is always good practice to be explicit with names and fully qualify object
names with the schema such as schema.object. This is particularly important
when creating or altering objects in SQL Server 2008.
42. 1-18 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating a Schema
Question: Where are objects created by a CREATE SCHEMA statement created?
43. Implementing a Microsoft SQL Server 2008 Database 1-19
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 4
Creating Database Snapshots
A database snapshot provides a read-only, static view of a source database as it
existed at snapshot creation, minus any uncommitted transactions. Snapshots can
be used for reporting purposes. In this lesson you will learn how database
snapshots work and you will learn about when to use database snapshots.
44. 1-20 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
How Database Snapshots Work
Key Points
A database snapshot provides a read-only, static view of a source database as it
existed at snapshot creation, minus any uncommitted transactions.
• Database Snapshots:
• Are dependent on the source database.
• Operate at the data-page level.
• Use one or more sparse files to store data.
• Database snapshots are dependent on the source database. The snapshots of a
database must be on the same server instance as the database.
45. Implementing a Microsoft SQL Server 2008 Database 1-21
MCT USE ONLY. STUDENT USE PROHIBITED
• In the event of a user error on a source database, you can revert the source
database to the state it was in when the snapshot was created. Data loss is
confined to updates to the database since the snapshot's creation.
• As data is written to a sparse file, NTFS allocates disk space gradually. If a
database snapshot runs out of space, it is marked as suspect, and it must be
dropped, however, the source database is not affected.
Question: How can you find out the actual size of a sparse file?
46. 1-22 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
When to Use Database Snapshots
Key Points
Clients can query a database snapshot, which makes it useful for writing reports
based on the data at the time of snapshot creation. Also, if the source database later
becomes damaged, you can revert the source database to the state it was in when
the snapshot was created.
• Because a database snapshot provides a static view of a database, a snapshot
can extend access to data from a particular point in time.
• Using database snapshots with database mirroring permits you to make the
data on the mirror server accessible for reporting.
• Before doing major updates, such as a bulk update, create a database snapshot
on the database protects data. If you make a mistake, you can use the snapshot
to recover by reverting the database to the snapshot.
47. Implementing a Microsoft SQL Server 2008 Database 1-23
MCT USE ONLY. STUDENT USE PROHIBITED
• By creating database snapshots on a regular basis, you can mitigate the impact
of a major user error, such as a dropped table.
• In a testing environment, it can be useful when repeatedly running a test
protocol for the database to contain identical data at the start of each round of
testing.
48. 1-24 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating Database Snapshots
Question: What file types are not allowed in the CREATE DATABASE statement
when creating a database snapshot?
49. Implementing a Microsoft SQL Server 2008 Database 1-25
MCT USE ONLY. STUDENT USE PROHIBITED
Lab: Creating Databases and Database Files
Exercise 1: Creating a Database
Scenario
The senior database developer at Adventure Works has created a specification for a
new database in which details of the information technology (IT) assets used by
the company will be stored. You must first use the specification to create the
database with the necessary options and create the appropriate filegroups. To do
this you will create a new database and create a SQL Server Management Studio
Scripts project with the following specifications:
• The new database name is AW_IT_Assets.
• The database should consist of two data files and one log file with the names
AW_IT_Assets_Data1, AW_IT_Assets_Data2, and AW_IT_Assets_log. These
files should be created in the E:MOD01Labfiles folder.
• The database should use two filegroups, the primary filegroup and a filegroup
named SECONDARY, which should be the default filegroup. The
AW_IT_Assets_Data2 file should be placed in the SECONDARY filegroup.
50. 1-26 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
• Both data files should have an initial size of 20 megabytes (MB) each and
should not grow automatically. The log file should have an initial size of 5 MB
and should not grow automatically.
• The database should automatically close when no users are connected and
should automatically shrink when appropriate.
• All scripts should be saved in a SQL Server Scripts project in the
E:MOD01LabfilesScripts folder.
The main tasks for this exercise are as follows:
1. Create a SQL Server Management Studio Scripts project.
2. Create a new database by executing a SQL Server Management Studio Scripts
project.
Task 1: Create a SQL Server Management Studio Scripts project
1. Start 6232A-NY-SQL-01, and log on as Student with the password of
Pa$$w0rd.
2. Create the AW_IT_Assets database based on the specifications provided.
Task 2: Create a new database by executing a SQL Server Management
Studio Scripts project
• Use the Generate Scripts Wizard to create a script of the database created in
Task 1.
• Save these scripts in a SQL Server Scripts project in the
E:MOD01LabfilesScripts folder.
Results: After this exercise, you should have created a new database with the
appropriate options and filegroups and created a SQL Server Management Studio
Scripts project.
51. Implementing a Microsoft SQL Server 2008 Database 1-27
MCT USE ONLY. STUDENT USE PROHIBITED
Exercise 2: Creating a Schema
Scenario
The senior database developer is now requesting that access to the new database
being used by the company be granted to a new user. In this exercise you will now
create the required schemas for the new AW_IT_Assets database.
The main tasks for this exercise are as follows:
1 Create a new database user.
2. Create a schema and assign ownership to a user.
3. Display ownership of a schema.
Task 1: Create a new database user
• Create a new database user named Katie.
• Do not grant Katie any permissions in the Database User window, as
permissions will be added in the next task.
Task 2: Create a schema and assign ownership to a user
• The database should have one user-defined schema named TechSupport.
• The user NY-SQL-01Katie should use the TechSupport schema as her default
schema.
Task 3: Display ownership of a schema
1. Create a T-SQL statement that displays ownership of the TechSupport schema.
2. Comment the T-SQL statement to explain what it will do on execution.
3. Execute the T-SQL statement.
Results: After this exercise, you should have created a schema and assigned ownership
to a user. You should have also displayed ownership of the newly created schema.
52. 1-28 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Exercise 3: Creating a Database Snapshot
Scenario
The senior developer at Adventure Works is now requesting a database snapshot
be created for reporting purposes. You will use T-SQL to write a statement that will
create a database snapshot, change the current database, and then restore the
database from the snapshot to undo those changes.
In this exercise you will create a database snapshot, alter the database, and then
revert the database to the previously created snapshot.
The main tasks for this exercise are as follows:
1. Create a database snapshot.
2. Alter the database.
3. Revert the database to the previously created database snapshot.
Task 1: Create a database snapshot
• A database snapshot named AW_IT_Assets_Snapshot1 must be created for
reporting purposes.
• Using T-SQL, create a snapshot of the AW_IT_Assets database.
• The files for the database snapshot must be created in the
E:MOD01LabfilesSnapshots folder.
Task 2: Alter the database
• Delete the TechSupport.Hardware table on the AW_IT_Assets database.
• Delete the TechSupport schema on the AW_IT_Assets database.
53. Implementing a Microsoft SQL Server 2008 Database 1-29
MCT USE ONLY. STUDENT USE PROHIBITED
Task 3: Revert the database to the previously created database
snapshot
• Create a T-SQL statement to revert the AW_IT_Assets database.
• Revert the database to the AW_IT_Assets_Snapshot1 database snapshot.
• Notice that the TechSupport.Hardware table and TechSupport schema have
both been restored.
Results: After this exercise, you should have created a database snapshot, altered the
database, and then reverted the database to the database snapshot.
Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual
machine and discard any changes.
54. 1-30 Creating Databases and Database Files
MCT USE ONLY. STUDENT USE PROHIBITED
Module Review and Takeaways
Review Questions
1. When are objects assigned to the default filegroup?
2. What is a database schema and how can schemas be used?
3. How would you recover an accidently dropped table and all of the
corresponding data from a database snapshot without recovering the entire
database?
Best Practices related to creating databases
Supplement or modify the following best practices for your own work situations:
• When you design a database you must first decide the tables that it needs.
Before you create a table and its objects, you should outline your plans about
the following table characteristics:
• The types of data the table will contain.
55. Implementing a Microsoft SQL Server 2008 Database 1-31
MCT USE ONLY. STUDENT USE PROHIBITED
• The number of columns in the table and, for each column, the data type
and length, if it is required.
• Which columns will accept null values.
• Whether and where to use constraints or defaults and rules.
• The types of indexes that will be needed, where required, and which
columns are primary keys and which are foreign keys.
• The most efficient way to create a database is to define everything that you
need at the same time. This includes the tables you require, the type of data
that goes into each table, and the users that can access those tables.
• You should not create any user objects, such as tables, views, stored
procedures, or triggers, in the master database. The master database contains
system-level information used by the instance of SQL Server, such as logon
information and configuration option settings.
Best Practices related to database snapshots
Supplement or modify the following best practices for your own work situations:
• Taking regular backups and testing your restore plan are essential to protect a
database. If you must restore the source database to the point in time at which
you created a database snapshot, implement a backup policy that enables you
to do that.
• Using database snapshots for reverting a database is not a substitute for your
backup and restore strategy.
• Reverting does not work on an offline or corrupted database.
Best practices related to compression
Supplement or modify the following best practices for your own work situations:
• If CPU is the dominant cost in your workload but you want to save some disk
space, you may want to enable PAGE compression on partitions that are not
accessed frequently while not compressing the current partition(s) that are
accessed and manipulated more frequently.
• If I/O cost is dominant for your workload, or you need to reduce disk space
costs, compressing all data using PAGE compression may be the best choice.
57. Implementing a Microsoft SQL Server 2008 Database 2-1
MCT USE ONLY. STUDENT USE PROHIBITED
Module 2
Creating Data Types and Tables
Contents:
Lesson 1: Creating Data Types 2-3
Lesson 2: Creating Tables 2-8
Lesson 3: Creating Partitioned Tables 2-17
Lab: Creating Data Types and Tables 2-23
58. 2-2 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
Module Overview
Objects that contain data have an associated data type that defines the kind of data
the object can contain, and all data stored in Microsoft® SQL Server® 2008 must be
compatible with base data types. Tables are database objects that contain all the
data in a database. In tables, data is organized in a row-and-column format similar
to a spreadsheet. Finally, partitioning makes large tables more manageable,
because partitioning enables you to manage and access subsets of data quickly and
efficiently, while maintaining data integrity. In this module you will be introduced
to the concepts involved in creating data types and tables. You will also learn about
partitioned tables.
59. Implementing a Microsoft SQL Server 2008 Database 2-3
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 1
Creating Data Types
Many objects in Microsoft SQL Server 2008 contain data and can be assigned data
types to better define the object attributes. In this lesson you will learn about
system-supplied data types, learn how to use system-supplied data types, and
discuss alias data types.
60. 2-4 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
What Are System-Supplied Data Types?
Key Points
As was mentioned earlier, objects that contain data have an associated data type
that defines the kind of data; for example, character, integer, or binary, the object
can contain.
• Columns in tables and views, parameters in stored procedures, variables, T-
SQL functions that return data values and stored procedures that have a return
code all have data types.
• All data stored in Microsoft SQL Server must be compatible with one of the
base data types shown in the table.
61. Implementing a Microsoft SQL Server 2008 Database 2-5
MCT USE ONLY. STUDENT USE PROHIBITED
Using System-Supplied Data Types
Key Points
SQL Server supplies a set of system data types that define all the types of data that
can be used with SQL Server.
• Data types in SQL Server are organized into several categories.
• Based on their storage characteristics, some data types are designated as
belonging to the large value data type group or the large object data type
group.
• All Unicode data uses the character set defined by the Unicode standard.
Unicode collations used for Unicode columns are based on attributes such as
case sensitivity, accent sensitivity, Kana sensitivity, width sensitivity and
binary.
62. 2-6 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
What Are Alias Data Types?
Key Points
Alias types are based on the system data types in SQL Server.
• Alias types can be used when several tables must store the same type of data in
a column and you have to make sure that these columns have identical data
type, length, and nullability. They can also be used in functions and stored
procedures.
• If an alias type is created in the model database, it exists in all new user-
defined databases. However, if the data type is created in a user-defined
database, the data type exists only in that user-defined database.
63. Implementing a Microsoft SQL Server 2008 Database 2-7
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating Data Types
Question: How is a user-defined data type implemented?
Question: How can you create an alias data type based on a system-supplied data
type?
64. 2-8 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 2
Creating Tables
Tables are database objects that contain all the data in a database. A table definition
is a collection of columns. In tables, data is organized in a row-and-column format
similar to a spreadsheet. In this lesson you will learn how SQL Server organizes
data in rows, how SQL Server organizes large data values, the concept of table
types, considerations for creating table types, and how to generate Transact-SQL
scripts.
65. Implementing a Microsoft SQL Server 2008 Database 2-9
MCT USE ONLY. STUDENT USE PROHIBITED
How SQL Server Organizes Data in Rows
Key Points
A data row consists of a row header and a data portion. It is important to
understand the elements of the data portion of each row to accurately estimate the
size of a table.
• The data portion of a row can contain fixed-length data, a null block, a variable
block, and variable-length data.
• Each row represents an individual occurrence of the object modeled by the
table. For example, a computer parts table would have one row for each
computer part carried by the company.
66. 2-10 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
How SQL Server Organizes Large Data Values
Key Points
With large-value data types you can work with SQL Server in a way that was not
possible using the text, ntext and image data types from earlier versions of SQL
Server.
• varchar(max), nvarchar(max), and varbinary(max), and XML data types are
collectively called large-value data types.
• Large-value data types can define variables that can store large amounts of
data, up to 2^31 bytes of character, binary, and Unicode data.
• Large-value data are similar in behavior to their smaller counterparts, varchar,
nvarchar and varbinary. This similarity enables SQL Server to store and
retrieve large character, Unicode, and binary data more efficiently.
67. Implementing a Microsoft SQL Server 2008 Database 2-11
MCT USE ONLY. STUDENT USE PROHIBITED
Types of Tables
Key Points
Besides the standard role of basic user-defined tables, SQL Server provides the
following types of tables that serve special purposes in a database:
• Partitioned tables: support all the properties and features associated with
designing and querying standard tables, including constraints, defaults,
identity and timestamp values, triggers, and indexes.
• Local temporary tables are visible only to the current connection and are
deleted after a user disconnects from that instance of SQL Server.
• Global temporary tables are visible to any user after they are created and are
deleted when all users referencing the table disconnect from that instance of
SQL Server.
68. 2-12 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
• System tables: SQL Server stores the data that defines the configuration of the
server and all its tables in a special set of tables known as system tables. You
cannot directly work with the data in these tables.
Question: What properties do partitioned tables support?
69. Implementing a Microsoft SQL Server 2008 Database 2-13
MCT USE ONLY. STUDENT USE PROHIBITED
Considerations for Creating Tables
Key Points
The most efficient way to create a table is to define everything needed in the table
at the same time. This includes its data restrictions and additional components.
• Database collation for char, varchar, text, nchar, nvarchar, and ntext data can
be overridden by specifying a collation for a particular column of the table and
using either the COLLATE clause of CREATE TABLE and ALTER TABLE, SQL
Server Management Studio, or the column.collation property.
• The nullability of a column determines whether that column can allow a null
value (NULL) as the data in that column.
• Computed columns can be used in select lists, WHERE clauses, ORDER BY
clauses, or any other locations in which regular expressions can be used, with
some exceptions.
• Identity Property columns identify a row uniquely.
70. 2-14 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
• Timestamp columns are generally used as a mechanism for version-stamping
table rows.
• Uniqueidentifier columns are 16-byte Globally Unique Identifiers (GUID).
Replication uses uniqueidentifier columns to guarantee that rows are uniquely
identified across multiple copies of a table.
71. Implementing a Microsoft SQL Server 2008 Database 2-15
MCT USE ONLY. STUDENT USE PROHIBITED
Generating Transact-SQL Scripts
Key Points
You can create Transact-SQL scripts using the Generate SQL Server Scripts
Wizard, or using Object Explorer.
• Use Object Explorer to quickly create scripts of an entire database, or a single
database object using the default options.
• The Generate Scripts Wizard flows through the process of creating Transact-
SQL scripts, and provides a variety of objects to be scripted at once.
• To create combined scripts, save the first script to a Query Editor window and
the second to the clipboard so it can be pasted into the window after the first
script.
72. 2-16 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating Tables
Question: What options of a table can be changed after the table has been created?
73. Implementing a Microsoft SQL Server 2008 Database 2-17
MCT USE ONLY. STUDENT USE PROHIBITED
Lesson 3
Creating Partitioned Tables
By using partitioning, the time taken to load data from an Online Transaction
Processing (OLTP) system to an Online Analytical Processing (OLAP) system is
significantly reduced. In this lesson you will be introduced to the concepts of
partitioned tables, partition functions, partition schemes, and you will discuss what
operations can be performed on partitioned data.
74. 2-18 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
What Are Partitioned Tables?
Key Points
The data of partitioned tables and indexes is divided into units that can be spread
across more than one filegroup in a database.
• The data is partitioned horizontally, so that groups of rows are mapped into
individual partitions.
• Partitioned tables and indexes support all the properties and features
associated with designing and querying standard tables and indexes, including
constraints, defaults, identity and timestamp values, and triggers.
• Partitioning a table or index might improve query performance if the partitions
are designed correctly, based on the types of queries frequently run and on
hardware configuration.
75. Implementing a Microsoft SQL Server 2008 Database 2-19
MCT USE ONLY. STUDENT USE PROHIBITED
What Are Partition Functions?
Key Points
A partition function specifies how the table or index is partitioned.
• The scope of a partition function is limited to the database that it is created in.
Within the database, partition functions reside in a separate namespace from
the other functions.
• Any rows whose partitioning column has null values are placed in the left-most
partition, unless NULL is specified as a boundary value and RIGHT is
indicated.
• boundary_value is a constant expression that can reference variables. This
includes user-defined type variables, or functions and user-defined functions.
It cannot reference Transact-SQL expressions.
• To make sure the partition function definition behaves as expected for all
session languages, use constants that are interpreted the same way for all
language settings, such as the yyyymmdd format.
76. 2-20 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
What Is a Partition Scheme?
Key Points
A partition scheme is a scheme in the current database that maps the partitions of a
partitioned table or index to filegroups.
• A partition function must first be created in a CREATE PARTITION
FUNCTION statement before creating a partition scheme.
• Partitions created by the partition function are mapped to the filegroups
specified in the partition scheme.
• In a partition scheme, only one filegroup can be designated NEXT USED. A
filegroup that is not empty can be specified. This means the filegroup will
accept a new partition that is created by using an ALTER PARTITION
FUNCTION statement.
Question: What is the relationship between a partitioned table, a partition
function, and a partition scheme?
77. Implementing a Microsoft SQL Server 2008 Database 2-21
MCT USE ONLY. STUDENT USE PROHIBITED
What Operations Can Be Performed on Partitioned Data?
Key Points
When you add a partition, you do so by "splitting" an existing partition into two
partitions and redefining the boundaries of the new partitions. When you drop a
partition, you do so by "merging" the boundaries of two partitions into one.
• Partition-aligned indexed views can be switched together with the partitioned
tables the views are defined against. Maintenance operations on partitions or
subsets of data are performed more efficiently because these operations target
only the data that is required, instead of the entire table.
• ALTER PARTITION FUNCTION can only be used for splitting one partition
into two, or for merging two partitions into one.
78. 2-22 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
Demonstration: Creating a Partitioned Table
Question: What is the scope of a partition function?
Question: How are partitions mapped?
79. Implementing a Microsoft SQL Server 2008 Database 2-23
MCT USE ONLY. STUDENT USE PROHIBITED
Lab: Creating Data Types and Tables
Exercise 1: Creating Data Types
Scenario
The sales manager at Adventure Works has requested that the company’s database
be modified to include data about goods that have been returned and sales that
have been refunded. In addition, the senior database developer has designed some
new data types for the returns and refunds data and has assigned you the task of
creating them in the database.
The main tasks for this exercise are as follows:
1. Create a data type based on the nvarchar system-supplied data type.
2. Create a data type based on the decimal system-supplied data type.
80. 2-24 Creating Data Types and Tables
MCT USE ONLY. STUDENT USE PROHIBITED
Task 1: Create a data type based on the nvarchar system-supplied data
type
• Start 6232A-NY-SQL-01, and log on as Student with the password of
Pa$$w0rd.
• Create a new data type named ShortDescription in the dbo schema.
• This data type should be based on the nvarchar system-supplied data type and
should have a maximum length of 100 characters.
Task 2: Create a data type based on the decimal system-supplied data
type
• Create a new data type named CashValue in the dbo schema.
• This data type should be based on the decimal system-supplied data type and
should have a precision of 8 and a scale of 2.
Results: After this exercise, you should have successfully created a new data type
based on the nvarchar system-supplied data type. You should have also successfully
created a new data type based on the decimal system-supplied data type.