Supplemental files and examples for this book can be found at http://examples.oreilly.com/9781565927568/. Please use a standard desktop web browser to access these files, as they may not be accessible from all ereader devices.
All code files or examples referenced in the book will be available online. For physical books that ship with an accompanying disc, whenever possible, weve posted all CD/DVD content. Note that while we provide as much of the media content as we are able via free download, we are sometimes limited by licensing restrictions. Please direct any questions or concerns to .
Preface
SQL in general, and Transact-SQL in particular, is so deceptivelysimple that few people take the time to master it. Many of the SQLbooks currently on the market contribute to this state of affairs bynot taking their readers very far beyond the simple SELECTcolumn_name FROM table_name WHERE conditions
pattern ofwriting SQL SELECT statements. In this book, we hope to take you farbeyond the level of writing simple SQL statements and open your eyesto the full power of SQL and Transact-SQL.
For many years, SQL has been the domain of large corporations usinghigh-end databases such as Oracle, Sybase, Informix, and DB2.Microsoft's entry into the market with Microsoft SQLServer brought Transact-SQL to the workgroup server and desktoplevel, thereby broadening the market for Transact-SQL programmers.More systems are being programmed in SQL and Transact-SQL, and ifyou're a Transact-SQL programmer,you'll want to leverage Transact-SQL to its fullest.
Getting the most out of SQL and Transact-SQL requires a particularway of thinking. SQL is a set-oriented language in which you focus onend results, not on the procedures used to accomplish those results.If you're used to thinking procedurally, this shiftto set-oriented thinking can be jarring. The SQL solutions toproblems that are easily described procedurally are often notobvious. So why bother with the set-oriented SQL solutions?It's true that Transact-SQL provides you withprocedural capabilities, but use of those capabilities is no excusefor not utilizing the core SQL language to its fullest. SQL solutionsare often magnitudes more efficient than the corresponding proceduralsolutions.
Why We Wrote This Book
We have many years experience working in SQL environments, and overthe years we've developed, or stumbled across, anumber of useful SQL design patterns that we apply to problems thatwe encounter in our day-to-day work. Knowing these patterns gives usan edge and allows us to accomplish things with ease that mightotherwise be difficult.
Looking back over our careers, we remember the"magic" of discovering a new andinnovative SQL-based solution to a programming problem. There was thesudden flash of light and a rush of adrenalin as a whole new vista ofpossibilities opened up before us. It's our hopethat we can share some of that magic with you. For that matter, weeach learned a few pieces of magic from the other while collaboratingon this book.
Audience for This Book
We have two target audiences in mind for this book: those who havejust recently learned SQL and those who have been using SQL forseveral years. This is not a learning-SQL type of book. We assumethat you have a working knowledge of the basic SQL statements:INSERT, UPDATE, DELETE, and SELECT. We also assume that you arepassingly familiar with Transact-SQL's proceduralcapabilities.
If you have recently learned SQL, then you know the basic statements.Next you need to learn how to "thinkSQL" to creatively apply SQL to the programmingproblems you encounter daily. This is difficult to teach; thecreative application of SQL is best learned by example. The purposeof this book is to provide nonobvious examples of SQL being usedcreatively to solve everyday problems. You'll beable to apply our patterns to your own work, and hopefullyyou'll be inspired to discover creative solutions ofyour own.
This book isn't just for newcomers to SQL. We thinkan experienced SQL programmer will discover at least one newtechnique in this book. We have even learned from each other ascoauthors by reading over each other's recipes.
Which Platform and Version?
All the recipes in this book were tested for compatibility with SQLServer 2000. Most of them have also been tested on SQL Server 7. Somerecipes use the new ANSI join syntax supported by SQL Server 2000.Those recipes will require some minor modifications for them to workon older SQL Server releases.
While not as commonly encountered as it used to be, Sybase also usesTransact-SQL. Sybase's Transact-SQL is not 100%compatible with Microsoft's Transact-SQL, butwe've coded the recipes so that, in the vastmajority of cases, they will also work for Sybase.
Structure of This Book
This book is divided into eight chapters. You can read through alleight chapters sequentially, or you can read only those chapters thatpertain to problems you are solving at any given time.
The only exception is , which you shouldread first no matter which other chapter you read next.
, introduces the concept and use of aPivot table. This recipe is in a chapter by itself, because we usethe Pivot table pattern in many other recipes throughout the book.This is a must-read chapter.
, focuses on the core ofSQL's functionality: set manipulation. In thischapter, you'll find techniques for performing theset operations you learned in elementary school, such as difference,intersection, and compliment, using SQL. You'll alsofind techniques for returning the top-n values from a set and forimplementing various types of aggregation.
, shows you how to implement lists,stacks, queues, arrays, and matrices using Transact-SQL. Suchstructures are often considered the domain of other programminglanguages, but it's sometimes advantageous toimplement them at the database level.
, shows you several useful techniques fordealing with hierarchical data from SQL. Hierarchical data presentssome special challenges because SQL is optimized for relational data.Readers who have been in the industry long enough will recall thatrelational databases replaced hierarchicaldatabases. Nonetheless, hierarchical data exists and we must dealwith it.
, demonstrates the ins and outs ofworking with time-based, or temporal, data. Temporal data isfrequently encountered in the business world, and failure torecognize the subtleties of querying such data is a common source oferrors. In this chapter, you'll learn aboutgranularity and about SQL Server's built-in supportfor temporal data. You'll then find a number ofrecipes that show SQL being used creatively to solve various time-and date- related problems.
, deals with the problem of loggingchanges and implementing audit trails. Learn how to implement anaudit-trail mechanism using Transact-SQL, how to generate auditsnapshots of a given point in time, and other related techniques.