Professional SQL Server 2008 Reporting ServicesProfessional Microsoft SQL Server 2008 Analysis Services shows readers how to build data warehouses and multidimensional databases, query
Trang 2Professional SQL Server 2008 Reporting Services
Professional Microsoft SQL Server 2008 Analysis Services shows readers how to
build data warehouses and multidimensional databases, query databases, and use Analysis Services and other components of SQL Server to provide end-to-end solutions
Professional Microsoft SQL Server 2008 Programming
978-0-470-25702-9
This updated new edition of Wrox’s best-selling SQL Server book has been expanded
to include coverage of SQL Server 2008’s new datatypes, new indexing structures, manageability features, and advanced time-zone handling
Professional Microsoft SQL Server 2008 Administration
978-0-470-24796-9
A how-to guide for experienced database administrators, this book is loaded with unique tips, tricks, and workarounds for handling the most difficult SQL Server administration issues The authors discuss data capture, performance studio, Query Governor, and new techniques for monitoring and policy management
Beginning Microsoft SQL Server 2008 Programming
Beginning T-SQL with Microsoft SQL Server 2005 and 2008 provides a comprehensive introduction to the T-SQL programming language, with
concrete examples showing how T-SQL works with both SQL Server 2005 and SQL Server 2008
Beginning Database Design Solutions
978-0-470-38549-4
Beginning Database Design Solutions introduces IT professionals—both DBAs and database developers—to database design It explains what
databases are, their goals, and why proper design is necessary to achieve those goals It tells how to decide what should be in a database to meet the application’s requirements It tells how to structure the database so it gives good performance while minimizing the chance for error
Enhance Your Knowledge Advance Your Career
Get more out of
Wrox Online Library
Hundreds of our books are available online
through Books24x7.com
Wrox Blox
Download short informational pieces and
code to keep you up to date and out of
trouble!
Chapters on Demand Purchase individual book chapters in pdf format
Join the Community Sign up for our free monthly newsletter at newsletter.wrox.com
Browse Ready for more Wrox? We have books and e-books available on NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!
Contact Us
We always like to get feedback from our readers Have a book idea?
Need community support? Let us know by e-mailing wrox-partnerwithus@wrox.com
Trang 3Introduction xxxv
Chapter 1: Being Objective: Re-Examining Objects in SQL Server 1
Chapter 2: Tool Time 19
Chapter 3: Asking a Better Question: Advanced Queries 37
Chapter 4: XML Integration 67
Chapter 5: Daring to Design 113
Chapter 6: Core Storage and Index Structure 147
Chapter 7: More Advanced Index Structures 189
Chapter 8: Views 237
Chapter 9: Scripts and Batches 255
Chapter 10: Advanced Programmability 283
Chapter 11: Transactions and Locks 335
Chapter 12: Triggers 367
Chapter 13: SQL Cursors 399
Chapter 14: Reporting Services 435
Chapter 15: Buying in Bulk: The Bulk Copy Program (BCP) and Other Basic Bulk Operations 473
Chapter 16: Getting Integrated 493
Chapter 17: Replication 513
Chapter 18: Looking at Things in Full: Full-Text Search 555
Chapter 19: Feeling Security 579
Chapter 20: A Grand Performance: Designing a Database That Performs Well 617
Chapter 21: What Comes After: Forensic Performance Tuning 637
Chapter 22: Administration 655
Chapter 23: SMO: SQL Management Objects 705
Chapter 24: Data Warehousing 727
Chapter 25: Being Well Connected 751
Appendix A: System Functions 753
Appendix B: Going Meta: Getting Data About Your Data 815
Appendix C: The Basics 841
Index 861
Trang 5Professional
Trang 8Professional Microsoft SQL Server 2008 Programming
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, 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 permission
should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030,
(201) 748-6011, fax (201) 748-6008, or online athttp;//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 accuracy 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 please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress
are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other
countries, and may not be used without written permission Microsoft and SQL Server are registered trademarks of
Microsoft Corporation in the United States and/or other countries All other trademarks are the property of their
respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be
available in electronic books.
Trang 9This book is dedicated with all my heart to Ashley, Addy, and Anna It’s hard to believe that Ashley was still in
elementary school when I wrote my first book (she’ll graduate from college later this year) and didn’t have to share this dedication with other kids (heck, she isn’t much of a kid anymore — eeek!) Then there’s Addy, who literally dreads me writing, yet continues to put up with me ‘‘disappearing’’ into my home office during the lengthy period
of time I work on a book Finally, there’s Anna, who came in the middle of this round of writing, and didn’t have
any real history on what to expect from my writing disappearances.
A dedication of this book would most certainly not be complete without a particularly special thank you to Deb,
who has leveraged my efforts in this and my recent Beginning title to redefine for me what the terms ‘‘love’’ and
‘‘support’’ mean.
As I’ve said for many releases now, I wish Wrox would let me print a picture of the women in my life on the cover
of this book rather than my ugly mug — I’m certain that you, the reader, would appreciate it too!
Trang 11About the Author
Experiencing his first infection with computing fever in 1978, Rob Vieira knew right away that this
was something ‘‘really cool.’’ In 1980 he began immersing himself into the computing world more
fully — splitting time between building and repairing computer kits, and programming in BASIC as
well as Z80 and 6502 assembly In 1983, he began studies for a degree in Computer Information Systems,but found the professional mainframe environment too rigid for his tastes and dropped out in 1985 topursue other interests Later that year, he caught the ‘‘PC bug’’ and began the long road of programming
in database languages from dBase to SQL Server Rob completed a degree in business administration in
1990 and since has typically worked in roles that allow him to combine his unique knowledge of ness and computing Beyond his bachelor’s degree, he has been certified as a Certified Management
busi-Accountant (CMA); Microsoft Certified as a Solutions Developer (MCSD), Trainer (MCT), and DatabaseAdministrator (MCDBA); and even had a brief stint certified as an Emergency Medical Technician (EMT)
Rob is currently the Database Team Lead for Stockamp, a Huron Consulting Group practice He has
published six books on SQL Server development
He resides in Vancouver, Washington, where he does his best to take care of ‘‘his girls,’’ and even takeshis best shot at letting Deb take care of him some too
Trang 15Nearly a decade has gone by since I finished my first book on SQL Server, and the list of those deservingsome credit continues to grow
As always, I’ll start with my kids They are the ones who most sacrifice time when a new release comes
along and I spend so much time writing
Deb— This was the first time she had to deal with one of my writing cycles, and she couldn’t have doneanything more to make me feel more supported Deb has helped me redefine the meaning of the wordsupport She is my rock
You— the readers You continue to write me mail and tell me how I helped you out in some way Thatcontinues to be the number one reason I find the strength to write another book The continued support
of my Professional series titles has been amazing We struck a chord — I’m glad Here’s to hoping we help
make your SQL Server experience a little less frustrating and a lot more successful
As always, I want to pay special thanks to several people past and present Some of these are at the oldWrox Press, but they remain so much of who I am as a writer that I need to continue to remember them.Others are new players for me, but have added their own stamp to the mix — sometimes just by showing
a little patience:
somehow guided me through the edit process to build a better book each time I have long since fallenout of touch with Kate, but she will always be the most special to me as someone who really helped shape
my writing career I will likely always hold this first ‘‘professional’’ dedication spot for her Whereveryou are Kate, I hope you are doing splendidly
bottom — that didn’t seem quite right for Syd Syd first appeared to me as one of a cast of seeminglythousands (it was less than that, but it seemed like a constantly changing set of people), but has evolvedinto one of the constants in my last few titles Syd has done a great job of finding some balance between
upholding the notion of ‘‘Wiley standards’’ versus allowing my books to be my books It’s beyond time
that she got her due — here is at least a little bit of it
where everything is’’ person of the book She has a way of displaying a kind of ‘‘peace’’ in most thingsI’ve seen her do — I need to learn that
writing instead of sleep lately, maybe it’s not thanks I owe him) I’ve had the pleasure of re-establishingcontact with Dominic recently, and it’s great to see him doing well
central to round two Catherine was much like Kate in the sense she had a significant influence on the
Trang 16shape and success of my first two titles I’ve also recently managed to be in touch with ‘‘Cath’’ again, and
am glad she also seems to be doing well
myself, and it’s not the easiest job to notice the little details that were missed or are, in some fashion,
wrong It’s even harder to read someone else’s writing style and pick the right times to say, ‘‘You might
want to approach this differently’’ and the right times to let it be John did a terrific job on both counts
John faced an especially trying time during the latter stages of this book’s development, and did an
amazing job of holding it all together I wish he and his wife Rebecca great fortunes and good health in
the year ahead
is one of the true ‘‘nice guys’’ who isn’t just nice — he just plain ‘‘gets it’’ when it comes to SQL Server
Richard has provided the answer to many a question over the years
This book has been in development for so long and touched enough people that I’m sure I’ve missed one
or two — if you’re among those missed, please accept my humblest apologies and my assurance that
your help was appreciated
Trang 17Contents
Trang 18Getting Started 27
SQL Server Business Intelligence Development Studio 33
Nested Queries Using Single Value SELECT Statements 39
Nested Queries Using Subqueries That Return Multiple Values 40
Comparing EXCEPT and INTERSECT with Their EXISTS and NOT EXISTS Equivalents 51
Creating, Altering, and Dropping XML Schema Collections 71
Trang 19XML Data Type Methods 73
Dealing with File-Based Information Via Classic BLOBs 126
Trang 20Chapter 6: Core Storage and Index Structure 147
Choosing Wisely: Deciding What Index Goes Where and When 174
Trang 21Understanding Depth Versus Fanout 200
Working with HierarchyID Values — HierarchyID Methods 202
Using a View to Change Data — Before INSTEAD OF Triggers 242
Making Your View Look Like a Table with VIEW_METADATA 248
Dynamic SQL: Generating Your Code on the Fly with the EXEC Command 263
Trang 22Control-of-Flow Statements 268
Understanding the SQLCLR and NET Programming in SQL Server 307
Creating Scalar User-Defined Functions from Assemblies 314
Trang 23At a Change of Database Options 345
When Recovery Time Would Exceed the Recovery Interval Option Setting 345
Dealing with Requirements Sourced from Other Tables 374
Feeding Data into De-normalized Tables for Reporting 379
Trang 24Triggers Can Be Nested 383
Triggers Don’t Get in the Way of Architecture Changes 384
Triggers Don’t Have Concurrency Issues with the Process That Fires Them 396
Types of Cursors and Extended Declaration Syntax 405
Trang 25Other Means of Accessing Reporting Services 437
Chapter 15: Buying in Bulk: The Bulk Copy Program (BCP)
Trang 26Creating, Altering, Dropping, and Manipulating a Full-Text Catalog 558
Creating, Altering, Dropping, and Manipulating Full-Text Indexes 561
Trang 27Don’t Forget Views, Stored Procedures, and UDFs as Security Tools 613
Trang 28Chapter 20: A Grand Performance:
Check the Index Tuning Tool in the Database Engine Tuning Advisor 620
Using the Least Restrictive Transaction Isolation Level Possible 623
Using Temp Tables to Allow Indexing on Working Data 625
Trang 29Chapter 22: Administration 655
The History of SQL Server Management Object Models 706
Trang 30Chapter 24: Data Warehousing 727
Legacy System Functions (a.k.a Global Variables) 754
Trang 36sys.user_token 830
Trang 37I n t r o d u c t i o n
And so we begin anew While the wait for SQL Server 2005 took a ghastly five years, Microsoft has
blessed us (and, no, I’m not being sarcastic!) with SQL Server 2008 in just three short years
It probably shouldn’t be surprising to me that SQL Server 2008 comes up short in terms of marquee
features — the flash and glitz stuff Yet, what I am surprised by is just how many ‘‘little things’’ havemade it into this release While there are some key feature areas (Policy Based Management, for example)that Microsoft can hang their marketing hat on, the most striking new features in SQL Server 2008 are farmore subtle in nature
SQL Server 2008 is jam-packed with a host of seemingly small, but extremely useful smaller additionssuch as:
❑ New, very useful data types (discrete date and time data types as well as support for geospatialdata and hierarchical data representation)
❑ The newMERGEcommand (combining the options ofINSERT,UPDATE, andDELETEall into one
statement, this is sometimes referred to as anUPSERTin other products)
❑ A revamping of Reporting Services to allow for far more elegant reports
❑ Tracking and availability of ‘‘missing’’ index information (noticing at time of optimization that anon-existent index would have been useful had it been there)
And these are just for starters
For those of you that have read the 2005 versions of my books, the change toward the separation of
beginning and professional level content continues The real ‘‘beginning’’ level discussion is now almost
completely moved into its own book (Beginning SQL Server 2008 Programming) There are some topics that
I consider borderline in terms of whether they are a beginner, intermediate, or professional level topicthat I have continued to provide some degree of coverage on, but, with this edition, most all genuinely
beginner content exists solely in the Beginning title (a new appendix has been added at the end of the
book to give extremely short syntax listings and a few examples, but what was hundreds of pages is now
in the tens of pages)
There is, however, good news that has continued to free up even more space, and this has allowed the
Professional title to return to more broad coverage of a wider range of topics This allows me to get closer
to the original goal I had for the Professional book: to give you enough grounding in most of the product
that, even if you couldn’t write at an expert level in each area, you would understand SQL Server as awhole and build a better system, knowing what’s involved in the many areas where SQL Server offersfunctionality, and being prepared to go get even more information if need be
Trang 38Other than that, this book maintains most of the style it has always had We cover most of the
add-on services, as well as advanced programming cadd-onstructs (such as NET assemblies) and some of the
supporting object models (which allow for management of your SQL Server and its various engines)
Version Issues
This book is written for SQL Server 2008 It does, however, maintain roots going back a few versions and
keeps a sharp eye out for backward compatibility issues with SQL Server 2005 and even SQL Server 2000
Prior versions are old enough now where little to no time is spent on them except in passing (in short,
few remain that have even seen SQL Server 6.5 and SQL Server 7.0 was just shy of a decade old at release
of SQL Server 2008)
Who This Book Is For
This book assumes that you have some existing experience with SQL Server and are at an intermediate
to advanced level Furthermore, the orientation of the book is highly developer focused
Aside from a quick reference-oriented appendix, very little coverage is given to beginner level topics It
is assumed you already have experience with data manipulation language (DML) statements, and know
the basics of all the mainstream SQL Server objects (views, stored procedures, user defined functions
and, to a much lesser extent, triggers) If you feel you are ready for more advanced topics, but also feel
that brushing up on the basics can’t hurt, I highly encourage you to check out Beginning SQL Server 2008
Programming, as the two books are now much more designed to work as a pair with some, but relatively
limited, overlap
What This Book Covers
This book is about SQL Server More specifically, it is oriented around developing on SQL Server Most
of the concepts are agnostic to what client language you use, though the examples that leverage a client
language generally do so in C# (A few are shown in more than one language.)
For those of you migrating from earlier versions of SQL Server, some of the ‘‘gotchas’’ that inevitably
exist any time a product has versions are discussed to the extent that they seem to be a genuinely relevant
issue
How This Book Is Str uctured
As is the case for all my books, this book takes something of a lassez faire writing style We roam around a
bit within a relatively loose structure Each chapter begins with an explanation of the things to be covered
in that chapter, and then we go through those items Within each topic covered, some background is
provided, and then we work through an example if appropriate Examples are generally created to be
short, and yet still quickly get at several of the concepts you need for whatever topic is being covered at
the time
Trang 39In terms of ‘‘what to cover next,’’ there is a logical progression We review tools and data types early on(since there are changes there), but move on very fast to topics that assume you are already comfortablewith the product.
To make reasonable use of this book, you will need administrative access to a computer that is capable
of running SQL Server 2008 While I highly recommend using the Developer Edition, the vast majority
of samples and advice applies to virtually all editions of SQL Server I do, however, recommend stayingwith a full version of SQL Server rather than using the Express Edition
Conventions
To help you get the most from the text and keep track of what’s happening, we’ve used a number ofconventions throughout the book
Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.
Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
❑ We highlight new terms and important words when we introduce them.
❑ We show keyboard strokes like this: Ctrl+A
❑ We show file names, URLs, and code within the text like so:persistence.properties
❑ We present code in two different ways:
We use a monofont type with no highlighting for most code examples
We use gray highlighting to emphasize code that’s particularly important in the
present context
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually or
to use the source code files that accompany the book All of the source code used in this book is availablefor download athttp://www.wrox.com Once at the site, simply locate the book’s title (either by usingthe Search box or by using one of the title lists) and click the Download Code link on the book’s detailpage to obtain all the source code for the book
Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is
Trang 40We make every effort to ensure that there are no errors in the text or in the code However, no one is
perfect, and mistakes do occur If you find an error in one of our books, like a spelling mistake or faulty
piece of code, we would be very grateful for your feedback By sending in errata you may save another
reader hours of frustration and at the same time you will be helping us provide even higher quality
information
To find the errata page for this book, go tohttp://www.wrox.comand locate the title using the Search
box or one of the title lists Then, on the book details page, click the Book Errata link On this page you
can view all errata that has been submitted for this book and posted by Wrox editors A complete book
list including links to each book’s errata is also available atwww.wrox.com/misc-pages/booklist.shtml
If you don’t spot ‘‘your’’ error on the Book Errata page, go towww.wrox.com/contact/techsupport
.shtmland complete the form there to send us the error you have found We’ll check the information
and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions
of the book
p2p.wrox.com
For author and peer discussion, join the P2P forums atp2p.wrox.com The forums are a Web-based
system for you to post messages relating to Wrox books and related technologies and interact with other
readers and technology users The forums offer a subscription feature to e-mail you topics of interest of
your choosing when new posts are made to the forums Wrox authors, editors, other industry experts,
and your fellow readers are present on these forums
Athttp://p2p.wrox.comyou will find a number of different forums that will help you not only as you
read this book, but also as you develop your own applications To join the forums, just follow these steps:
1. Go top2p.wrox.comand click the Register link
2. Read the terms of use and click Agree
3. Complete the required information to join as well as any optional information you wish to
provide and click Submit
4. You will receive an e-mail with information describing how to verify your account and
com-plete the joining process
You can read messages in the forums without joining P2P but in order to post your own messages, you
must join.
Once you join, you can post new messages and respond to messages other users post You can read
messages at any time on the Web If you would like to have new messages from a particular forum
e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to
questions about how the forum software works as well as many common questions specific to P2P and
Wrox books To read the FAQs, click the FAQ link on any P2P page