Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 448 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
448
Dung lượng
16,11 MB
Nội dung
Shaw
Kellenberger
Shelve in
Databases / MS SQL Server
User level:
Beginning
www.apress.com
SOURCE CODE ONLINE
RELATED
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Beginning T-SQL 2012
Beginning T-SQL2012 starts you on the path to mastering T-SQL. It shows you how to
implement best practices for writing T-SQL, avoid common errors, and write scalable
code for good performance.
Beginning T-SQL2012 begins with an introduction to databases and normalization
as well as SQL Server Management Studio. The authors then teach you one feature
or concept of T-SQL at a time, with each new skill building on the ones you previously
learned. The book contains many simple examples to illustrate the techniques covered
and get you quickly using them.
With BeginningT-SQL 2012, you’ll learn how to:
• Write accurate queries that are scalable and perform well
• Combine set-based and procedural processing, obtaining the best from both worlds
• Embed business logic in your database through stored procedures and functions
• Simplify your work with new and advanced features, such as common table
expressions and virtual tables
• Enhance performance by knowing when to apply features such table value
parameters and when not to
With an emphasis on best practices and sound coding techniques, BeginningT-SQL
2012 gives you hands-on knowledge of this important language. It teaches you how
to write code that will help you to achieve the best-performing applications possible.
SECOND
EDITION
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
iv
Contents at a Glance
Foreword xvi
About the Authors xviii
About the Technical Reviewer xix
Acknowledgments xx
Introduction xxi
Chapter 1: Getting Started 1
Chapter 2: Writing Simple SELECT Queries 35
Chapter 3: Using Functions and Expressions 79
Chapter 4: Querying Multiple Tables 131
Chapter 5: Grouping and Summarizing Data 169
Chapter 6: Manipulating Data 203
Chapter 7: Understanding T-SQL Programming Logic 241
Chapter 8: Working with XML 285
Chapter 9: Moving Logic to the Database 311
Chapter 10: Working with Data Types 367
Chapter 11: Writing Advanced Queries 391
Chapter 12: Where to Go Next? 419
Index 423
xxi
Introduction
I never thought I’d be writing a technical book. I have a MA in English Literature so I always pictured
myself sitting in an oak paneled room surrounded by books and attentive students listening to me
pontificating on the latest criticism of 19
th
Century novels. It didn’t take me long to realize though that
path wasn’t for me and I really wasn’t cut out for a life in academia. But now I was an ex-English major
working in a book store, starting a family and with little career prospects.
Working in a bookstore did offer some advantages. One advantage was the easy access to
technical books. I had endless access to books just like the one you are reading now. I thought to myself,
why not read these books, learn from them, and try working in IT? I didn’t see a need to go back to
school in order to learn IT. I had the books, I had the computer at home to work on, and I had the goal of
acquiring an IT certification. I eventually passed the certification exam and soon after that I got my first
break into IT working for a small consulting company.
So, why does any of this matter? The point is that many, if not most, of the people working in IT
today didn’t plan to be in IT. They come from a diverse background. The one thing that binds them
together is their desire to learn and study to become experts in their field. They all started down the path
by reading books just like the one you are holding. They made a decision to start an IT career. This is an
important book because it’s the beginning. The book is the stepping stone to becoming a professional.
Although it isn’t the great American novel I had hoped to someday write, it was still a pleasure and honor
to have been asked by Kathi and Apress to revise it because, unlike a novel, this book has practical, real
world applications. I also take pride in the fact I have given back a little for the benefits similar books
have given me in the past.
Enjoy the book and never stop learning.
-Scott Shaw
C H A P T E R 1
1
Getting Started
If you are reading this book, you probably know about T-SQL. 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 stored in a SQL Server database, regardless of
which application or tool you use. SQL Server 2012T-SQL is based on standards created by the American
National Standards Institute (ANSI), but Microsoft has added several functionality enhancements. You
will find that T-SQL is a very versatile and powerful programming language.
T-SQL consists of Data Definition Language (DDL) and Data Manipulation Language (DML)
statements. This book focuses primarily on the DML statements, which you will use to retrieve and
manipulate data. The book also covers DDL statements, which you will use to create and manage
objects. You will learn about table creation, for example, in Chapter 9.
In this chapter, you will learn how to install a free edition of SQL Server and get it ready for running
the example code and performing the exercises in the rest of the book. This chapter also gives you a
quick tour of SQL Server Management Studio (SSMS) and introduces a few concepts to help you become
a proficient T-SQL programmer.
Installing SQL Server Express Edition
Microsoft makes SQL Server 2012 available in six different editions, including two that can be installed
on a desktop computer or laptop. If you don’t have access to SQL Server, you can download and install
the SQL Server Express edition from Microsoft’s web site at
www.microsoft.com/express/sql/download/default.aspx. To fully take advantage of all the concepts
covered in this book, download SQL Server 2012 Express with Tools. You may notice a new LocalDB
option for SQL Server Express; LocalDB is an extremely lightweight version of SQL Server that doesn’t
include any configuration options or tools. Since you will need the tools for this book you don’t want to
download the LocalDB version. Be sure to choose either the 64-bit or 32-bit download according to the
operating system that you are running. The Express edition will run on the following operating systems
available at the time of this writing: Windows Server 2008 SP2, Windows Server 2008 R2 SP1, Windows 7
SP1, Windows Vista SP2. Note that SQL Server 2012 is not compatible with Windows XP.
Note SP is shorthand for Service Pack, so SP2 refers to Service Pack 2. A service pack is an update to the
operating system or to other software that fixes bugs and security issues.
CHAPTER 1 GETTING STARTED
2
Here are the steps to follow to install SQL Server Express:
1. Once you have downloaded the SQL Server 2012 Express edition installation
file from Microsoft’s site, double-click the file to extract and start up the SQL
Server Installation Center. Figure 1-1 shows the Planning pane of the SQL
Server Installation Center once the extraction has completed. You may need to
click on Planning in the left-hand side to see these options.
Figure 1-1. SQL Server Installation Center’s Planning pane
2. To make sure that your system meets all the requirements to install SQL Server
Express, click the System Configuration Checker link, which opens the Setup
Support Rules screen (see Figure 1-2). Click “Show details” or “View detailed
report” to see more information. Click OK to dismiss the screen when you are
done.
CHAPTER 1 GETTING STARTED
3
Figure 1-2. The Setup Support Rules details page
3. If your system doesn’t meet the requirements, click the Hardware and
Software Requirements link on the Planning pane of the SQL Server
Installation Center, which will take you to a web page on Microsoft’s site. Be
sure to scroll down the web page to find the information for the Express
edition. The hardware requirements are not difficult to meet with today’s PCs.
4. Once you are certain that your computer meets all the requirements, switch to
the Installation pane, shown in Figure 1-3, and click “New SQL Server stand-
alone installation or add features to an existing installation.” The Setup
Support Rules screen you saw in step 2 will display again, but the behavior will
be different this time. Click OK to dismiss the Setup Support Rules screen, and
an installation wizard will begin.
CHAPTER 1 GETTING STARTED
4
Figure 1-3. The Installation pane
5. You may or may not see a Setup Support Files screen at this point. If you do see
it, click Install.
6. Select Express from the drop-down and click Next on the Product Key screen
when installing SQL Server Express edition. No need to have a key since this is
a free edition! Accept the license terms and click Next.
7. Some more checking of your system will take place. You may get a warning
about your firewall (Figure 1-4), especially if you are installing on a
workstation. The warning will say to open ports required for other systems to
access your SQL Server. You can ignore that warning unless you do really want
to open up your system. Click Next to continue.
CHAPTER 1 GETTING STARTED
5
Figure 1-4. More system checks
8. If you have a previously installed instance of SQL Server on your computer, the
installation will prompt you to either update an existing instance or install a
new instance on the Installation Type screen. Select to install a new instance
and click Next. If you don’t have a previous install, select the option “SQL
Server Feature Installation” and click Next.
9. On the Feature Selection screen (Figure 1-5), make sure that “Database Engine
Services,” “Full-Text and Semantic Extractions for Search,” and “Management
Tools – Basic” are selected before clicking Next. If a previous SQL Server 2012
R2 installation is in place, the Management Tools check box might be grayed
out since you need to install it only once per computer.
CHAPTER 1 GETTING STARTED
6
Figure 1-5. The Feature Selection screen
10. Figure 1-6 shows the Instance Configuration screen, and it is very important.
Here you can choose to install a default instance or a named instance. If you
have any SQL Server instances already installed, possibly an earlier version
such as 2008 R2, they will show up in the list on this screen. Each instance
must have a unique name, so you must avoid using any existing instance
names. See the sidebar “Named Instances” for more information about
naming SQL Server instances. The Express edition installation installs the
named instance MSSQLSERVER by default. Use the name MSSQLSERVER if
you can; otherwise, type in a unique name. Figure 1-6 shows the instance
configuration screen. Click Next.
[...]... 1-1 You will need to change the path to match the location where you downloaded the AdventureWorks2012 data file Figure 1-13 shows how your screen should look Listing 1-1 Script to Create the AdventureWorks2012 Database CREATE DATABASE AdventureWorks2012 ON (FILENAME = ':\\AdventureWorks2012_Data.mdf') FOR ATTACH_REBUILD_LOG ; Figure 1-13 The sample database install You should now have... Express with Tools as outlined earlier, you should be able to find SSMS by selecting Start All Programs Microsoft SQL Server 2012 SQL Server Management Studio SSMS is your window into SQL Server You can manage your database, create scripts, and—most importantly—execute T-SQL code and see the results Launching SQL Server Management Studio Launch SSMS by selecting Start All Programs Microsoft... window you will type and run queries as you learn about T-SQL The following steps will guide you through writing your first query in the Query Editor 1 Make sure your SQL Server instance is selected in the Object Explorer, and click New Query, which is located right above the Object Explorer, to open the Query Editor window 2 Select the AdventureWorks2012 database from the drop-down list on the left if... application To do that, you will most likely use a programming language such as Visual Basic NET or C# Calls to SQL Server via T-SQL can be made within your application code or through a middle tier such as a web service Regardless of your application architecture, at some point you’ll use T-SQL SQL Server does have a very nice reporting tool called Reporting Services that is part of the business intelligence... normalization is beyond the scope of this book, but it is helpful to understand why databases are normalized To learn more about normalization, see Pro SQL Server 2012 Relational Database Design and Implementation by Louis Davidson and Jessica Moss (Apress, 2012) Figure 1-31 shows how a database design might look before it is normalized The example is of an order-entry database There is one table, and that table... SQL Server You can download the sample databases from the CodePlex samples web site at www.codeplex.com Because the link will change frequently as updated samples become available, search for SQL Server 2012 sample databases Make sure you are downloading the latest version of the sample databases Figure 1-12 shows a portion of the download page that was current the day that this section was written Figure... be prompted to connect to an instance of SQL Server, as shown in Figure 1-17 17 CHAPTER 1 GETTING STARTED Figure 1-17 Connect to Server dialog box Notice in this example that the computer name is SQL2012 and we are using the default instance If you installed a named instance, you will see the computer name followed by a “\” and then the instance name For the default instance you can also use (local),... resources available in this application at a later time Luckily, you don’t have to start the install again You can run the Installation Center by selecting Start All Programs Microsoft SQL Server 2012 Configuration Tools SQL Server Installation Center at any time 12 CHAPTER 1 GETTING STARTED Installing the Sample Databases Sample databases are very useful to help beginners practice writing... Editor window 2 Select the AdventureWorks2012 database from the drop-down list on the left if it is not already selected, as in Figure 1-19 19 CHAPTER 1 GETTING STARTED Figure 1-19 The AdventureWorks2012 database 3 Type the following code in the Query Editor window on the right It’s a query to display all the data in the Employee table SELECT * FROM HumanResources.Employee; 4 You will notice as you... earlier than SQL Server 2008 Figure 1-20 IntelliSense 20 CHAPTER 1 GETTING STARTED 5 Click Execute or press the F5 key to see the results, as in Figure 1-21 Figure 1-21 Results of running your first T-SQL query SSMS has several scripting features to help you write code Follow these steps to learn how to create a query without typing 1 Make sure that the Tables folder is expanded, and select the HumanResources.Employee . Server User level: Beginning www.apress.com SOURCE CODE ONLINE RELATED BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® Beginning T-SQL 2012 Beginning T-SQL 2012 starts you on the path to mastering T-SQL. It. you how to implement best practices for writing T-SQL, avoid common errors, and write scalable code for good performance. Beginning T-SQL 2012 begins with an introduction to databases and. this book, you probably know about T-SQL. 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