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

Beginning T-SQL 2012 pptx

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 (16.11 MB, 448 trang )

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-SQL 2012 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-SQL 2012 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 Beginning T-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, Beginning T-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 2012 T-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.
CHAPTER 1  GETTING STARTED
7

Figure 1-6. The Instance Configuration screen
NAMED INSTANCES
Multiple SQL Server installations can run on one physical computer. Each installation is called an instance.
You may have only one default instance on a computer. Any additional instances must be named. To
connect to SQL Server, you must specify the physical computer name. When working with named
instances, you must specify the instance name as well. To connect to a default instance, only the
computer name is required. When connecting to name instances, the computer name plus the instance
name are required: computerName\instanceName.
11. The Disk Space Requirements screen (Figure 1-7) will ensure that you have
enough disk space for the install. However, “space for the install” refers to
having space for the executable and other files such as the system databases.
The system databases start out small but can grow quite large in a production
system. The space requirements don’t include any user databases, which are
CHAPTER 1  GETTING STARTED
8
the databases that will store your data, so make sure you also have room for
them before clicking Next.


Figure 1-7. The Disk Space Requirements screen
12. On the Service Configuration screen, shown in Figure 1-8, you must specify
accounts under which SQL Server will run. If you are setting up SQL Server for
a production environment, you probably have a special service account to use.
Since you are just installing the Express edition for learning purposes here,
choose the default for all the services.
CHAPTER 1  GETTING STARTED
9

Figure 1-8. Server Configuration screen
13. On the Database Engine Configuration screen’s Account Provisioning tab
(Figure 1-9), you will either select the “Windows authentication mode” option
or the “Mixed Mode” option. If you select "Windows authentication mode,"
SQL Server can accept connections only from Windows-authenticated
accounts; if you selected “Mixed Mode,” it can additionally allow accounts set
up within SQL Server. For the purposes of the book, you can leave the
authentication mode as “Windows authentication mode.” Click the Add
Current User button near the bottom of the page to make sure that the
account you are using is added as an administrator.
CHAPTER 1  GETTING STARTED
10

Figure 1-9. The Database Engine Configuration screen
14. On the Data Directories tab, you can specify directories for database and log
files as well as all the other directories needed for your SQL Server instance. In
a learning environment, the defaults are fine. On a production system, the
database administrator will strategically place files for best performance.
15. Click the FILESTREAM tab on the current screen to enable FILESTREAM
functionality, as in Figure 1-10. FILESTREAM was introduced in SQL Server 2008

and we will look more closely at it in Chapter 10.
CHAPTER 1  GETTING STARTED
11

Figure 1-10. FILESTREAM configuration
16. Click Next after configuring FILESTREAM. You’ll see an Error and Usage
Reporting screen. Check the buttons on that screen to send reports to
Microsoft if you choose to do that, and click Next again.
17. The installation performs more checks from the Installation Rules page that
appears next, such as making sure that the settings you have selected will
work. Click Next to continue.
18. A summary screen of what will be installed displays. Click Install, and the
installation begins.
19. Once the install is complete, you can view a report to help you solve any issues
with the installation. Figure 1-11 shows the report from a successful
installation.
CHAPTER 1  GETTING STARTED
12

Figure 1-11. A successful installation report
20. Click the Close button. Congratulations! You have just installed SQL Server
Express.
After the installation completes, the SQL Server Installation Center displays once more. You may be
interested in viewing some of the 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.
CHAPTER 1  GETTING STARTED
13
Installing the Sample Databases
Sample databases are very useful to help beginners practice writing code. Several databases, such as

Pubs, Northwind, and AdventureWorks, have been available for this purpose over the many releases of
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 1-12. The source for the AdventureWorks databases
The following steps will guide you through installing the sample databases.
CHAPTER 1  GETTING STARTED
14
1. After clicking the appropriate link for your processor type and operating
system, click the I Agree button to accept the license agreement.
2. Click Save to download the files.
3. Navigate to a location that you will remember, and click Save.
4. Once the download completes, open SQL Server Management Studio and start
a new query. You can skip ahead in this chapter to see how this is done. In the
query windows, execute the command shown in Listing 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 = '<drive>:\<file
path>\AdventureWorks2012_Data.mdf') FOR ATTACH_REBUILD_LOG ;

