Tải bản đầy đủ (.pdf) (10 trang)

Hướng dẫn học Microsoft SQL Server 2008 part 1 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1003.68 KB, 10 trang )

Nielsen ffirs.tex V4 - 07/21/2009 11:34am Page 1
Microsoft
®
SQL Server
®
2008
Bible
Paul Nielsen
with Mike White
and Uttam Parui
Wiley Publishing, Inc.
Nielsen ffirs.tex V4 - 07/21/2009 11:34am Page 2
Soli Deo Gloria
— Paul Nielsen
For my wife, Katy, who has been so patient during the long nights
and weekends of research and writing.
—MikeWhite
To my wife, Shyama, and my daughters, Noyonika and Niharika.
— Uttam Parui
Microsoft
®
SQL Server
®
2008 Bible
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
ISBN: 978-0-470-25704-3
Manufactured in the United States of America
10987654321
No part of this publication may be reproduced, stored in a retrieval system or t ransmitted 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, H oboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at ey
.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.
Library of Congress Control Number: 2009928744
Trademarks: Wiley and the Wiley logo 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 r egistered 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.
www.getcoolebook.com
Nielsen f02.tex V4 - 07/21/2009 11:24am Page iii
About Paul Nielsen
Paul Nielsen, SQL Server MVP since 2004, focuses on database performance through excellent
design — always normalized, generalized, and data driven. Continuing to push the envelope of
database design, Paul experiments with Object/Relational designs, the open-source T-SQL solution for
transforming SQL Server into an object database.
As an entrepreneur, Paul has developed an application that helps nonprofit organizations that give hope
to children in developing counties.
As a consultant, he has developed small to very large SQL Server databases, and has helped several
third-party software vendors improve the quality and performance of their databases.
As a presenter, Paul has given talks at Microsoft TechEd, PASS Summits, DevLink (Nashville), SQL
Teach (Canada), Rocky Mountain Tech Tri-Fecta, ICCM, and numerous user groups. Paul recorded
SQL Server 2005 Development with Total Training. He has presented his Smart Database Design
Seminar in the U.S., Canada, U.K., and Denmark. Paul also provides private and public SQL Server
developer and data architecture courses.
As a family guy, Paul lives in Colorado Springs with his very sweet wife, Edie, and Dasha, their five-
year-old daughter. He has two adult children: Lauren, who will soon graduate from the University of
Colorado at Boulder, to collect scores of apples as an elementary school teacher, and David, who has a
genius within him. Paul’s hobbies include photography, a little jazz guitar, great movies, and stunt kites.
Paul answers reader e-mails at
For links to blogs, Twitter, eNewsletter, seminars and courses, free SQL utilities, links, screencasts, and
updates to this book, visit
www.SQLServerBible.com.
About the Contributing Authors

