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

beginning t-sql 2008 [electronic resource]

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

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 , or
visit .
For information on translations, please contact Apress directly at 233 Spring Street, New York, NY 10013.
E-mail , or visit .
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
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
.

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
■ CONTENTS

ix

ISNULL and COALESCE 81
Concatenating Other Data Types to Strings 82
Using Mathematical Operators 85
Data Type Precedence 87
Using Functions 87
Using String Functions 87
Nesting Functions 95
Using Date Functions 96
Using Mathematical Functions 103
System Functions 106
Using Functions in the WHERE and ORDER BY Clauses 111
Thinking About Performance 113
Using Functions in the WHERE Clause 113
Summary 116

■Chapter 4: Querying Multiple Tables 117
Writing Inner Joins 117
Joining Two Tables 117
Avoiding an Incorrect Join Condition 119
Joining on a Different Column Name 120
Joining on More Than One Column 121
Joining Three or More Tables 123
Writing Outer Joins 125
Using LEFT OUTER JOIN 125
Using RIGHT OUTER JOIN 126
Using OUTER JOIN to Find Rows with No Match 127
Adding a Table to the Right Side of a Left Join 128
Adding a Table to the Left Side of a Left Join 130
FULL OUTER JOIN 132
CROSS JOIN 133
Self-Joins 135
Writing Subqueries 137
Using a Subquery in an IN List 137
Using a Subquery and NOT IN 138
Using a Subquery Containing NULL with NOT IN 139
Writing UNION Queries 140
■ CONTENTS

x

Exploring Derived Tables and Common Table Expressions 143
Using Derived Tables 143
Using Common Table Expressions 145
Using a CTE to Solve a Complicated Join Problem 146
Thinking About Performance 148

Summary 150
■Chapter 5: Grouping and Summarizing Data 151
Aggregate Functions 151
The GROUP BY Clause 153
Grouping on Columns 153
Grouping on Expressions 155
The ORDER BY Clause 157
The WHERE Clause 159
The HAVING Clause 160
DISTINCT 163
Using DISTINCT vs. GROUP BY 163
DISTINCT Within an Aggregate Expression 164
Aggregate Queries with More Than One Table 166
Isolating Aggregate Query Logic 168
Using a Correlated Subquery in the WHERE Clause 168
Inline Correlated Subqueries 170
Using Derived Tables 172
Common Table Expressions 173
Using Derived Tables and CTEs to Display Details 174
The OVER Clause 176
Thinking About Performance 178
Summary 181
■Chapter 6: Manipulating Data 183
Inserting New Rows 183
Adding One Row with Literal Values 184
Avoiding Common Insert Errors 185
Inserting Multiple Rows with One Statement 187
Inserting Rows from Another Table 188
Inserting Missing Rows 190
■ CONTENTS


xi

Creating and Populating a Table in One Statement 191
Inserting Rows into Tables with Default Column Values 193
Inserting Rows into Tables with Automatically Populating Columns 194
Deleting Rows 198
Using DELETE 198
Deleting from a Table Using a Join or a Subquery 201
Truncating 203
Updating Existing Rows 205
Using the UPDATE Statement 205
Updating Data with Expressions and Columns 207
Updating with a JOIN 208
Updating with Aggregate Functions 210
Using Transactions 212
Writing an Explicit Transaction 212
Rolling Back a Transaction 214
Locking Tables 215
Thinking About Performance 216
Database Cleanup 219
Summary 220
■Chapter 7: Understanding T-SQL Programming Logic 221
Variables 221
Declaring and Initializing a Variable 221
Using Expressions and Functions with Variables 224
Using Variables in WHERE and HAVING Clauses 225
The IF… ELSE Construct 228
Using IF 228
Using ELSE 230

Using Multiple Conditions 232
Nesting IF…ELSE 233
Using IF EXISTS 235
WHILE 236
Using a WHILE Loop 237
Using ROWCOUNT 238
Nesting WHILE Loops 240
■ CONTENTS

xii

Exiting a Loop Early 241
Using CONTINUE 242
Error Handling 244
Using @@ERROR 244
Using GOTO 246
Using TRY … CATCH 246
Viewing Untrappable Errors 248
Using RAISERROR 250
Using TRY…CATCH with Transactions 251
Temporary Tables and Table Variables 253
Creating Local Temp Tables 253
Creating Global Temp Tables 254
Creating Table Variables 255
Using a Temp Table or Table Variable 256
Using a Temp Table or Table Variable as an Array 258
Using a Cursor 260
Thinking About Performance 262
Summary 267
■Chapter 8: Moving Logic to the Database 269