Figure 1-13. The sample database install
You should now have AdventureWorks database installed on your SQL Server instance. Your next
step is to install SQL Server’s help system, Books Online. Then I’ll show you how to look at the
AdventureWorks database in the “Using SQL Server Management Studio” section.

CHAPTER 1  GETTING STARTED
15
Installing Books Online
In SQL Server 2012 you have the choice of accessing Books Online via the Internet or locally. When you
first install SQL Server you have the option to install the Books Online components. These components
allow for better integration with the web-based documentation. The online components allow for
updates to Books Online on the Internet to be applied to your local installation. Follow these steps to
install Books Online locally.
1. Open up Management Studio and select Help from the menu. Under Help,
select Manage Help Settings.
2. A window will pop up with a list of items. Select “Install Content from Online.”
3. Scroll down until you find the entry for SQL Server and click Add, as shown in
Figure 1-14, and then click Update.

Figure 1-14. Installing Books Online
Using Books Online
Once SQL Server Books Online is installed, you can launch it by opening Management Studio and
selecting Help from the top menu. Under the Help menu, select View Help. A new browser window will
open up to the first page of MSDN.
Books Online is now part of the standardized Help Viewer. The screen for Microsoft Help Viewer is
divided into two sections, as shown in Figure 1-15. The contents are displayed in the left pane. You can
expand each entry to see the sections and click a topic to view each article on the right.
CHAPTER 1  GETTING STARTED
16

Figure 1-15. The two panes of Microsoft Help Viewer
In the top right corner there is a search bar. Type in a term, such as query, to see the results found in
the local help system and any articles posted online. On the right you’ll see advanced search options
(Figure 1-16) and in the main window you’ll see the results listed by topic and by location.
CHAPTER 1  GETTING STARTED

17

Figure 1-16. Search results in Microsoft Help Viewer
Once you find an article or help topic you think you will want to view periodically, you can click the
“Add to Favorites” button as you would for any other web site.
You will learn how to write T-SQL from reading this book, but I recommend that you check Books
Online frequently to learn even more!
Using SQL Server Management Studio
Now that you have SQL Server, SQL Server Books Online, and the sample database installed, it’s time to
get acquainted with SQL Server Management Studio (SSMS). SSMS is the tool that ships with most
editions of SQL Server, and you can use it to manage SQL Server and the databases as well as write T-
SQL code. If you have installed SQL Server 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 SQL Server 20012  SQL Server
Management Studio. After the splash screen displays, you will be prompted to connect to an instance of
SQL Server, as shown in Figure 1-17.
CHAPTER 1  GETTING STARTED
18

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), Localhost, or a period in place of the computer
name as long as you are logged on locally and not trying to connect to a remote SQL Server. Make sure
that the appropriate server name is filled in, and click Connect.
Once connected to an instance of SQL Server, you can view the databases and all the objects in the
Object Explorer. The Object Explorer is located the left side of the screen by default. You can expand

each item to see other items underneath. For example, once you expand the Databases folder, you can
expand one of the databases. Then you can expand the Tables folder for that database. You can expand a
table name and drill down to see the columns, indexes, and other properties. In the right pane, you can
see details about the selected item. If you don’t see the details, press the F7 key. Figure 1-18 shows the
Object Explorer window and details.
CHAPTER 1  GETTING STARTED
19

Figure 1-18. The Object Explorer
Running Queries
One SSMS feature that you will use extensively during this book is the Query Editor. In this 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
it is not already selected, as in Figure 1-19.
CHAPTER 1  GETTING STARTED
20

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 type that IntelliSense (Figure 1-20) is available in the
Query Editor window. IntelliSense helps you by eliminating keystrokes to save
you time. It also validates the code before the code is compiled. It doesn’t work
when connecting to versions earlier than SQL Server 2008.


Figure 1-20. IntelliSense
CHAPTER 1  GETTING STARTED
21
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 table, as in Figure 1-22.

Figure 1-22. The HumanResources.Employee table

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×