Kellenberger Beginning T-SQL 2008 Companion eBook Available trim = 7.5" x 9.25" spine = 0.875" 464 page count The experT’s Voice ® in sQL serVer Beginning T-SQL 2008 Kathi Kellenberger Quickly move beyond beginner status with this step-by-step approach to learning T-SQL this print for content only—size & color not accurate Books for professionaLs By professionaLs ® cyan MaGenTa yeLLoW BLack Beginning T-SQL 2008 Dear Reader, Transact-SQL (T-SQL) is the language used to retrieve and manipulate data in a SQL Server database, and it’s the programming language that I use most often in my job as a SQL Server DBA. T-SQL is really far more than just a simple query language involving statements such as SELECT and UPDATE. T-SQL is a full- fledged programming language that allows you to use SQL Server in some very powerful ways. It allows you to write stored code that executes in the database, allows you to centralize business logic in the database, and quite frankly is the key to utilizing SQL Server. Using SQL Server without knowing T-SQL is like try- ing to ride a bicycle without attaching the pedals. Beginning T-SQL 2008 is organized so that each section and chapter builds upon what comes before it. Instead of showing you every possible option when I introduce a new statement or topic, each section covers a single concept, and those concepts lead you one step at a time toward mastery of the language. Almost every section in the book contains a code example, and I encourage you to type in and execute each example to help you learn. I also encourage you to experiment with these examples or to come up with your own. Most of the chapters have exercises giving you the chance to work out the solution. Take the time to complete the exercises because that is how you will learn. Without pedals, you might get your bike to move, but you’ll go much faster and more efficiently if you attach the pedals. Go ahead. Put on your pedals. Learn T-SQL. Kathi Kellenberger, SQL Server MVP, MCT Coauthor of Professional SQL Server 2005 Integration Services (Wrox) US $39.99 Shelve in Databases / SQL Server User level: Beginner THE APRESS ROADMAP Expert SQL Server 2008 Development SQL Server 2008 Query Performance Tuning Pro PHP: Patterns, Frameworks, Testing, and More Pro T-SQL 2008 Programmer’s Guide SQL Server 2008 Transact-SQL Recipes Advanced Joomla! Beginning T-SQL 2008 Beginning SQL Queries Beginning Joomla! Second Edition www.apress.com SOURCE CODE ONLINE Companion eBook See last page for details on $10 eBook version ISBN 978-1-4302-2461-7 9 781430 224617 5 39 9 9 .875 i Beginning T-SQL 2008 ■ ■ ■ Kathi Kellenberger ii Beginning T-SQL 2008 Copyright © 2009 by Kathi Kellenberger All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2461-7 ISBN-13 (electronic): 978-1-4302-2462-4 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Java™ and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the US and other countries. Apress, Inc., is not affiliated with Sun Microsystems, Inc., and this book was written without endorsement from Sun Microsystems, Inc. Lead Editors: Jonathan Gennick, Douglas Pundick Technical Reviewer: Ken Simmons Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Project Manager: Kylie Johnston Copy Editor: Kim Wimpsett Production Support: Patrick Cunningham Indexer: BIM Indexing Artist: April Milne Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or visit http://www.springeronline.com. For information on translations, please contact Apress directly at 233 Spring Street, New York, NY 10013. E-mail info@apress.com, or visit http://www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at http://www.apress.com. iii This book is dedicated to Thomas Indiana, the most joyful person I have ever known. In his first three years, he has taught me to appreciate every moment of my life. iv v Contents at a Glance ■Contents at a Glance v ■Contents vi ■About the Author xviii ■About the Technical Reviewer xix ■Acknowledgments xx ■Introduction xxi ■Chapter 1: Getting Started 1 ■Chapter 2: Writing Simple SELECT Queries 37 ■Chapter 3: Using Functions and Expressions 79 ■Chapter 4: Querying Multiple Tables 117 ■Chapter 5: Grouping and Summarizing Data 151 ■Chapter 6: Manipulating Data 183 ■Chapter 7: Understanding T-SQL Programming Logic 221 ■Chapter 8: Moving Logic to the Database 269 ■Chapter 9: Working with New Data Types 317 ■Chapter 10: Writing Advanced Queries 343 ■Chapter 11: Where to Go Next? 375 ■Appendix: Solutions to the Exercises 379 ■Index 427 vi vii Contents ■Contents at a Glance v ■Contents vi ■About the Author xviii ■About the Technical Reviewer xix ■Acknowledgments xx ■Introduction xxi ■Chapter 1: Getting Started 1 Installing SQL Server Express Edition 1 Installing the Sample Databases 12 Installing Books Online 16 Using Books Online 17 Using SQL Server Management Studio 19 Launching SQL Server Management Studio 20 Running Queries 21 Exploring Database Concepts 26 What Is SQL Server? 26 Database As Container 28 Data Is Stored in Tables 29 Data Types 30 Normalization 31 Understanding Indexes 33 Database Schemas 34 Summary 35 ■ CONTENTS viii ■Chapter 2: Writing Simple SELECT Queries 37 Using the SELECT Statement 37 Selecting a Literal Value 37 Retrieving from a Table 38 Generating a Select-List 40 Mixing Literals and Column Names 42 Filtering Data 43 Adding a WHERE Clause 43 Using WHERE Clauses with Alternate Operators 45 Using BETWEEN 48 Using NOT BETWEEN 49 Filtering On Date and Time 51 Pattern Matching with LIKE 53 Restricting the Characters in Pattern Matches 54 Combining Wildcards 56 Using WHERE Clauses with Two Predicates 58 Using WHERE Clauses with Three or More Predicates 58 Using NOT with Parentheses 60 Using the IN Operator 62 Working with Nothing 63 Performing a Full-Text Search 65 Using CONTAINS 66 Using Multiple Terms with CONTAINS 67 Searching Multiple Columns 68 Using FREETEXT 69 Sorting Data 70 Thinking About Performance 72 Taking Advantage of Indexes 72 Viewing Execution Plans 74 Summary 77 ■Chapter 3: Using Functions and Expressions 79 Expressions Using Operators 79 Concatenating Strings 79 Concatenating Strings and NULL 80 [...]... that I write this book xix Introduction Welcome to Beginning T-SQL 2008 This book introduces you to the language known as T-SQL, also called Transact-SQL It’s the fundamental language that you need to know in order to work productively with Microsoft’s database management system known as SQL Server Almost everything that you do in SQL Server boils down to T-SQL commands, whether you write them yourself... you are reading this book, you probably know what T-SQL is T-SQL, also known as Transact-SQL, is Microsoft’s implementation of the Structured Query Language (SQL) for SQL Server T-SQL is the language that is most often used to extract or modify data that is stored in a SQL Server database, regardless of the application or tool used SQL Server 2008 T-SQL is based on standards created by the American... features of T-SQL that you can use to create scripts and database objects so you can do more with T-SQL than just write single statements Finally, I introduce you to some new, more advanced T-SQL features so that you can take advantage of cutting-edge techniques that many developers haven’t even heard about Almost everything in SQL Server boils down to T-SQL sooner or later Don’t think you can escape T-SQL. .. your chance to really shine–if you know T-SQL Those who understand T-SQL can look at what a tool or a utility is doing and understand why the generated code is failing Those without T-SQL knowledge will be seeking you out, because you’ll be the one to diagnose and solve the problem You’ll also be able to get work done without fancy and expensive tool sets With T-SQL, you can be productive in almost... myself helping developers write T-SQL code These developers usually know how to write simple queries, but they might need help writing an outer join or can’t figure out which columns belong in the GROUP BY clause I have also had the pleasure of teaching T-SQL to a few individuals who had never written a query before This book is targeted to both groups: those with a bit of T-SQL experience and those who... never written a query before This book is targeted to both groups: those with a bit of T-SQL experience and those who are absolute beginners when it comes to T-SQL How This Book Is Structured About a year ago I got the opportunity to teach beginning T-SQL to a group of a dozen students The catch was that I had to write the courseware in addition to teaching it Because of that experience, the idea for this... is a simple example of a T-SQL statement It’s a simple query to list all the databases hosted on SQL Server: SELECT name FROM sys.databases; I wrote this book because I love working with T-SQL and love teaching others how to use it I was introduced to SQL Server in the run up to year 2000 I was enamored with the power of SQL Server and with the expressiveness built into the T-SQL language The amount... son, Nathan, and can often be found on a cruise ship, at a Disney resort, or on the beach in his hometown of Pensacola, Florida xviii Acknowledgments When I was first approached by Apress to write a beginning T-SQL book, it was important to me to write the book myself When I say that, I mean that it was important to me to be the only author on this book Of course, I know that it takes many dedicated people... give you an example to type in and execute, and then explain the results You will also find exercises in Chapters 2 through 8 to reinforce what you have just learned If you are new to T-SQL, you will probably read this book beginning with Chapter 1 and continue to Chapter 11 You might just want to keep the book around as a reference to look up concepts that you don’t use on a daily basis Either way, the... will need to modify data as well as retrieve it, this chapter teaches how to insert new rows and update or delete existing rows xxi ■ INTRODUCTION Chapter 7, “Understanding T-SQL Programming Logic”: This chapter demonstrates that T-SQL is more than just data retrieval and manipulation by teaching how to create scripts with programming logic Chapter 8, “Moving Logic to the Database”: This chapter teaches . Kellenberger Beginning T-SQL 2008 Companion eBook Available trim = 7.5" x 9.25" spine = 0.875" 464 page count The experT’s Voice ® in sQL serVer Beginning T-SQL 2008 Kathi Kellenberger Quickly. learning T-SQL this print for content only—size & color not accurate Books for professionaLs By professionaLs ® cyan MaGenTa yeLLoW BLack Beginning T-SQL 2008 Dear Reader, Transact-SQL (T-SQL) . ROADMAP Expert SQL Server 2008 Development SQL Server 2008 Query Performance Tuning Pro PHP: Patterns, Frameworks, Testing, and More Pro T-SQL 2008 Programmer’s Guide SQL Server 2008 Transact-SQL Recipes Advanced