Mary Chipman has been writing about databases and database development since SQL Server
version 6.0. She is best known for the Microsoft Access Developer’s Guide to SQL Server, which has
maintained a five-star ranking on Amazon.com since it was published in 2000. Mary is currently part
of the Business Platform Division at Microsoft, where she is dedicated to providing customers with
the information they need to get the most out of Microsoft’s data access technologies. Prior to joining
Microsoft, Mary was a founding partner of MCW Technologies, spoke at industry conferences, authored
several books, and created award-winning courseware and videos for Application Developers Training
Company (
www.appdev.com/info.asp?page=experts mchipman). She was awarded MVP status
every year from 1995 until she joined Microsoft in 2004. Mary contributed Chapter 38.
Scott Klein is a .Net and SQL Server developer in South Florida and the author of Professional SQL
Server 2005 XML (Programmer to Programmer). Scott contributed chapters 32, 33, and 34.
Uttam Parui is currently a Senior Premier Field Engineer at Microsoft. He has worked with SQL Server
for over 11 years and joined Microsoft nine years ago with the SQL Server Developer Support team.
Additionally, Uttam has assisted with training and mentoring the SQL Customer Support Services (CSS)
and SQL Premier Field Engineering (PFE) teams, and was one of the first to train and assist in the
development of Microsoft’s SQL Server support teams in Canada and India. Uttam led the development
www.getcoolebook.com
Nielsen f02.tex V4 - 07/21/2009 11:24am Page iv
About the Authors
of and successfully completed Microsoft’s globally coordinated intellectual property for the ‘‘SQL Server
2005/2008: Failover Clustering’’ workshop. He received his master’s degree in computer science from
University of Florida at Gainesville and is a Microsoft Certified Trainer (MCT) and Microsoft Certified IT
Professional (MCITP): Database Administrator 2008. He can be reached at
Uttam wrote all but one of the chapters in Part VI, ‘‘Enterprise Data Management,’’ Chapter 39, and
Chapters 41 through 48.
Jacob Sebastian, SQL Server MVP, is a SQL Server Consultant specializing in XML based on
Ahmedabad, India, and has been using SQL Server since version 6.5. Jacob compressed his vast
knowledge of SQL Server and XML into Chapter 18.
Allen White, SQL Server MVP (with a minor in PowerShell), is a SQL Server Trainer with Scalability

Experts. He has worked as a database administrator, architect and developer for over 30 years and blogs
on
www.SQLBlog.com. Allen expressed his passion for PowerShell in Chapter 7.
Michael White has focused on database development and administration since 1992. Concentrating
on Microsoft’s Business Intelligence (BI) tools and applications since 2000, he has architected and
implemented large warehousing and Analysis Services applications, as well as nontraditional applications
of BI tools. After many years in corporate IT and consulting, Mike currently works as a data architect
for IntrinsiQ, LLC. He is a strong advocate for the underused BI toolset and a frequent speaker at SQL
Server user groups and events. Mike wrote Chapter 37 and all the chapters (70 through 76) in Part X,
‘‘Business Intelligence.’’
About the Technical Reviewers
John Paul Cook is a database consultant based in Houston. Hisprimaryfocusisonthedevelopment
and tuning of custom SQL Server–based solutions for large enterprise customers. As a three-time
Microsoft MVP for Virtual Machines, his secondary focus is using virtualization to facilitate application
testing. You can read his blog at
paul cook.
Hilary Cotter has been a SQL Server MVP for eight years and specializes in replication, high availabil-
ity, and full-text search. He lives in New Jersey and loves to play the piano and spend time with his
wife and four kids. He has answered over 17,000 newsgroup questions, some of them correctly.
Louis Davidson has over 15 years of experience as a corporate database developer and architect. He
has been the principal author on four editions of a book on database design, including Professional
SQL Server 2008 Relational Database Design and Implementation. You can get more information about his
books, blogs, and more at his web page, drsql.org.
Rob Farley lives in Adelaide, Australia, where the sun always shines and it hasn’t rained (hardly at all)
for a very long time. He runs the Adelaide SQL Server User Group, operates a SQL Server consultancy
called LobsterPot Solutions, acts as a mentor for SQLskills Australia, and somehow finds time to be mar-
ried with three amazing children. He is originally from the U.K., and his passions include serving at his
church and supporting Arsenal Football Club. He blogs at
/>and can be reached via e-mail to
Hongfei Guo is a senior program manager in the SQL Server Manageability Team. Prior to Microsoft,