Tables 269
Adding Check Constraints to a Table 270
Adding UNIQUE Constraints 272
Adding a Primary Key to a Table 274
Creating Foreign Keys 277
Creating Foreign Keys with Delete and Update Rules 279
Defining Automatically Populated Columns 284
Views 288
Creating Views 288
Avoiding Common Problems with Views 291
Manipulating Data with Views 293
User-Defined Functions 297
Creating User-Defined Scalar Functions 297
Using Table-Valued User-Defined Functions 299
Stored Procedures 301
■ CONTENTS

xiii

Using Default Values with Parameters 304
Using the OUTPUT Parameter 306
Saving the Results of a Stored Proc in a Table 307
Using a Logic in Stored Procedures 309
User-Defined Data Types 311
Triggers 312
Thinking About Performance 313
Database Cleanup 314
Summary 317
■Chapter 9: Working with New Data Types 317
Large-Value String Data Types (MAX) 317

Large-Value Binary Data Types 319
Creating VARBINARY(MAX) Data 319
Using FILESTREAM 321
XML Data 323
Retrieving Data As XML 323
Using the XML Data Type 325
Enhanced Date and Time 326
Using DATE, TIME, and DATETIME2 326
Using DATETIMEOFFSET 328
HIERARCHYID 329
Viewing HIERARCHYID 329
Creating a Hierarchy 331
Using Stored Procedures to Manage Hierarchical Data 332
Spatial Data Types 335
Using GEOMETRY 335
Using GEOGRAPHY 337
Viewing the Spatial Results Tab 338
Sparse Columns 339
Summary 341
■Chapter 10: Writing Advanced Queries 343
Advanced CTE Queries 343
Using Multiple CTEs 343
Calling a CTE Multiple Times 345
■ CONTENTS

xiv

Joining a CTE to Another CTE 347
Using the Alternate CTE Syntax 349
Writing a Recursive Query 350

The OUTPUT Clause 352
Using OUTPUT to View Data 353
Saving OUTPUT Data to a Table 355
The MERGE Statement 357
GROUPING SETS 360
Pivoted Queries 361
Pivoting Data with CASE 362
Using the PIVOT Function 363
TOP Enhancements 365
Ranking Functions 367
Using ROW_NUMBER 368
Using RANK and DENSE_RANK 370
Using NTILE 371
Database Cleanup 372
Summary 373
■Chapter 11: Where to Go Next? 375
Online Resources 375
Conferences 376
User Groups 376
Vendors 377
Books 377
Classes 377
SQL Server Books Online 377
Practice, Practice, and More Practice 378
Teach Someone Else 378
■Appendix: Solutions to the Exercises 379
Chapter 2: Writing Simple SELECT Queries 379
Solutions to Exercise 2-1: Using the SELECT Statement 379
Solutions to Exercise 2-2: Filtering Data 380
Solutions to Exercise 2-3: Filtering with Wildcards 381

Solutions to Exercise 2-4: Filtering with Multiple Predicates 382
■ CONTENTS

xv

Solutions to Exercise 2-5: Working with Nothing 383
Solutions to Exercise 2-6: Performing a Full-Text Search 384
Solutions to Exercise 2-7: Sorting Data 385
Solutions to Exercise 2-8: Thinking About Performance 385
Chapter 3: Using Functions and Expressions 387
Solutions to Exercise 3-1: Writing Expressions Using Operators 387
Solutions to Exercise 3-2: Using Mathematical Operators 388
Solutions to Exercise 3-3: Using String Functions 388
Solutions to Exercise 3-4: Using Date Functions 389
Solutions to Exercise 3-5: Using Mathematical Functions 390
Solutions to Exercise 3-6: Using System Functions 391
Solutions to Exercise 3-7: Using Functions in the WHERE and
ORDER BY Clauses 392

Solutions to Exercise 3-8: Thinking About Performance 392
Chapter 4: Querying Multiple Tables 393
Solutions to Exercise 4-1: Writing Inner Joins 393
Solutions to Exercise 4-2: Writing Outer Joins 395
Solutions to Exercise 4-3: Writing Subqueries 397
Solutions to Exercise 4-4: Exploring Derived Tables and
Common Table Expressions 398
Solutions to Exercise 4-5: Thinking About Performance 399
Chapter 5: Grouping and Summarizing Data 400
Solutions to Exercise 5-1: Using Aggregate Functions 400
Solutions to Exercise 5-2: Using the GROUP BY Clause 401

Solutions to Exercise 5-3: Using the HAVING Clause 402
Solutions to Exercise 5-4: Using DISTINCT 402
Solutions to Exercise 5-5: Using Aggregate Queries with
More Than One Table 403

