Harness the Powerful New Features of SQL Server 2008 Whether you’re a database administrator or application developer, this in-depth guide is your key to delivering improved data collec
Trang 1Harness the Powerful New
Features of SQL Server 2008
Whether you’re a database administrator or application developer, this
in-depth guide is your key to delivering improved data collection, storage,
re-porting, and security with SQL Server 2008 Mastering SQL Server 2008 brings
you up to speed on architecture, installation, and confi guration essentials,
before moving to the step-by-step instruction you need for more advanced
topics such as procedural programming, query optimization, how to use spatial
data, SQL Server in the NET world, and more
You’ll master the extensive toolset, explore useful third-party tools, and most
importantly, fi nd out how to choose and use the right SQL Server features for
the specifi c tasks you have
COVERAGE INCLUDES:
• Installing and confi guring SQL Server 2008
• Understanding SQL Server’s place within the Microsoft architecture
• Making data reliably and effi ciently available to your consumers
• Securing your data with SQL Server 2008’s new Transparent Data
Encryption feature
• Integrating XML technology into SQL Server
• Creating index architectures for maximum benefi t and minimum cost
• Exploring new geometry and geography data types for today’s businesses
• Maximizing data warehousing and business intelligence tools
Master the New Features
of SQL Server 2008
Migrate Smoothly from Other Major RDBMS to SQL Server 2008
Discover Practical Tools and Techniques, Whether You’re a Developer or Administrator
Implement and Optimize Security to Protect Your Data Resources
Learn in the Context of Real-World Scenarios and Tasks
ABOUT THE AUTHORS
Michael Lee, MCT, MCITP, MCPD, SCJP, has been teaching SQL Server since 1995 Over the last 13 years, Michael has provided training
and consulting services in SQL Server and Enterprise Data Architecture to companies across the U.S and Europe Gentry Bieker, MCT,
MCITP, MCDBA, MCSE, has been a consultant, mentor, and trainer since 1998 He has been architecting, developing, and administering
SQL Server databases since version 6.0
Install, Confi gure, and Manage SQL Server 2008
Optimize, Troubleshoot, and Secure Your Database
Microsoft®
Trang 3Mastering
Trang 5Michael Lee
Gentry Bieker
Trang 6Acquisitions Editor: Agatha Kim
Development Editor: Laurene Sorensen
Technical Editor: Acey Bunch
Production Editor: Christine O’Connor
Copy Editor: Kathy Grider-Carlyle
Production Manager: Tim Tate
Vice President and Executive Group Publisher: Richard Swadley
Vice President and Publisher: Neil Edde
Book Designer: Maureen Forys, Happenstance Type-O-Rama; Judy Fung
Compositor: Jeffrey Lytle, Happenstance Type-O-Rama
Proofreader: Scott Klemp, Word One
Cover Designer: Ryan Sneed
Cover Image: © Pete Gardner / Digital Vision / Getty Images
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-28904-4
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,
mechan-ical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act,
without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for
per-mission should be addressed to the Perper-missions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011,
fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the
accu-racy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness
for a particular purpose No warranty may be created or extended by sales or promotional materials The advice and strategies contained
herein may not be suitable for every situation This work is sold with the understanding that the publisher is not engaged in rendering legal,
accounting, or other professional services If professional assistance is required, the services of a competent professional person should be
sought Neither the publisher nor the author shall be liable for damages arising herefrom The fact that an organization or Web site is
referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher
endorses the information the organization or Web site may provide or recommendations it may make Further, readers should be aware that
Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department
within the U.S at (800) 762-2974, outside the U.S at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data
Trang 7Dear Reader,
Thank you for choosing Mastering SQL Server 2008 This book is part of a family of
premium-quality Sybex books, all of which are written by outstanding authors who combine practical experience with a gift for teaching
Sybex was founded in 1976 More than thirty years later, we’re still committed to producing sistently exceptional books With each of our titles we’re working hard to set a new standard for the industry From the paper we print on, to the authors we work with, our goal is to bring you the best books available
con-I hope you see all that reflected in these pages con-I’d be very interested to hear your comments and get your feedback on how we’re doing Feel free to let me know what you think about this or any other Sybex book by sending me an email at nedde@wiley.com, or if you think you’ve found a technical error in this book, please visit http://sybex.custhelp.com Customer feedback is criti-cal to our efforts at Sybex
Best regards,
Neil Edde Vice President and Publisher Sybex, an Imprint of Wiley
Trang 8To our students, who forced us to continually improve.
Trang 9Every project of this size is always an intense collaboration This was certainly no exception It all starts with the wonderful team at Sybex This is the seventh project that I have worked on with the Sybex team, and I am always impressed by the work that they do Special thanks to Neil Edde, Pete Gaughan, and Agatha Kim for their magnificent work on managing this pro-cess Thanks also to our editor, Laurene Sorensen, who was able to merge our ideas together and help us to make the technical content actually readable And thanks to the production team
of Christine O’Connor, Kathy Grider-Carlyle, and Scott Klemp Acey Bunch was a spectacular technical editor; an accomplished author in his own right, he provided many insights on the content that proved invaluable and substantially improved the quality of the content Gentry Bieker, my coauthor on this project, was able to really capture the essence of SQL Server in the real world, something with which he has extensive experience The production team at Sybex is superb They were even able to take my hand drawings and turn them into real graphics, a true feat if you have ever seen my handwriting
Finally, on a personal note, my career in training and technology would never have taken off had it not been for a former mentor, Bob Taylor Other colleagues including Jon Hansen, Dale Byrd, Bryan Bechtoldt, Ken Sandlin, and Mike Mansfield have contributed so much to
my career and given me amazing support over the years Additionally, most of this work was written while I was employed at Aristocrat Technologies in Las Vegas, and I need to thank my colleagues and the management there for their support and input And of course, I need to offer special thanks to my family, my wife and son, who always pay the highest price for these proj-ects as I lock myself into the office every weekend to write They have been incredibly support-ive as the process continued week after week, and I could not have done it without them
Most importantly, thanks to you, the reader You are the reason for this project in the first place I hope that you find value in the pages Without you, we would not have had this incred-ible opportunity Your feedback is invaluable and will help make any future projects better and more relevant Good luck in your undertakings with SQL Server 2008 I wish you the best in your endeavors
—Michael Lee
I’m incredibly thankful for the level of support I’ve received from everyone while writing my portion of this book Thanks to Jennifer Hanner for all of the sacrifices she made, and the trips she allowed me to miss in order to complete this book, helping to keep me sane, and encourag-ing me to keep going through the process To Samantha and Joel, my children, who went on many trips and outings without me through during the writing process They made me smile, and reminded me that there is more to life than just a book To Joel: “Yes, I’m finally done with
my chapter!” To Michael Lee, who gave me this fantastic opportunity and introduced me to the process, and has always been patient and understanding in my learning about what it takes to put together a book of this size Thanks to the entire book team: Laurene Sorensen, Acey Bunch, Pete Gaughan, Agatha Kim, and Neil Edde I had an incredible amount of help and support from everyone I’ve encountered at Sybex and Wiley You have all given me a ton of respect for the process that goes into creating a book And to every one of my students (especially the dif-ficult ones), who helped me to make it to where I am today
—Gentry Bieker
Trang 11About the Authors
Michael Lee (MCT, MCPD, MCITP, SCJP) has spent the last 15 years in technology training and consulting Most of his career has been spent working with companies and helping them ease the transition to new technologies and practices With a degree in Business Finance from the University of Utah, Michael discovered early that he enjoyed the IT aspects of business and built
a career bringing together businesses and IT professionals, helping them understand each other and improve communication
His beginnings in IT were a bit dubious, having worked as an intern with IBM in 1988 on the FAA modernization project (AAS), which has been dubbed one of the greatest project failures
in IT history A lot was learned from that experience, and since then, his focus has been ing together business and technology interests As a former Microsoft Regional Director, he was heavily involved in the rollout of Visual Studio 6.0 in 1997 and has made a career out of melding business and technology into a unified strategic front
bring-Currently, Michael is employed with the Clark County Court System in Las Vegas, Nevada where he still gets a chance to get his hands dirty with all kinds of technology, applying his pas-sion to the public sector When he is not coding, writing, or spending time with family, you can usually find him on his Harley, looking for that next great American Road
Gentry Bieker is a certified trainer, consultant, and mentor who has focused on SQL Server and related technologies for the last decade His experience spans from database design and tuning
to application development and enterprise application integration He has developed numerous presentations, classes, and sessions on SQL Server and many of the other Microsoft technolo-gies that work with SQL Server In addition to SQL Server, he also focuses on SharePoint and Microsoft CRM He has worked with customers in many industries, spanning from health care and insurance to casino gaming and manufacturing
As an energetic and passionate individual, he has found that turning massive amounts
of data into useful information is what gets him up in the morning He’s provided training, mentoring, and consulting services for many companies, large and small, including Microsoft, Unisys, and Kimberly-Clark In his spare time, he enjoys spending time with his children, jump-ing out of perfectly good airplanes, and gaming
Trang 12Contents at a Glance
Introduction xxiii
Chapter 1 • Overview of Microsoft SQL Server 2008 1
Chapter 2 • Understanding SQL Server Architecture 35
Chapter 3 • Databases, Files, and Resource Management 65
Chapter 4 • Tables and CRUD Operations 89
Chapter 5 • Procedural Programming 133
Chapter 6 • Managing Data Integrity 163
Chapter 7 • SQL Server and XML 189
Chapter 8 • Managing User Security 223
Chapter 9 • Data Recovery 253
Chapter 10 • Monitoring SQL Server Activity 283
Chapter 11 • Using the SQL Server Agent Service 319
Chapter 12 • Data Availability and Distribution 349
Chapter 13 • SQL Server Data Security 389
Chapter 14 • Indexing Strategies for Query Optimization 415
Chapter 15 • Transactions and Locking 443
Chapter 16 • Using the Resource Governor and Policy-Based Management 473
Chapter 17 • SQL Server and the NET Client 503
Chapter 18 • SQL Server and the Common Language Runtime 539
Chapter 19 • Using Spatial Data 569
Chapter 20 • Service-Oriented Architecture and the Service Broker 595
Chapter 21 • Full-Text Search Services 623
Trang 13Appendices 653
Appendix A • The Bottom Line 655
Appendix B • SQL Server Analysis Services Overview 693
Appendix C • SQL Server 2008 Reporting Services 709
Index 723
Trang 15Introduction xxiii
Chapter 1 • Overview of Microsoft SQL Server 2008 1
SQL Server in the Enterprise World 1
The Need for an Enterprise System 2
SQL Server Features 3
SQL Server’s Place Within Microsoft Architecture 6
SQL Server Licensing 8
Installing SQL Server 2008 10
Defining an Installation Plan 10
SQL Server 2008 Installation Requirements 16
The SQL Server Installation Process 17
Verifying the Installation 26
The SQL Server Tool Set 28
The Microsoft Client Tools 28
Third-Party Tools and Utilities 32
The Bottom Line 33
Chapter 2 • Understanding SQL Server Architecture .35
Essential Internals 35
SQL Server Data Storage Architecture 35
The Data Engine 44
SQL Server and Windows 47
The SQL Server System Catalog 48
The System Databases 48
System Tables, Views, and Functions 49
System Stored Procedures 55
Datatyping 57
System-Defined Datatypes 57
User-Defined Datatypes 60
The Bottom Line 63
Chapter 3 • Databases, Files, and Resource Management .65
Planning a Database 65
Planning for Database Usage 65
Planning for Recovery 66
Capacity Planning 68
Trang 16xiv | Contents
Creating Databases 69
Creating the Database 70
Manipulating Database Options 75
Managing Databases, Files, and Filegroups 78
Altering a Database 78
Growing and Shrinking Databases and Files 82
Creating Database Snapshots 86
The Bottom Line 88
Chapter 4 • Tables and CRUD Operations 89
Designing Data Storage 89
Implementing a Normalized Design 90
Denormalization 94
Creating and Dropping SQL Server Tables 96
The Basics of Table Creation 96
Computed Columns in Tables 98
Dropping Tables 100
Table Partitioning 100
Selecting Data from a Table 105
Aggregation and Grouping 106
Joins and Table Correlation 109
Subqueries, Derived, and Temporary Tables 113
Common Table Expressions 118
Modifying Data 122
The INSERT Process 122
The DELETE Process 124
The UPDATE Process 126
The MERGE Process 127
Using the OUTPUT Clause 129
The Bottom Line 130
Chapter 5 • Procedural Programming 133
Procedural Structures 133
Batches 133
Variables 135
Control-of-Flow Statements 136
Error Management 138
Basic Transaction Processing 142
Stored Procedures 144
Designing Effective Stored Procedures 145
Creating and Executing a Simple Stored Procedure 146
Using Parameters 147
Managing Return Values 151
Understanding Compilation 151
Views 153
Trang 17Contents | xv
User-Defined Functions 155
Functions Versus Stored Procedures 156
Built-In Functions Revisited 157
Scalar Functions 157
Table-Valued Functions 159
Using Synonyms 161
Why Use Synonyms? 161
Creating a Synonym 161
The Bottom Line 162
Chapter 6 • Managing Data integrity 163
Understanding Data Integrity Controls 163
Enforcing Data Integrity 164
Data Integrity Categories 164
Working with Constraints 165
Primary Key and Unique Constraints 165
Foreign Key Constraints 168
Default Definitions 172
Check Constraints 174
Working with DML Triggers 175
Understanding Triggers 176
Using AFTER Triggers 179
Using INSTEAD OF Triggers 183
Special Considerations 185
Rule and Default Objects 186
Default Objects 186
Rules 187
The Bottom Line 187
Chapter 7 • SQL Server and xML 189
Returning XML from SQL Server Using FOR XML 189
Creating XML with RAW Mode Queries 190
Creating XML with AUTO Mode Queries 192
Creating XML with EXPLICIT Mode Queries 195
Creating XML with PATH Mode Queries 198
The xml Datatype 200
Implementing the xml Datatype 201
Shredding XML Data to Relational Output 203
Validating XML with Schemas 205
Using the XML Schema Collection 206
Using Namespaces in Schemas 207
Implementing XQuery 208
Simple XQuery Expressions 208
Structuring Complex XQuery Syntax 209
Creating an XML Structure with XQuery 211
XQuery and Namespaces 212
Other XML Datatype Methods 215
Trang 18xvi | Contents
XML Indexes 218
The Bottom Line 221
Chapter 8 • Managing User Security .223
The SQL Server Security Infrastructure 223
SQL Server 2008 Security Architecture 224
Implementing SQL Server Principals and Authentication 231
Implementing Logins 231
Implementing Users 237
Implementing Roles 239
Implementing Permissions in SQL Server 242
Understanding Permission Behavior 243
Setting Permissions 244
Ownership Chains 249
The Bottom Line 250
Chapter 9 • Data Recovery 253
Transaction Architecture 253
Database Recovery Models 254
The Internals of Transaction Logging 254
How Transaction Logging Is Used 255
Backup and Restore Strategies 257
Recovery Models and Backup Strategy 258
Backup Types 260
Performing Backups 260
Full Backups 261
Backup Devices, Media Sets, and Media Families 261
Differential Backups 263
Transaction Log Backups 264
Partial Backups 264
Creating Backups Using Management Studio 265
Performing Restores 267
Retrieving Backup Metadata 267
Performing a Complete Restore 268
Performing Point in Time Recovery 271
Performing a File or Filegroup Restore 273
Performing Page Restore Operations 275
Using SQL Server Management Studio to Restore a Database 275
Other Issues 277
System Database Recovery 277
Backup Security 279
Backup Performance and Optimization 280
Backup Compression 280
The Bottom Line 281
Trang 19Contents | xvii
Chapter 10 • Monitoring SQL Server Activity .283
Using System Monitor 283
Basic Monitoring Concepts 284
Graphs, Logs, and Alerts 286
Selecting Resources and Counters 287
Using SQL Profiler & Trace 290
Designing a Good Trace 290
Selecting Data Columns and Events 291
Evaluating Trace Output 297
Replaying Traces for Performance Analysis 301
DDL Triggers 305
DDL Triggers Versus DML Triggers 306
Trigger Events 307
EVENTDATA and Its Schema 311
Event Notifications 314
Event Notifications Versus DDL Triggers 315
Event Classes 315
Implementing Event Notifications 315
The Bottom Line 317
Chapter 11 • Using the SQL Server Agent Service 319
SQL Agent and Automation 319
Reducing Administration Overhead 319
The SQL Server Agent Architecture 320
Configuring the SQL Agent Service 323
Creating Jobs 328
Creating Jobs 328
Creating Job Steps 330
Creating Schedules 335
Executing Jobs 336
Creating Alerts 337
Monitoring the Event Log 338
Responding to Performance Alerts 340
Understanding WMI Alerts 340
Creating Operators 341
Operator Types 341
Configuring Operators 342
Associating Operators with Jobs and Alerts 343
Scripting the SQL Agent 344
Understanding the SQL Agent System Stored Procedures 344
Scripting Existing Jobs 345
The Bottom Line 347
Trang 20xviii | Contents
Chapter 12 • Data Availability and Distribution 349
Overview of SQL Server Availability and Distribution Options 349
Hardware Considerations 350
SQL Server Features 352
Database Log Shipping 355
Configuring Log Shipping 356
Failing Over in a Log Shipping Scenario 365
Database Mirroring 366
Configuring Database Mirroring 366
Exploring the Mirroring Solution 373
Replication 374
Replication Overview 374
Configuring Replication 376
The Bottom Line 386
Chapter 13 • SQL Server Data Security 389
Understanding the SQL Server Key Infrastructure 389
The SQL Server Keys 390
Extensible Key Management 399
Backing Up the Keys 400
Using Transparent Data Encryption 401
Creating Keys and Certificates 402
Encrypting Data Using SQL Server 403
Understanding Authenticators 404
Encryption with Passphrases 404
Encryption with Symmetric Keys 405
Encryption with Asymmetric Keys 406
Encryption with Certificates 408
Module Signing 411
The Bottom Line 413
Chapter 14 • indexing Strategies for Query Optimization 415
Index Architecture 415
Index Basics 416
Data Heaps 418
Clustered Indexes 422
Nonclustered Indexes 424
Planning Clustered and Nonclustered Indexes 426
Creating and Managing Indexes 430
Creating Indexes with SSMS 430
Managing Indexes and Fragmentation with SSMS 432
Creating and Managing Indexes with TSQL 436
Special Index Considerations 439
Covering a Query 439
Logical Operator Processing 440