she spent six years in database research and earned her PhD from University of Wisconsin at Madison.
Hongfei’s dissertation was ‘‘Data Quality Aware Caching’’ and she implemented it in the SQL Server
Engine code base while interning at Microsoft Research. For the SQL Server 2008 release, Hongfei was a
critical contributor to the Policy-Based Management feature (PBM) and witnessed its journey from birth
iv
www.getcoolebook.com
Nielsen f02.tex V4 - 07/21/2009 11:24am Page v
About the Technical Reviewers
to product. For SQL Server 11, Hongfei will continue her role as feature owner of PBM, and is dedicated
to producing the next version that customers desire.
Allan Hirt has been using SQL Server in various guises since 1992. For the past 10 years, he has been
consulting, training, developing content, speaking at events, as well as authoring books, white papers,
and articles related to SQL Server architecture, high availability, administration, and more. His latest
book is Pro SQL Server 2008 Failover Clustering (Apress, 2009). Before forming Megahirtz in 2007, he
most recently worked for both Microsoft and Avanade, and still continues to work closely with Microsoft
on various projects, including contributing to the recently published SQL Server 2008 Upgrade Technical
Reference Guide. He can be contacted at or via his website at
www.sqlha.com.
Brian Kelley is a SQL Server author, blogger, columnist, and Microsoft MVP focusing primarily on SQL
Server security. He is a contributing author for How to Cheat at Securing SQL Server 2005 (Syngress,
2007) and Professional SQL Server 2008 Administration (Wrox, 2008). Brian currently serves as a database
administrator/architect in order to concentrate on his passion: SQL Server. He can be reached at

Jonathan Kehayias is a SQL Server MVP and MCITP Database Administrator and Developer, who got
started in SQL Server in 2004 as a database developer and report writer in the natural gas industry.
He has experience in upgrading and consolidating SQL environments, and experience in running SQL
Server in large virtual environments. His primary passion is performance tuning, and he frequently
rewrites queries for better performance and performs in-depth analysis of index implementation and
usage. He can be reached through his blog at
kehayias.

Hugo Kornelius, lead technical editor, is co-founder and R&D lead of perFact BV, a Dutch com-
pany that improves analysis methods and develops computer-aided tools to generate completely
functional applications from the analysis deliverable on the SQL Server platform. In his spare
time, Hugo likes to share and enhance his knowledge of SQL Server by frequenting newsgroups
and forums, reading and writing books and blogs, and attending and speaking at conferences. As
a result of these activities, he has been awarded MVP status since January 2006. Hugo blogs at
He can be reached by e-mail at
Marco Shaw, ITIL, RHCE, LCP, MCP, has been working in the IT industry for over 10 years. Marco
runs a Virtual PowerShell User Group, and is one of the community directors of the PowerShell Com-
munity site
www.powershellcommunity.org. Marco recently received the Microsoft MVP Award
for the second year in a row (2008/2009) for contributions to the Windows PowerShell Community.
Included in his recent authoring activities is writing PowerShell content for various books published in
2008 and 2009. Marco’s blog is at
.
Simon Sabine is Database Architect for SQL Know How, a SQL Server Consultancy and Training
provider in the U.K. He has particular expertise in the world of search, distributed architec-
tures, business intelligence, and application development. He has worked with SQL Server since
1998, always focused on high-performance, reliable systems. Simon received the MVP award in
2006. He founded the first free SQL Server conference in the U.K., SQLBits, in 2007, along with
other MVPs in the U.K. He is a regular speaker at SQL Server events and maintains a blog at
www.sqlblogcasts.com/blogs/simons. He is married with children and lives in the U.K. You can
contact him at
Peter Ward is the Chief Technical Architect for WARDY IT Solutions (
www.wardyit.com). Peter
is an active member in the Australian SQL Server community, and president of the Queensland SQL
Server User Group. Peter is a highly regarded speaker at SQL Server events throughout Australia and is
a sought-after SQL Server consultant and trainer, providing solutions for some of the largest SQL Server
sites in Australia. He has been awarded Microsoft Most Valuable Professional status for his technical
excellence and commitment to the SQL Server community.

v
www.getcoolebook.com
Nielsen f03.tex V4 - 07/21/2009 11:31am Page vi
Credits
Executive Editor
Bob Elliott
Senior Project Editor
Ami Frank Sullivan
Development Editor
Lori Cerreto
Lead Technical Editor
Hugo Kornelius
Technical Editors
John Paul Cook
Hilary Cotter
Louis Davidson
Rob Farley
Hongfei Guo
Allan Hirt
Jonathan Kehayias
Brian Kelley
Hugo Kornelius
Simon Sabine
Marco Shaw
Peter Ward
Production Editor
Dassi Zeidel
Copy Editor
Luann Rouff
Editorial Director