Solutions to Exercise 5-6: Isolating Aggregate Query Logic 403
Solutions to Exercise 5-7: Thinking About Performance 405
Chapter 6: Manipulating Data 407
Solutions to Exercise 6-1: Inserting New Rows 407
Solutions to Exercise 6-2: Deleting Rows 411
Solutions to Exercise 6-3: Updating Existing Rows 412
Solutions to Exercise 6-4: Using Transactions 413
■ CONTENTS

xvi

Chapter 7: Understanding T-SQL Programming Logic 414
Solutions to Exercise 7-1: Using Variables 414
Solutions to Exercise 7-2: Using the IF…ELSE Construct 415
Solutions to Exercise 7-3: Using WHILE 416
Solutions to Exercise 7-4: Handling Errors 418
Solutions to Exercise 7-5: Creating Temporary Tables and Table Variables 419
Chapter 8: Moving Logic to the Database 420
Solutions to Exercise 8-1: Creating Tables 420
Solutions to Exercise 8-2: Creating Views 422
Solutions to Exercise 8-3: Creating User-Defined Functions 423
Solutions to Exercise 8-4: Creating Stored Procedures 425
■Index 427




xvii

About the Author
■Kathi Kellenberger fell in love with computers the first time she touched a TRS-
80 during her last year of college. Unfortunately, she was working on a degree in a
health-care field that she stayed with for 16 years after college. During those years,
she began programming as a hobby and eventually set up databases and wrote
programs for several charity projects. Luckily, she was able to switch to computer
programming during the Y2K craze, working on projects to update networks,
workstations, and software for several small law firms. During that time, she
programmed everything from ASP web sites to WordPerfect macros to Palm Pilot
applications. She also began working with SQL Server.
After programming for a few years, she had the chance to become a SQL
Server database administrator for Bryan Cave LLP, a prestigious law firm headquartered in St. Louis. The
move proved to be a good one, and she made SQL Server the focus of her career.
In 2004 after reading a particularly bad article on her favorite SQL Server web site, she decided
that even she could write a better article, and her writing career began. Writing articles led to the
opportunity to contribute to one of Brian Knight’s books, Professional SQL Server 2005 Integration
Services (Wrox, 2006). She soon added speaking at user groups’ meetings and conferences and getting
involved with the PASS organization as a volunteer. In 2008, Kathi was awarded SQL Server MPV status
for her many contributions to the SQL Server user community.
Kathi lives in Edwardsville, Illinois, with husband, Dennis. She enjoys singing, cycling, running,
and spending time with family and friends.
xviii

About the Technical Reviewer
■Ken Simmons is a database administrator/developer specializing in SQL Server
and .NET. He is the author of Pro SQL Server 2008 Administration (Apress, 2009)
and Pro SQL Server 2008 Mirroring (Apress, 2009). He has been working in the IT

industry since 2000 and currently holds certifications for MCP, MCAD, MCSD,
MCDBA, and MCTS for SQL 2005.
Ken is active in the online community and
often participates in the SQL forums on MSDN and SQLServerCentral.com. He
enjoys sharing tips by writing articles for SQLServerCentral.com and
MSSQLTips.com. When he is not working, Ken enjoys traveling with his wife,
Susan, and 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.
xix

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 to actually produce the book. Some of them I have
met, like Apress editor Jonathan Gennick. Others I know through frequent e-mails: project manager
Kylie Johnston and editors Ken Simmons, Douglas Pundick, and Kim Wimpsett. I am sure there are
countless others who have worked behind the scenes to help get my book into your hands. I thank
everyone for their hard work and dedication to help me write a better book.
It was important to me to write this book myself because I felt the book was already living inside
my brain, just waiting for my fingers to type the words. I knew what I wanted to cover and could imagine
you reading each chapter well before I began writing it. I’m not saying that writing the entire book was
an easy task, especially with the busy life I lead, but I knew that this was what I needed to do.
So many people in my life have helped me along the way. My parents, Bill and Marilyn Morgan,
taught me to believe that I could do anything in life that I wanted to do, and they were right! I thank
them for everything they have done for me and my siblings. And, Mom, I promise I’ll get to the
campground for a weekend soon. I thank my brothers, Bill, Jeff, and Bob Morgan, for being computer
geeks like me and for sharing their knowledge with me when I was getting started in this business.
Thanks to my sisters, Jackie Laurie, Jeanne Morgan, and Chris Brandt, who aren’t quite as geeky as I am
but who are the most fun sisters anyone could ever have.
Thanks to Dennis, my love, for encouraging me, listening to me, and just putting up with me all

