Libro La biblia de microsoft sql server 2008 inglés

download Libro La biblia de microsoft sql server 2008 inglés

If you can't read please download the document

Transcript of Libro La biblia de microsoft sql server 2008 inglés

  • 1.Nielsen ast.tex V4 - 07/23/2009 6:17pm Page xxxivMore free ebooks : http://fast-file.blogspot.com

2. Nielsen frs.tex V4 - 07/21/2009 11:34am Page 1Microsoft SQL Server 2008 BiblePaul Nielsenwith Mike Whiteand Uttam ParuiWiley Publishing, Inc.More free ebooks : http://fast-file.blogspot.com 3. Nielsenfrs.texV4 - 07/21/2009 11:34am Page 2 Soli Deo Gloria Paul Nielsen For my wife, Katy, who has been so patient during the long nightsand weekends of research and writing. Mike WhiteTo my wife, Shyama, and my daughters, Noyonika and Niharika. Uttam ParuiMicrosoft SQL Server 2008 BiblePublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.comCopyright 2009 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-0-470-25704-3Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or byany means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted underSections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission ofthe Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright ClearanceCenter, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to thePublisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111River 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 orwarranties with respect to the accuracy or completeness of the contents of this work and specically disclaimall warranties, including without limitation warranties of tness for a particular purpose. No warranty may becreated or extended by sales or promotional materials. The advice and strategies contained herein may notbe suitable for every situation. This work is sold with the understanding that the publisher is not engaged inrendering legal, accounting, or other professional services. If professional assistance is required, the servicesof a competent professional person should be sought. Neither the publisher nor the author shall be liable fordamages arising herefrom. The fact that an organization or Web site is referred to in this work as a citationand/or a potential source of further information does not mean that the author or the publisher endorses theinformation the organization or Web site may provide or recommendations it may make. Further, readersshould be aware that Internet Web sites listed in this work may have changed or disappeared between whenthis work was written and when it is read.For general information on our other products and services please contact our Customer CareDepartment within the United States at (877) 762-2974, outside the United States at (317) 572-3993 orfax (317) 572-4002.Library of Congress Control Number: 2009928744Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons,Inc. and/or its afliates, in the United States and other countries, and may not be used without writtenpermission. Microsoft and SQL Server are registered trademarks of Microsoft Corporation in the United Statesand/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 notbe available in electronic books. More free ebooks : http://fast-file.blogspot.com 4. Nielsenf02.tex V4 - 07/21/200911:24am Page iiiAbout Paul NielsenPaul Nielsen, SQL Server MVP since 2004, focuses on database performance through excellentdesign always normalized, generalized, and data driven. Continuing to push the envelope ofdatabase design, Paul experiments with Object/Relational designs, the open-source T-SQL solution fortransforming SQL Server into an object database.As an entrepreneur, Paul has developed an application that helps nonprot organizations that give hopeto children in developing counties.As a consultant, he has developed small to very large SQL Server databases, and has helped severalthird-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), SQLTeach (Canada), Rocky Mountain Tech Tri-Fecta, ICCM, and numerous user groups. Paul recordedSQL Server 2005 Development with Total Training. He has presented his Smart Database DesignSeminar in the U.S., Canada, U.K., and Denmark. Paul also provides private and public SQL Serverdeveloper and data architecture courses.As a family guy, Paul lives in Colorado Springs with his very sweet wife, Edie, and Dasha, their ve-year-old daughter. He has two adult children: Lauren, who will soon graduate from the University ofColorado at Boulder, to collect scores of apples as an elementary school teacher, and David, who has agenius within him. Pauls hobbies include photography, a little jazz guitar, great movies, and stunt kites.Paul answers reader e-mails at [email protected] links to blogs, Twitter, eNewsletter, seminars and courses, free SQL utilities, links, screencasts, andupdates to this book, visit www.SQLServerBible.com.About the Contributing AuthorsMary Chipman has been writing about databases and database development since SQL Serverversion 6.0. She is best known for the Microsoft Access Developers Guide to SQL Server, which hasmaintained a ve-star ranking on Amazon.com since it was published in 2000. Mary is currently partof the Business Platform Division at Microsoft, where she is dedicated to providing customers withthe information they need to get the most out of Microsofts data access technologies. Prior to joiningMicrosoft, Mary was a founding partner of MCW Technologies, spoke at industry conferences, authoredseveral books, and created award-winning courseware and videos for Application Developers TrainingCompany (www.appdev.com/info.asp?page=experts mchipman). She was awarded MVP statusevery 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 SQLServer 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 Serverfor 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 rst to train and assist in thedevelopment of Microsofts SQL Server support teams in Canada and India. Uttam led the developmentMore free ebooks : http://fast-file.blogspot.com 5. Nielsen f02.tex V4 - 07/21/200911:24am Page iv About the Authors of and successfully completed Microsofts globally coordinated intellectual property for the SQL Server 2005/2008: Failover Clustering workshop. He received his masters degree in computer science from University of Florida at Gainesville and is a Microsoft Certied Trainer (MCT) and Microsoft Certied IT Professional (MCITP): Database Administrator 2008. He can be reached at [email protected]. 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 Microsofts 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. His primary focus is on the development and tuning of custom SQL Serverbased 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 http://sqlblog.com/blogs/john 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 hasnt 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 nds 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 http://msmvps.com/blogs/robfarley and can be reached via e-mail to [email protected]. 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. Hongfeis 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 birthiv More free ebooks : http://fast-file.blogspot.com 6. Nielsen f02.tex V4 - 07/21/200911:24am Page v About the Technical Reviewersto product. For SQL Server 11, Hongfei will continue her role as feature owner of PBM, and is dedicatedto 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 beenconsulting, 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 latestbook is Pro SQL Server 2008 Failover Clustering (Apress, 2009). Before forming Megahirtz in 2007, hemost recently worked for both Microsoft and Avanade, and still continues to work closely with Microsofton various projects, including contributing to the recently published SQL Server 2008 Upgrade TechnicalReference Guide. He can be contacted at [email protected] or via his website at www.sqlha.com.Brian Kelley is a SQL Server author, blogger, columnist, and Microsoft MVP focusing primarily on SQLServer 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 databaseadministrator/architect in order to concentrate on his passion: SQL Server. He can be reached [email protected] Kehayias is a SQL Server MVP and MCITP Database Administrator and Developer, who gotstarted 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 SQLServer in large virtual environments. His primary passion is performance tuning, and he frequentlyrewrites queries for better performance and performs in-depth analysis of index implementation andusage. He can be reached through his blog at http://sqlblog.com/blogs/jonathan 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 completelyfunctional applications from the analysis deliverable on the SQL Server platform. In his sparetime, Hugo likes to share and enhance his knowledge of SQL Server by frequenting newsgroupsand forums, reading and writing books and blogs, and attending and speaking at conferences. Asa result of these activities, he has been awarded MVP status since January 2006. Hugo blogs athttp://sqlblog.com/blogs/hugo_kornelis. He can be reached by e-mail at [email protected] Shaw, ITIL, RHCE, LCP, MCP, has been working in the IT industry for over 10 years. Marcoruns 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 Awardfor 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 in2008 and 2009. Marcos blog is at http://marcoshaw.blogspot.com.Simon Sabine is Database Architect for SQL Know How, a SQL Server Consultancy and Trainingprovider 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 since1998, always focused on high-performance, reliable systems. Simon received the MVP award in2006. He founded the rst free SQL Server conference in the U.K., SQLBits, in 2007, along withother MVPs in the U.K. He is a regular speaker at SQL Server events and maintains a blog atwww.sqlblogcasts.com/blogs/simons. He is married with children and lives in the U.K. You cancontact him at [email protected] Ward is the Chief Technical Architect for WARDY IT Solutions (www.wardyit.com). Peteris an active member in the Australian SQL Server community, and president of the Queensland SQLServer User Group. Peter is a highly regarded speaker at SQL Server events throughout Australia and isa sought-after SQL Server consultant and trainer, providing solutions for some of the largest SQL Serversites in Australia. He has been awarded Microsoft Most Valuable Professional status for his technicalexcellence and commitment to the SQL Server community. v More free ebooks : http://fast-file.blogspot.com 7. Nielsen f03.texV4 - 07/21/2009 11:31am Page viCreditsExecutive EditorEditorial DirectorBob Elliott Robyn B. SieskySenior Project Editor Editorial ManagerAmi Frank SullivanMary Beth WakeeldDevelopment EditorProduction ManagerLori CerretoTim TateLead Technical Editor Vice President and Executive Group PublisherHugo KorneliusRichard SwadleyTechnical Editors Vice President and Executive PublisherJohn Paul CookBarry PruettHilary CotterAssociate PublisherLouis DavidsonJim MinatelRob FarleyHongfei Guo Project Coordinator, CoverAllan HirtLynsey StanfordJonathan KehayiasBrian KelleyProofreaderHugo KorneliusPublication Services, Inc.Simon SabineMarco ShawIndexerPeter WardJack LewisProduction Editor Cover DesignDassi ZeidelMichael E. TrentCopy Editor Cover ImageLuann Rouff Joyce Haughey More free ebooks : http://fast-file.blogspot.com 8. Nielsenf04.texV4 - 07/21/200911:36am Page viiFrom 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 workedstraight through weekends in the SQL Dungeon to nish the book. My rst thank-you must go to mybeautiful 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 adoptionof Dasha from Russia in 2007. Every tiny detail was professional and we couldnt be more pleased. Iencourage every healthy family to adopt an orphan. I know its a stretch, but its well worth it.This was the second book that I did with the same team at Wiley: Bob Elliot, Ami Frank Sullivan, MaryBeth Wakeeld, and Luann Rouff. What an amazing team, and Im sure there are others with whom Ididnt have direct contact. Ami is a pleasure to work with and one of the best editors in the business.Im a lucky author to work with her.Im also lucky enough to be an MVP. By far the best benet of being an MVP is the privatenewsgroup reading the questions and dialogue between the MVPs more brilliant than me andthe 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 insightfulgroup.Kalen Delaney deserves a special acknowledgment. Kalen is a gracious lady with the highest integrity, adeep 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 hesgrown from our respectful and friendly debates as much as I have. And if you ever get a chance to seeus on stage, be sure to ask Louis about denormalization. Hell 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 whats right in the book you should credit thetech editors. I think it would be interesting to publish a book with all the tech editor comments andsuggestions. Some authors dont like it when a tech editor disagrees or nitpicks. Personally, I thinkthats what makes a great tech editor, which is why I picked my friend Hugo Kornelius as the leadtech editor for this book. Hugos a great tech editor, and this book had an incredible team of technicaleditors 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 ve times!), Jonathan Kehayias,Simon Sabin, Hilary Cotter, Hongfei Guo, Peter Ward, Allan Hirt, John Paul Cook, Brian Kelley, RobFarley, and Marco Shaw. Im also honored to acknowledge the many comments, recommendations,and encouragement Ive received from loyal readers. A few readers volunteered to help me polish thisedition by serving as a pre-editorial board, adding signicant comments and feedback to early versionsvii More free ebooks : http://fast-file.blogspot.com 9. Nielsenf04.texV4 - 07/21/200911:36amPage 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 Barbosa, Mesut Demir, Denis Gobo, Dominique Verri` re, Erin Welker, Henry S. Hayden, James Beidleman, Joe Webb, Ken Scott, Kevin Cox, Kevine 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 whos joined me in these settings, thanks for your participation and enthusiasm. To the many who contributed efforts 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 Wakeeld, 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 theres a fair wind outside somewhere and Im going to nd it. From Uttam Parui: I would like to thank my parents for their endless love and support and for giving me the best education they could provide, which has made me successful in life. Id 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 book, 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 More free ebooks : http://fast-file.blogspot.com 10. Nielsen CAG.texV3 - 07/10/2009 2:37pm Page ixForeword ...................................................................................................................................................xxxiiiIntroduction ............................................................................................................................................... xxxvPart I Laying the FoundationChapter 1: The World of SQL Server ................................................................................................................................. 3Chapter 2: Data Architecture ............................................................................................................................................. 27Chapter 3: Relational Database Design ..............................................................................................................................43Chapter 4: Installing SQL Server 2008 ............................................................................................................................. 73Chapter 5: Client Connectivity .......................................................................................................................................... 93Chapter 6: Using Management Studio ............................................................................................................................ 101Chapter 7: Scripting with PowerShell ............................................................................................................................. 129Part II Manipulating Data with SelectChapter 8: Introducing Basic Query Flow ......................................................................................................................167Chapter 9: Data Types, Expressions, and Scalar Functions ...........................................................................................197Chapter 10: Merging Data with Joins and Unions .........................................................................................................227Chapter 11: Including Data with Subqueries and CTEs ................................................................................................259Chapter 12: Aggregating Data ..........................................................................................................................................289Chapter 13: Windowing and Ranking ............................................................................................................................ 319Chapter 14: Projecting Data Through Views .................................................................................................................. 329Chapter 15: Modifying Data ............................................................................................................................................ 347Chapter 16: Modication Obstacles ................................................................................................................................ 377Part III Beyond RelationalChapter 17: Traversing Hierarchies ................................................................................................................................. 399Chapter 18: Manipulating XML Data .............................................................................................................................. 435Chapter 19: Using Integrated Full-Text Search .............................................................................................................. 491Part IV Developing with SQL ServerChapter 20: Creating the Physical Database Schema ..................................................................................................... 513Chapter 21: Programming with T-SQL ...........................................................................................................................559Chapter 22: Kill the Cursor! ............................................................................................................................................579Chapter 23: T-SQL Error Handling ................................................................................................................................ 593Chapter 24: Developing Stored Procedures .................................................................................................................... 607Chapter 25: Building User-Dened Functions ................................................................................................................623Chapter 26: Creating DML Triggers ................................................................................................................................635Chapter 27: DDL Triggers ............................................................................................................................................... 657Chapter 28: Building Out the Data Abstraction Layer ...................................................................................................665Chapter 29: Dynamic SQL and Code Generation ..........................................................................................................673Part V Data ConnectivityChapter 30: Bulk Operations ...........................................................................................................................................685Chapter 31: Executing Distributed Queries .................................................................................................................... 691Chapter 32: Programming with ADO.NET 3.5 .............................................................................................................. 715Chapter 33: Sync Framework .......................................................................................................................................... 751Chapter 34: LINQ ............................................................................................................................................................ 775ix More free ebooks : http://fast-file.blogspot.com 11. NielsenCAG.texV3 - 07/10/20092:37pmPage xContents at a GlanceChapter 35: Asynchronous Messaging with Service Broker ...........................................................................................807Chapter 36: Replicating Data ...........................................................................................................................................813Chapter 37: Performing ETL with Integration Services ................................................................................................. 829Chapter 38: Access as a Front End to SQL Server ........................................................................................................867Part VI Enterprise Data ManagementChapter 39: Conguring SQL Server .............................................................................................................................. 883Chapter 40: Policy-Based Management ........................................................................................................................... 939Chapter 41: Recovery Planning ....................................................................................................................................... 953Chapter 42: Maintaining the Database ............................................................................................................................985Chapter 43: Automating Database Maintenance with SQL Server Agent ................................................................... 1011Chapter 44: Transferring Databases .............................................................................................................................. 1039Chapter 45: Database Snapshots ................................................................................................................................... 1059Chapter 46: Log Shipping ..............................................................................................................................................1069Chapter 47: Database Mirroring .................................................................................................................................... 1091Chapter 48: Clustering ...................................................................................................................................................1119Part VII SecurityChapter 49: Authenticating Principals ...........................................................................................................................1169Chapter 50: Authorizing Securables .............................................................................................................................. 1187Chapter 51: Data Cryptography .................................................................................................................................... 1197Chapter 52: Row-Level Security .................................................................................................................................... 1205Part VIII Monitoring and AuditingChapter 53: Data Audit Triggers ................................................................................................................................... 1223Chapter 54: Schema Audit Triggers .............................................................................................................................. 1233Chapter 55: Performance Monitor .................................................................................................................................1237Chapter 56: Tracing and Proling .................................................................................................................................1243Chapter 57: Wait States ................................................................................................................................................. 1255Chapter 58: Extended Events ........................................................................................................................................ 1261Chapter 59: Change Tracking ........................................................................................................................................1267Chapter 60: Change Data Capture ................................................................................................................................ 1285Chapter 61: SQL Audit .................................................................................................................................................. 1297Chapter 62: Management Data Warehouse .................................................................................................................. 1305Part IX Performance Tuning and OptimizationChapter 63: Interpreting Query Execution Plans ......................................................................................................... 1313Chapter 64: Indexing Strategies .....................................................................................................................................1321Chapter 65: Query Plan Reuse ...................................................................................................................................... 1357Chapter 66: Managing Transactions, Locking, and Blocking ...................................................................................... 1363Chapter 67: Data Compression ..................................................................................................................................... 1415Chapter 68: Partitioning .................................................................................................................................................1427Chapter 69: Resource Governor .................................................................................................................................... 1453Part X Business IntelligenceChapter 70: BI Design ....................................................................................................................................................1461Chapter 71: Building Multidimensional Cubes with Analysis Services .......................................................................1469Chapter 72: Programming MDX Queries ......................................................................................................................1509Chapter 73: Authoring Reports with Reporting Services ............................................................................................. 1527Chapter 74: Administering Reporting Services ............................................................................................................. 1559Chapter 75: Analyzing Data with Excel ........................................................................................................................1577Chapter 76: Data Mining with Analysis Services ......................................................................................................... 1593Appendix A: SQL Server 2008 Specications ..........................................................................................1613Appendix B: Using the Sample Databases ................................................................................................1619Index ..........................................................................................................................................................1625xMore free ebooks : http://fast-file.blogspot.com 12. Nielsen ftoc.tex V4 - 07/21/20093:36pmPage xiForeword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiiiIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxvPart I Laying the FoundationChapter 1: The World of SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 A Great Choice ...................................................................................................................................................................................4 SQL Server Database Engine ............................................................................................................................................................. 6 Database Engine ....................................................................................................................................................................6 Transact-SQL ......................................................................................................................................................................... 8 Policy-Based Management .................................................................................................................................................. 10 .NET Common Language Runtime ................................................................................................................................... 10 Service Broker ..................................................................................................................................................................... 11 Replication services .............................................................................................................................................................11 Integrated Full-Text Search ................................................................................................................................................11 Server management objects ................................................................................................................................................12 Filestream ............................................................................................................................................................................ 12 SQL Server Services ......................................................................................................................................................................... 12 SQL Server Agent ............................................................................................................................................................... 12 Database Mail ......................................................................................................................................................................12 Distributed Transaction Coordinator (DTC) .....................................................................................................................12 Business Intelligence .........................................................................................................................................................................14 Business Intelligence Development Studio ........................................................................................................................14 Integration Services .............................................................................................................................................................14 Analysis Services ................................................................................................................................................................. 15 Reporting Services ...............................................................................................................................................................17 UI and Tools .................................................................................................................................................................................... 17 SQL Server Management Studio ........................................................................................................................................18 SQL Server Conguration Manager ...................................................................................................................................18 SQL Proler/Trace ...............................................................................................................................................................19 Performance Monitor ..........................................................................................................................................................19 Command-line utilities ....................................................................................................................................................... 19 Books Online .......................................................................................................................................................................20 SQL Server Editions .........................................................................................................................................................................20 Exploring the Metadata ....................................................................................................................................................................22 System databases .................................................................................................................................................................22 Metadata views ....................................................................................................................................................................22 Whats New? .....................................................................................................................................................................................23 Summary ........................................................................................................................................................................................... 26Chapter 2: Data Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Information Architecture Principle ..................................................................................................................................................28Database Objectives ..........................................................................................................................................................................28Usability ...............................................................................................................................................................................29Extensibility ......................................................................................................................................................................... 29Data integrity .......................................................................................................................................................................30Performance/scalability ........................................................................................................................................................31Availability ...........................................................................................................................................................................31Security ................................................................................................................................................................................31Smart Database Design .....................................................................................................................................................................33Database system .................................................................................................................................................................. 34Physical schema .................................................................................................................................................................. 36 xi More free ebooks : http://fast-file.blogspot.com 13. Nielsen ftoc.tex V4 - 07/21/2009 3:36pmPage xiiContentsSet-based queries ................................................................................................................................................................ 37Indexing ...............................................................................................................................................................................37Concurrency ........................................................................................................................................................................ 38Advanced scalability ............................................................................................................................................................38A performance framework ................................................................................................................................................. 39Issues and objections ..........................................................................................................................................................40Summary ........................................................................................................................................................................................... 40Chapter 3: Relational Database Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Database Basics ................................................................................................................................................................................. 43 Benets of a digital database .............................................................................................................................................44 Tables, rows, columns ........................................................................................................................................................45 Database design phases ...................................................................................................................................................... 46 Normalization ......................................................................................................................................................................47 The three Rules of One .................................................................................................................................................. 47 Identifying entities .............................................................................................................................................................. 48 Generalization ......................................................................................................................................................................49 Primary keys ....................................................................................................................................................................... 51 Foreign keys ........................................................................................................................................................................52 Cardinality ........................................................................................................................................................................... 52 Optionality ...........................................................................................................................................................................52 Data Design Patterns ........................................................................................................................................................................55 One-to-many pattern .......................................................................................................................................................... 55 One-to-one pattern ............................................................................................................................................................. 56 Many-to-many pattern ........................................................................................................................................................56 Supertype/subtype pattern ..................................................................................................................................................59 Domain integrity lookup pattern .......................................................................................................................................61 Recursive pattern ................................................................................................................................................................ 61 Database design layers ........................................................................................................................................................65 Normal Forms ...................................................................................................................................................................................65 First normal form (1NF) ....................................................................................................................................................66 Second normal form (2NF) ............................................................................................................................................... 67 Third normal form (3NF) ..................................................................................................................................................69 The Boyce-Codd normal form (BCNF) .............................................................................................................................70 Fourth normal form (4NF) ................................................................................................................................................70 Fifth normal form (5NF) ................................................................................................................................................... 71 Summary ........................................................................................................................................................................................... 71Chapter 4: Installing SQL Server 2008 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Selecting Server Hardware ............................................................................................................................................................... 73CPU planning ......................................................................................................................................................................73Copious memory .................................................................................................................................................................74Disk-drive subsystems ........................................................................................................................................................ 74Network performance .........................................................................................................................................................76 Preparing the Server .........................................................................................................................................................................78Dedicated server ..................................................................................................................................................................78Operating system ................................................................................................................................................................ 79Service accounts ..................................................................................................................................................................79Server instances ...................................................................................................................................................................79 Performing the Installation .............................................................................................................................................................. 81Attended installations ......................................................................................................................................................... 81Unattended installations ..................................................................................................................................................... 85Remote installations ............................................................................................................................................................86 Upgrading from Previous Versions ................................................................................................................................................. 86Upgrading from SQL Server 2005 ....................................................................................................................................87 Migrating to SQL Server ..................................................................................................................................................................87Migrating from Access ........................................................................................................................................................87Migration Assistant ............................................................................................................................................................. 88 Removing SQL Server ...................................................................................................................................................................... 90 Summary ........................................................................................................................................................................................... 91Chapter 5: Client Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Enabling Server Connectivity ...........................................................................................................................................................93 Server Conguration Manager ........................................................................................................................................... 94 SQL Native Client Connectivity (SNAC) ..........................................................................................................................95xii More free ebooks : http://fast-file.blogspot.com 14. Nielsen ftoc.tex V4 - 07/21/2009 3:36pm Page xiiiContentsSQL Server Native Client Features ................................................................................................................................................. 96 Requirements .......................................................................................................................................................................97 Asynchronous operations ................................................................................................................................................... 97 Multiple Active Result Sets (MARS) ..................................................................................................................................97 XML data types ...................................................................................................................................................................98 User-dened types .............................................................................................................................................................. 98 Large value types ................................................................................................................................................................98 Handling expired passwords ..............................................................................................................................................98 Snapshot isolation ...............................................................................................................................................................99Summary ........................................................................................................................................................................................... 99Chapter 6: Using Management Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Organizing the Interface ................................................................................................................................................................ 104Window placement ...........................................................................................................................................................104The Context Menu ........................................................................................................................................................... 106 Registered Servers ...........................................................................................................................................................................107Managing Servers ..............................................................................................................................................................107Server Groups ................................................................................................................................................................... 109 Object Explorer .............................................................................................................................................................................. 110Navigating the tree ........................................................................................................................................................... 110Filtering Object Explorer ................................................................................................................................................. 113Object Explorer Details ....................................................................................................................................................113The Table Designer .......................................................................................................................................................... 114Building database diagrams ..............................................................................................................................................115The Query Designer ......................................................................................................................................................... 116Object Explorer reports ....................................................................................................................................................118 Using the Query Editor .................................................................................................................................................................119Opening a query connecting to a server ....................................................................................................................... 119Opening a .sql le ........................................................................................................................................................... 119Shortcuts and bookmarks ................................................................................................................................................ 121Query options ................................................................................................................................................................... 122Executing SQL batches .....................................................................................................................................................123Results! .............................................................................................................................................................................. 123Viewing query execution plans ....................................................................................................................................... 123 Using the Solution Explorer ..........................................................................................................................................................125 Jump-Starting Code with Templates .............................................................................................................................................126Using templates .................................................................................................................................................................126Managing templates .......................................................................................................................................................... 126 Summary ......................................................................................................................................................................................... 126Chapter 7: Scripting with PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Why Use PowerShell? .................................................................................................................................................................... 130 Basic PowerShell .............................................................................................................................................................................130Language features ..............................................................................................................................................................130Creating scripts ................................................................................................................................................................. 137 Communicating with SQL Server ................................................................................................................................................. 142SQL Server Management Objects ....................................................................................................................................142ADO.NET .......................................................................................................................................................................... 147 Scripting SQL Server Tasks ...........................................................................................................................................................150Administrative tasks ..........................................................................................................................................................150Data-based tasks ............................................................................................................................................................... 159 SQL Server PowerShell Extensions ............................................................................................................................................... 161SQLPS.exe ..........................................................................................................................................................................161The SQL PSDrive SQLSERVER: .................................................................................................................................162SQL cmdlets ......................................................................................................................................................................162 Summary ......................................................................................................................................................................................... 164Part II Manipulating Data with SelectChapter 8: Introducing Basic Query Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Understanding Query Flow ........................................................................................................................................................... 168 Syntactical ow of the query statement ......................................................................................................................... 168 A graphical view of the query statement .......................................................................................................................169 xiiiMore free ebooks : http://fast-file.blogspot.com 15. Nielsenftoc.tex V4 - 07/21/2009 3:36pmPage xivContentsLogical ow of the query statement ...............................................................................................................................170Physical ow of the query statement ............................................................................................................................. 171From Clause Data Sources ............................................................................................................................................................ 171Possible data sources ........................................................................................................................................................171Table aliases ...................................................................................................................................................................... 173[Table Name] .................................................................................................................................................................... 173Fully qualied names .......................................................................................................................................................174Where Conditions .......................................................................................................................................................................... 175Using the between search condition ...............................................................................................................................176Comparing with a list ......................................................................................................................................................176Using the like search condition ...................................................................................................................................... 179Multiple where conditions ............................................................................................................................................... 181Select...where .....................................................................................................................................................................182Columns, Stars, Aliases, and Expressions .................................................................................................................................... 183The star ............................................................................................................................................................................. 183Aliases ................................................................................................................................................................................183Qualied columns .............................................................................................................................................................184Ordering the Result Set .................................................................................................................................................................185Specifying the order by using column names ...............................................................................................................185Specifying the order by using expressions .....................................................................................................................187Specifying the order by using column aliases ............................................................................................................... 188Using the column ordinal position .................................................................................................................................188Order by and collation .................................................................................................................................................... 189Select Distinct ................................................................................................................................................................................. 191Top () ..............................................................................................................................................................................................192The with ties option ........................................................................................................................................................ 193Selecting a random row ...................................................................................................................................................194Summary ......................................................................................................................................................................................... 195Chapter 9: Data Types, Expressions, and Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . 197 Building Expressions ...................................................................................................................................................................... 197 Operators ...........................................................................................................................................................................198 Bitwise operators ...............................................................................................................................................................199 Case expressions ............................................................................................................................................................... 202 Working with nulls .......................................................................................................................................................... 204 Scalar Functions ............................................................................................................................................................................. 209 User information functions .............................................................................................................................................. 210 Date and time functions .................................................................................................................................................. 210 String Functions ............................................................................................................................................................................. 214 Soundex Functions .........................................................................................................................................................................218 Using the SOUNDEX() function ..................................................................................................................................... 220 Using the DIFFERENCE() Soundex function .................................................................................................................221 Data-Type Conversion Functions .................................................................................................................................................. 222 Server Environment Information ...................................................................................................................................................224 Summary ......................................................................................................................................................................................... 225Chapter 10: Merging Data with Joins and Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 Using Joins ......................................................................................................................................................................................228 Inner Joins ...................................................................................................................................................................................... 230Building inner joins with the Query Designer .............................................................................................................. 231Creating inner joins within SQL code ........................................................................................................................... 231Number of rows returned ................................................................................................................................................233ANSI SQL 89 joins .......................................................................................................................................................... 234Multiple data source joins ............................................................................................................................................... 235 Outer Joins ......................................................................................................................................................................................236Using the Query Designer to create outer joins ........................................................................................................... 238T-SQL code and outer joins ............................................................................................................................................238Outer joins and optional foreign keys ........................................................................................................................... 240Full outer joins .................................................................................................................................................................241Red thing blue thing ........................................................................................................................................................241Placing the conditions within outer joins ......................................................................................................................243Multiple outer joins ..........................................................................................................................................................244 Self-Joins ..........................................................................................................................................................................................244 Cross (Unrestricted) Joins ..............................................................................................................................................................247xivMore free ebooks : http://fast-file.blogspot.com 16. Nielsen ftoc.tex V4 - 07/21/20093:36pmPage xv ContentsExotic Joins .....................................................................................................................................................................................248 Multiple-condition joins ................................................................................................................................................... 248(theta) joins ..................................................................................................................................................................249 Non-key joins ................................................................................................................................................................... 249Set Difference Queries ....................................................................................................................................................................250 Left set difference query .................................................................................................................................................. 251 Full set difference queries ................................................................................................................................................252Using Unions ..................................................................................................................................................................................254 Union [All] ........................................................................................................................................................................254 Intersection union .............................................................................................................................................................255 Difference union/except ....................................................................................................................................................256Summary ......................................................................................................................................................................................... 257Chapter 11: Including Data with Subqueries and CTEs . . . . . . . . . . . . . . . . . . . . . . . . . 259 Methods and Locations ..................................................................................................................................................................259 Simple Subqueries .......................................................................................................................................................................... 262 Common table expressions .............................................................................................................................................. 264 Using scalar subqueries ....................................................................................................................................................265 Using subqueries as lists ..................................................................................................................................................267 Using subqueries as tables ...............................................................................................................................................271 Row constructors .............................................................................................................................................................. 273 All, some, and any ...........................................................................................................................................................274 Correlated Subqueries .................................................................................................................................................................... 276 Correlating in the where clause ......................................................................................................................................276 Correlating a derived table using apply .........................................................................................................................280 Relational Division ..........................................................................................................................................................................281 Relational division with a remainder ..............................................................................................................................282 Exact relational division ...................................................................................................................................................285 Composable SQL ............................................................................................................................................................................286 Summary ......................................................................................................................................................................................... 288Chapter 12: Aggregating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 Simple Aggregations ....................................................................................................................................................................... 289 Basic aggregations ............................................................................................................................................................. 290 Aggregates, averages, and nulls ....................................................................................................................................... 293 Using aggregate functions within the Query Designer ..................................................................................................293 Beginning statistics ............................................................................................................................................................294 Grouping within a Result Set ....................................................................................................................................................... 295 Simple groupings .............................................................................................................................................................. 296 Grouping sets ....................................................................................................................................................................297 Filtering grouped results ..................................................................................................................................................298 Aggravating Queries ....................................................................................................................................................................... 299 Including group by descriptions ..................................................................................................................................... 299 Including all group by values ......................................................................................................................................... 301 Nesting aggregations .........................................................................................................................................................303 Including detail descriptions ............................................................................................................................................304 OLAP in the Park .......................................................................................................................................................................... 306 Rollup subtotals ................................................................................................................................................................ 306 Cube queries ..................................................................................................................................................................... 308 Building Crosstab Queries ............................................................................................................................................................. 309 Pivot method .....................................................................................................................................................................309 Case expression method ...................................................................................................................................................311 Dynamic crosstab queries ................................................................................................................................................ 312 Unpivot ..............................................................................................................................................................................313 Cumulative Totals (Running Sums) ..............................................................................................................................................314 Correlated subquery solution ...........................................................................................................................................315 T-SQL cursor solution ......................................................................................................................................................315 Multiple assignment variable solution .............................................................................................................................316 Summary ......................................................................................................................................................................................... 317Chapter 13: Windowing and Ranking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 Windowing ......................................................................................................................................................................................319The Over() clause .............................................................................................................................................................320Partitioning within the window ...................................................................................................................................... 321xvMore free ebooks : http://fast-file.blogspot.com 17. Nielsen ftoc.tex V4 - 07/21/20093:36pmPage xviContentsRanking Functions ..........................................................................................................................................................................322 Row number() function ................................................................................................................................................... 322 Rank() and dense_rank() functions .................................................................................................................................324 Ntile() function ................................................................................................................................................................. 325 Aggregate Functions ......................................................................................................................................................... 326Summary ......................................................................................................................................................................................... 327Chapter 14: Projecting Data Through Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 Why Use Views? ............................................................................................................................................................................ 329 The Basic View ...............................................................................................................................................................................331Creating views using the Query Designer ......................................................................................................................332Creating views with DDL code .......................................................................................................................................334Executing views ................................................................................................................................................................ 334Altering and dropping a view .........................................................................................................................................336 A Broader Point of View ............................................................................................................................................................... 336Column aliases ..