Robyn B. Siesky
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Lynsey Stanford
Proofreader
Publication Services, Inc.
Indexer
Jack Lewis
Cover Design
Michael E. Trent
Cover Image
Joyce Haughey
www.getcoolebook.com
Nielsen f04.tex V4 - 07/21/2009 11:36am Page vii
From Paul Nielsen: Of course, any book this size requires the efforts of several people.
Perhaps the greatest effort was made by my family as I spent long days, pulled all-nighters, and worked
straight through weekends in the SQL Dungeon to finish the b ook. My first thank-you must go to my
beautiful wife, Edie, and my kids, Lauren, David, and Dasha for their patience and love.
I also want to thank the folks at European Adoption Consultants who helped us with our adoption
of Dasha f rom Russia in 2007. Every tiny detail was professional and we couldn’t be more pleased. I
encourage every healthy f amily to adopt an orphan. I know it’s a stretch, but it’s well worth it.

This was the second book that I did with the same team at Wiley: Bob Elliot, Ami Frank Sullivan, Mary
Beth Wakefield, and Luann Rouff. What an amazing team, and I’m sure there are others with whom I
didn’t have direct contact. Ami is a pleasure to work with and one o f the best editors in the business.
I’m a lucky author to work with her.
I’m also lucky enough to be an MVP. By far the best benefit of being an M VP is the private
newsgroup — reading the questions and dialogue between the MVPs more brilliant than me and
the Microsoft development team. When Louis, Erland, Aaron, Hugo, Linchi, Alex, Simon, Greg, Denis,
Adam, and, of course, Kalen, and the many others ask a question or dig into an issue, I pay attention.
Whenever the MVPs meet I always feel like a fortunate guest to be among such a smart and insightful
group.
Kalen Delaney deserves a special acknowledgment. Kalen is a gracious lady with the highest integrity, a
deep knowledge of SQL Server, and always a kind word. Thank you, Kalen.
Louis Davidson has become a good friend. We co-present at many conferences and I hope that he’s
grown from our respectful and friendly debates as much as I have. And if you ever get a chance to see
us on stage, be sure to ask Louis about denormalization. He’ll like that.
To the other authors who contributed to this book, I thank you: Mike White, Uttam Parui, Allen White,
Scott Klein, and Jacob Sebastian. Without you the book might not have come out before SQL 11 ships.
For any errors and omissions I take full credit; for what’s right in the book you should credit the
tech editors. I think it would be interesting to publish a book with all the tech editor comments and
suggestions. Some authors don’t like it when a tech editor disagrees or nitpicks. Personally, I think
that’s what makes a great tech editor, which is why I picked my friend Hugo Kornelius as the lead
tech editor for this book. Hugo’s a great tech editor, and this book had an incredible team of technical
editors — all experts, and all went above and beyond in their quest for perfection: Louis Davidson
(who tech edited the chapter on relational database design about five times!), Jonathan Kehayias,
Simon Sabin, Hilary Cotter, Hongfei Guo, Peter Ward, Allan Hirt, John Paul Cook, Brian Kelley, Rob
Farley, and Marco Shaw. I’m also honored to acknowledge the many comments, recommendations,
and encouragement I’ve received from loyal readers. A few readers volunteered to help me polish this
edition by serving as a pre-editorial board, adding significant comments and feedback to early versions
vii
www.getcoolebook.com