these years. You are my prince. Thanks to Andy and Anna, my son and his wife, and to Denise and Ryan,
my daughter and her husband. Thanks for being my kids and for being my friends. And to Thomas, my
amazing grandson, you have made my life more fun than I knew possible.
As you can imagine, writing a book takes over one’s life. I found myself just working and writing
for months. I want to thank several friends, Justin Siess, Jason Rutherford, Stephen Harris, Luke Moore,
and Pam King, for getting me away from my desk for awhile each day and back to the gym even when I
didn’t think I had time to go.
Several other people have been instrumental in my career. Doug Wilmsmeyer believed that I
could leave my health professions career and become a programmer before I even knew that is what I
wanted to do. Thanks, Doug, for your encouragement and advice throughout the years. Brian Knight,
author, trainer, and SQL Server superstar, changed my life in 2005 when he asked me to write a couple of
chapters for his Integration Services book. Thanks to Brian and to his business partners, Steve Jones and
Andy Warren, who have encouraged me and nurtured my writing since I turned in my first article to
SQLServerCentral.com almost five years ago. Thanks to Tom LaRock, SQLRockstar, for your
encouragement and friendship.
Thanks, most of all, to my students and readers who have provided criticism and feedback,
appreciation and praise. It is for you that I write this book.
xx

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 or whether a tool
generates them for you. If you want to be successful in a career involving SQL Server, then it helps to
master the underlying language.
To whet your appetite and to give you an idea of what you’re in for, here 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 of work that you can get done in
a single statement of T-SQL versus large blocks of code in other languages is simply amazing. Using T-
SQL, you can generate complex reports from a single statement, embed business logic in your database,
create maintenance scripts to automate administrative tasks, and do much, much more.
The approach I take in this book is to begin with a review of some fundamental database
concepts. Why? Because you need to understand how SQL Server stores the data before you begin to
write queries against it. Then I move on to writing some simple queries, giving you the tools you need to
begin extracting useful data from a database. From there we move on to manipulating data because
most databases are not static; they are updated frequently. I then show you the programming logic
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 by using tools. Tools that generate code for you are great, but tools break. And when
things go wrong, that’s 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 any circumstance.

■ INTRODUCTION

xxi

Who This Book Is For
I have often found 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 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 book was born, and the book is roughly based on the class I taught.
Within the book, each chapter or section builds on knowledge presented in the previous
chapter or section. Most of the sections talk about a concept, 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 book contains many simple examples to illustrate the
techniques covered and get you quickly using those techniques.
Chapter 1, “Getting Started”: This chapter provides instructions for installing SQL Server Express
edition and configuring it to be ready for the rest of the book. It also introduces database concepts
such as normalization and indexes so that you understand how data is stored in SQL Server
databases.
Chapter 2, “Writing Simple SELECT Queries”: This chapter teaches you how to write your first T-SQL
statements. It covers how to select, filter, and order data from a table.
Chapter 3, “Using Functions and Expressions”: This chapter shows you how to use built-in functions
and expressions to modify how the data is displayed, filtered, or ordered.
Chapter 4, “Querying Multiple Tables”: This chapter demonstrates several techniques to use data
from more than one table in the same query.
Chapter 5, “Grouping and Summarizing Data”: This chapter teaches how to write aggregate queries.
Aggregate queries allow you to group data and use special functions, such as SUM and COUNT, that
operate over groups of data.
Chapter 6, “Manipulating Data”: Because you will need to modify data as well as retrieve it, this

chapter teaches how to insert new rows and update or delete existing rows.
■ INTRODUCTION

xxii

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 how to create database objects such
as stored procedures and views that allow you to store logic within the database. You will also learn
about table constraints that control what data may be added to a table.
Chapter 9, “Working with New Data Types”: This chapter covers the new data types introduced with
SQL Server 2005 and 2008. You will learn about the XML data type, new large value data types, spatial
data types, and more.
Chapter 10, “Writing Advanced Queries”: This chapter introduces several new query types, such as
the new pivot query, as well was some advanced techniques using common table expressions to
solve complex problems efficiently.
Chapter 11, “Where to Go Next?”: This chapter provides information about resources, many of them
free, that you can use to enhance your skills.
Appendix, “Solutions to the Exercises”: The appendix provides solutions to the exercises in Chapter 2
through Chapter 8.
Prerequisites
To run the code samples in this book, you will need a computer with the following:
1. Windows Server 2003 SP2, Windows Server 2008, Windows Vista, Windows XP SP2, or Windows XP
SP3
2. 1GHz or faster processor (2GHz or faster is recommended)
3. 512MB RAM (1GB or more is recommended)
4. 1.9GB free hard disk space
5. An Internet connection to download SQL Server Express edition from Microsoft’s web site
Downloading the Code

The source code for this book is available to readers at in the Downloads section
of this book’s home page. Please feel free to visit the Apress web site and download all the code there.
You can also check for errata and find related titles from Apress.
■ INTRODUCTION

xxiii

Contacting the Author
Kathi can be contacted at You will find her blog and social networking pages at
the following sites:




×