Nielsen f04.tex V4 - 07/21/2009 11:36am Page viii
Acknowledgments
of various chapters for this book: JJ Bienn, Viktor Gurevich, Steve Miller, Greg Low, Aaron Bertrand,
Adam Greifer, Alan Horsman, Andrew Novick, Degmar Barb osa, Mesut Demir, Denis Gobo, Dominique
Verri
`
ere, Erin Welker, Henry S. Hayden, James Beidleman, Joe Webb, Ken Scott, Kevin Cox, Kevin
Lambert, Michael Shaya, Michael Wiles, Scott Stonehouse, and Scott Whigham. Thank you, all.
I really enjoy teaching and sharing SQL Server in the classroom, in seminars, at conferences, and on
the street corner. To everyone who’s joined me in these settings, thanks for your participation and
enthusiasm.
To the many who contributed e fforts to the two previous editions, thank you. This work builds on your
foundation.
This was the second book that I did with the same team at Wiley: Bob Elliott, Ami Frank Sullivan, Mary
Beth Wakefield, Dassi Zeidel, and Luann Rouff.
Finally, a warm thank you goes out to the Microsoft SQL Server team in Redmond. Thanks for building
such a great database engine. Thanks for your close relationships with the MVPs. And thanks to those
team members who spent time with me individually: Buck Woody, Hongfei Guo, Ed Lehman.
For those of you who follow me on Twitter and read my daily tweets about writing, this book was pow-
ered by Dr. Pepper. And now, I have a stunt kite that has been in its case far too long — there’s a fair
wind outside somewhere and I’m going to find it.
From Uttam Parui: I would like to thank my parents for their e ndless love and support and for giving
me the best education they could provide, which has made me successful in life. I’d like to thank my
loving wife, Shyama, and my two doting daughters, Noyonika and Niharika, for all their encouragement
and understanding while I spent many nights and weekends working on the book. I would also like to
thank Paul Nielsen, the lead author, for giving me this great opportunity to co-author this b ook, and for
his support throughout the writing of it. Last but not least, I would like to thank everyone at Wiley for
their help with this book.
viii
www.getcoolebook.com

Nielsen CAG.tex V3 - 07/10/2009 2:37pm Page ix
Foreword xxxiii
Introduction xxxv
Part I Laying the Foundation
Chapter 1: The World of SQL Server 3
Chapter 2: Data Architecture
27
Chapter 3: Relational Database Design
43
Chapter 4: I nstalling SQL Server 2008
73
Chapter 5: Client Connectivity
93
Chapter 6: Using Management Studio
101
Chapter 7: Scripting with PowerShell
129
Part II Manipulating Data with Select
Chapter 8: Introducing Basic Query Flow 167
Chapter 9: Data Types, Expressions, and Scalar Functions
197
Chapter 10: Merging Data w ith Joins and Unions
227
Chapter 11: Including Data with Subqueries and CTEs
259
Chapter 12: Aggregating Data
289
Chapter 13: Windowing and Ranking
319
Chapter 14: Projecting Data Through Views

329
Chapter 15: Modifying Data
347
Chapter 16: Modification Obstacles
377
Part III Beyond Relational
Chapter 17: Traversing Hierarchies 399
Chapter 18: Manipulating XML Data
435
Chapter 19: Using Integrated Full-Text Search
491
Part IV Developing with SQL Server
Chapter 20: Creating the Physical Database Schema 513
Chapter 21: Programming with T-SQL
559
Chapter 22: Kill the Cursor!
579
Chapter 23: T-SQL Error Handling
593
Chapter 24: Developing Stored Procedures
607
Chapter 25: Building User-Defined Functions
623
Chapter 26: Creating DML Triggers
635
Chapter 27: DDL Triggers
657
Chapter 28: Building Out the Data Abstraction Layer
665
Chapter 29: Dynamic SQL and Code Generation

673
Part V Data Connectivity
Chapter 30: Bulk Operations 685
Chapter 31: Executing Distributed Queries
691
Chapter 32: Programming with ADO.NET 3.5
715
Chapter 33: Sync Framework
751
Chapter 34: LINQ
775
ix
www.getcoolebook.com

×