Microsoft SQL Server 2005 Express Edition For Dummies (2006)
Microsoft SQL Server 2005 Express Edition For Dummies (2006)
™
SQL Server 2005
Express Edition
FOR
DUMmIES
‰
by Robert Schneider
Microsoft ®
™
SQL Server 2005
Express Edition
FOR
DUMmIES
‰
by Robert Schneider
Microsoft® SQL Server™ 2005 Express Edition For Dummies®
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing,
Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at
http://www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United
States and other countries, and may not be used without written permission. Microsoft and SQL Server
are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other coun-
tries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not asso-
ciated with any product or vendor mentioned in this book.
‘Microsoft’ is a registered trademark of Microsoft Corporation in the United States and/or other countries
and is used by Wiley Publishing, Inc. under license from owner. ‘Microsoft® SQL Server™ 2005 Express
Edition For Dummies®’ is an independent publication not affiliated with Microsoft Corporation.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP-
RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-
TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE-
ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON-
TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE
UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE
AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR-
THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR-
MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE.
FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE
CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care
Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Library of Congress Control Number: 2005927727
ISBN-13: 978-0-7645-9927-9
ISBN-10: 0-7645-9927-5
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/QW/QW/QW/IN
About the Author
Robert D. Schneider has more than 15 years of experience developing and
delivering sophisticated software solutions worldwide. He has provided data-
base optimization, distributed computing, and other technical expertise to a
wide variety of enterprises in the financial, technology, and government sec-
tors. Clients have included Chase Manhattan Bank, VISA, HP, SWIFT, and the
governments of the United States, Brazil, and Malaysia.
Author’s Acknowledgments
The author wants to acknowledge the following people for their invaluable
assistance in creating and publishing this work: Nicole Sholly, Tiffany
Franklin, Damir Bersinic, Rebecca Senninger, Terri Varveris, Nancy L.
Reinhardt, and the folks in Composition Services. And last but certainly not
least: Lynn Z. Schneider, Danielle Jolie Schneider, and Nicole Sierra Schneider
for their unswerving support and encouragement.
Publisher’s Acknowledgments
We’re proud of this book; please send us your comments through our online registration form
located at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:
Changing Data...............................................................................................150
Deleting Data.................................................................................................152
Removing all rows from a table ........................................................153
Removing some of the rows from a table........................................154
Chapter 17: Sorry, I’ll Try That Again: Adding Error Handling
to Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .251
Don’t Just Ignore It: Why You Should Care About Errors .......................251
How to Handle Errors ..................................................................................252
Information about errors...................................................................252
Built-in system functions...................................................................254
Handling errors in the database .......................................................254
Handling errors in the application ...................................................256
Error Examples .............................................................................................257
Syntax error.........................................................................................258
Database schema issue......................................................................258
Data conversion problems ................................................................259
Referential integrity violation ...........................................................259
Trigger interception ...........................................................................260
Defining Your Own Errors with RAISERROR .............................................260
Chapter 21: Using XML with SQL Server 2005 Express . . . . . . . . . . .317
What Is This Thing Called XML? ................................................................317
XML advantages .................................................................................318
XML structure .....................................................................................318
Other important XML concepts .......................................................321
When should you use XML?..............................................................322
Placing XML into Your SQL Server 2005 Express Database....................323
Operating on XML-based Information .......................................................326
Searching for XML data .....................................................................327
Modifying XML data ...........................................................................328
Formatting relational data as XML...................................................328
Magazines......................................................................................................335
User Groups ..................................................................................................335
Books .............................................................................................................335
Database Design Tools ................................................................................336
Administrative Tools ...................................................................................336
Data Generation Tools .................................................................................336
Blogs ..............................................................................................................336
Chapter 23: Ten SQL Server 2005 Express Troubleshooting Tips . . .337
Show Me How I Can Get the Product.........................................................337
I Can’t Install It!.............................................................................................338
I Can’t Connect to the Database! ................................................................338
Show Me How to Administer My Database...............................................339
I Can’t See My Data!......................................................................................339
My Data Is Messed Up!.................................................................................340
I Want to Automate Some Operations .......................................................340
I Want to Simplify My Data ..........................................................................341
I Want to Build Good Software....................................................................341
My Database Server Is Too Slow! ...............................................................342
Index........................................................................377
Introduction
A lthough once derided as a provider of relatively low-end relational data-
base products, Microsoft has turned its flagship SQL Server database
into a platform that can compete with any database servers on the market.
Ironically, the downside of all this power is that some now find SQL Server to
be too complex and feature-rich.
Here are some of the things you can do with this book:
Foolish Assumptions
You don’t need a PhD from MIT to derive value from this book. On the contrary:
Any exposure to the items on the following list goes a long way towards helping
2 Microsoft SQL Server 2005 Express Edition For Dummies
you make the most from the book. And if you don’t currently have any experi-
ence, you will soon:
However, if you’re an absolute newbie with SQL Server who is building a new
application, you’ll probably want to look at the early chapters on the prod-
uct’s architecture and infrastructure first before moving onto the develop-
ment section.
Also, if you’re not the type of person who pops the hood of your car to see
how the motor works, you’ll likely find yourself skipping the information
called out by the tech stuff icons. Just as your car still runs without you mem-
orizing the workings of its transmission, you can still derive a lot of value from
SQL Server 2005 Express even if you don’t know its internal architecture.
Introduction 3
How This Book Is Organized
Microsoft SQL Server 2005 Express Edition For Dummies is split into eight
parts. You don’t have to read it sequentially, and you don’t even have to read
all the sections in any particular chapter. You can use the Table of Contents
and the index to find the information you need and quickly get your answer.
In this section, I briefly describe what you find in each part.
This icon highlights the new features you find in this latest version of SQL
Server Express.
This icon marks a general interesting and useful fact — something that you
may want to remember for later use.
When you see this icon, you know that techie stuff is nearby. If you’re not
feeling very techie, you can skip this info.
The Tip icon points out helpful information that is likely to make your
job easier.
The Warning icon highlights lurking danger. With this icon, I’m telling you to
pay attention and proceed with caution.
6 Microsoft SQL Server 2005 Express Edition For Dummies
Task Look At
Installation requirements and guide Chapter 2
Upgrading to SQL Server 2005 Express Appendix B
Common problems Chapter 23
SQL Server 2005 Express functionality limitations Chapter 1
Converting to a more powerful SQL Server version Appendix A
Pairing the database with the right applications Chapter 1
Enabling the right network protocols Chapter 3
Creating databases and tables Chapter 8
Best practices for database design Chapter 9
Transact-SQL syntax Chapter 10
Using XML with SQL Server 2005 Express Chapter 21
Writing your own stored procedures Chapter 14
Using views Chapter 9
Configuring the SQL Server 2005 Express engine Chapter 5
Integrating transactions to your application Chapter 12
Taking advantage of replication Chapter 6
Using SQL Server Management Studio Express Chapter 4
Intercepting calls to your database Chapter 15
Protecting your information Chapter 11
Backing up your database Chapter 13
Using other languages to build stored procedures Chapter 16
Graceful error handling Chapter 17
Building applications with Express editions Chapters 19 and 20
Reporting services Chapter 18
Key terms and concepts Appendix C
Part I
Welcome to SQL
Server 2005 Express
In this part . . .
B efore you can start making the most of your SQL
Server 2005 Express database server, you need to do
a few simple — yet important — tasks. That’s what this
part is all about: Helping you figure out if SQL Server 2005
Express is right for you, and then getting going as quickly
as possible.
First, you find out all about SQL Server 2005 Express,
including its major features, as well as where it differs
from its bigger (and more expensive) siblings. With that
background out of the way, you’re ready to see how to get
your own, free copy of SQL Server 2005 Express. Next, I
tell you about some common situations in which you use
this product, as well as some scenarios where you should
choose another edition. Finally, the part closes out with
some basic steps that you can follow to get your database
up and running.
Chapter 1
To begin, I give you some context to understand how this capable, yet entry-
level product came about, along with how it fits in with the rest of the SQL
Server product family. Next, you see who the ideal user is for SQL Server 2005
Express, along with a list of some of the product’s most compelling features
(as well as what’s not present). Finally, I show you the kind of tools that you’ll
want to acquire so you can get started building applications and working
with your SQL Server 2005 Express data.
As more time passed, a new breed of database companies arose. With names
like Oracle, Informix, and Sybase, these vendors (and many others) developed
a particular kind of database, known as a relational database. Relational data-
bases are particularly well designed for storing information in tabular format,
which further helped software developers as they built a whole new class of
enterprise applications.
Microsoft also entered the relational database fray some years back with the
SQL Server database. Once thought of as a relatively lightweight database
vendor, Microsoft has continually refined SQL Server to the point where it
can compete for the largest and most complicated database-driven applica-
tions. Of course, all these capabilities and power have made the SQL Server
database platform somewhat intimidating and confusing for many developers
and users, especially those that are building and using simpler solutions.
To address this problem, beginning with the SQL Server 2005 product family,
Microsoft has created several different versions of SQL Server. Known as edi-
tions, each of these versions addresses a different class of database environ-
ment. Despite this segmentation, all editions are built on the same underlying
technology platform. The main difference among the editions is that the sim-
pler, less far-reaching versions don’t have all the features and storage capac-
ity that you find in their larger (and more complex) siblings. Here’s a list of all
the SQL Server 2005 editions:
To get the lowdown on the differences among each SQL Server 2005 edition,
go to
www.microsoft.com/sql/prodinfo/features/compare-
features.mspx
As you evaluate potential uses for SQL Server Express 2005, note that you can
use it for all sorts of applications, from traditional, desktop-based rich client
software as well as browser-based solutions that are available over the Internet.
SQL Server 2005 Express is just one component of a larger collection of entry-
level products aimed at helping developers and hobbyists use Microsoft’s tech-
nologies to deliver powerful and flexible computing solutions. These products,
all of which are part of Visual Studio 2005 Express include the following:
All these products work seamlessly with SQL Server 2005 Express. If you’re inter-
ested in taking advantage of these products, have a look at Chapters 19 and 20.
12 Part I: Welcome to SQL Server 2005 Express
Figure 1-1:
SQL Server
2005
Express
information
available
from inside
Visual
Studio.
14 Part I: Welcome to SQL Server 2005 Express
⻬ High availability features: The entire SQL Server 2005 product family
offers numerous technologies to help keep your database up and run-
ning at all times. However, Express doesn’t offer these capabilities, all of
which reduce down time or help improve performance:
• Online restore
• Database mirroring
• Partitioning
• Failover clustering
• Online indexing
If you’re building a mission critical application and continual uptime is
of vital importance to you, you may want to deploy your solution on one
of the other SQL Server 2005 editions.
⻬ Rich programming language choices: The entire SQL Server 2005 prod-
uct line supports the Microsoft Common Language Runtime (CLR). This
means that you can develop internal database logic such as stored pro-
cedures and triggers in any one of a number of popular programming
languages, rather than in SQL Server’s internal programming language:
Transact-SQL.
⻬ Analysis services: The more advanced editions of SQL Server 2005 fea-
ture business analytic logic that you can use to help make sense of your
information. This is especially true if your environment sports massive
volumes of data that need to be crunched to come up with recognizable
patterns. The bad news is that this is not present in SQL Server 2005
Express. However, the good news is that chances are that if these kinds
of data are found in your organization, you’ll have already purchased
one of the many third-party business intelligence products.
⻬ Report server: Users always want more information out of their data-
base. With SQL Server 2005’s reporting services, you can set up a wide
range of developer-driven and user-driven reports. You can then inte-
grate and deliver these communiqués through a series of different pre-
sentation technologies. Happily, you’ll find these capabilities present in
SQL Server 2005 Express with Advanced Services, which should help
please those finicky users. If you’re curious about how these features
work, take a look at Chapter 18 for the details.
⻬ Integration services: These features allow you to write powerful integra-
tion logic that can take information from a broad range of other data
storage locations and then store it inside SQL Server. The same holds
true for outbound data. Unfortunately, you won’t find these services pre-
sent in SQL Server 2005 Express. Luckily, this doesn’t mean that you
can’t integrate data among disparate systems; it just means that you
may have to do some more work to achieve the same results.
⻬ Notification services: This refers to the capability, found only in the
more feature-rich editions of SQL Server 2005, to build sophisticated
publish-and-subscribe applications. Once created, these applications
Chapter 1: SQL Server 2005 Express Overview 15
can properly react to a wide variety of events, notifying all interested
parties that an event has occurred. SQL Server 2005 Express does let
you take advantage of replication, but only as a subscriber.
⻬ Backup/recovery options: Because backup and recovery are a vital part
of any data integrity and reliability plan, SQL Server 2005 offers adminis-
trators a choice among several different recovery models, each of which
has its own strengths and weaknesses. However, your data-archiving
choices are somewhat more reduced for SQL Server 2005 Express. You
can still set up a very robust backup and recovery strategy; it’s just not
as full featured as in the more advanced editions of SQL Server. In partic-
ular, because the SQL Server Agent is not present, you won’t be able to
schedule jobs or configure alerts and operators.
SQL Server 2005 Express strikes a nice balance between simplicity and
power, while holding the cost as low as you can possibly get. Plus, because
many small businesses one day find themselves morphed (or acquired) into
larger enterprises, making this database server the cornerstone of your data
storage architecture means that you never outgrow your database: You can
easily upgrade to SQL Server 2005 Enterprise.
On top of that, the fact that SQL Server 2005 Express is a true relational data-
base management platform means that you can store and track just about
anything in your database. Some particularly good applications include
⻬ Inventory details
⻬ Sales statistics
⻬ Financial metrics
16 Part I: Welcome to SQL Server 2005 Express
When you have this information safely ensconced in your SQL Server 2005
Express database, you’re free to use all sorts of tools and technologies to
help make sense of your data. For example, you might store details about all
the individual transactions that your organization performs, and then use
business intelligence or other data analysis tools to help identify trends from
your sales results.
While you’re free to store anything you like in your SQL Server 2005 Express
database, be aware that any individual database has a maximum storage limit
of 4GB for your information. If you find yourself approaching that ceiling, you
need to archive some of your older data to make room for newer knowledge.
Distributed enterprise
With the rise of low cost, high-speed Internet connections, many more organi-
zations are realizing benefits from distributed computing. For the distributed
enterprise of any size, SQL Server 2005 Express offers a good balance
between the low maintenance requirements of an entry-level database like
Microsoft Access, and the capabilities of a robust, server-based database.
In addition to these features, you can administer multiple remote SQL Server
2005 Express sites from one location via the SQL Server Management Studio
Express.
Another useful capability of SQL Server 2005 Express is its ability to partici-
pate as a client in a replication architecture. This means that you could have
a single, high-end edition of SQL Server distributing its data among numerous
SQL Server 2005 Express clients. These clients could, in turn, support read-
only applications like reporting or business intelligence. This type of archi-
tecture spreads the processing load across multiple machines, and helps
eliminate bottlenecks.
If you base your applications and solutions around SQL Server 2005 Express,
you’re not locked in: If your customers need extra horsepower and capabili-
ties, they can quickly and painlessly upgrade to a more powerful edition of
SQL Server.
As an added benefit to OEMs and ISVs, SQL Server 2005 Express lets you
store your data in a single, easily transferred file. Known as an .mdf file, this
structure combines the simplicity of a low-end flat file with the power of a
true relational database management system. You should note, however, that
you have to deploy the SQL Server Express 2005 server, even if you only
intend to deploy .mdf files with your solution.
Before you get heavily into using this edition, you should make sure that
none of these limitations are showstoppers for you. Remember that the
majority of these constraints shouldn’t impact you during development;
they’re only an issue at runtime.
Even though this edition has feature restrictions, SQL Server 2005 Express
works with all the same types of information as its more fully featured sib-
lings, and you can easily migrate to a more powerful edition. It also supports
all the same application programming interfaces (APIs), as well as the same
stored procedure and trigger capabilities.
This means that as a designer, you can build your SQL Server 2005 Express
database with confidence, knowing that you aren’t painted into a corner by
missing capabilities, nor the solution you design is forever consigned to this
entry-level database. This works the other way as well: You can design your
solution on a more powerful edition of SQL Server 2005, and then deploy it
onto SQL Server 2005 Express, as long as it doesn’t require any of the fea-
tures that are only found in the more expensive editions of the product.
This tight integration can go a long way toward boosting your productivity. In
effect, with these products, Microsoft has broken down the traditional barrier
between application and database tools.
Figure 1-2:
Visual
Basic 2005
Express
and SQL
Server 2005
Express.
20 Part I: Welcome to SQL Server 2005 Express
Of course, Microsoft isn’t the only game in town when it comes to application
development technologies. You can use several third-party tools (including
open source and shareware) to construct a SQL Server-based solution.
To begin, SQL Server 2005 Express snaps into the standard Microsoft
Computer Management console. This lets you configure and run your data-
base services, which you can see in Figure 1-3.
Figure 1-3:
Configuring
SQL Server
2005
Express
services.
Chapter 1: SQL Server 2005 Express Overview 21
For further configuring and managing your SQL Server 2005 Express server,
you can choose between graphical and character-based tools. As you might
expect, graphical tools provide more intuitive, easy-to-understand informa-
tion about your server.
When it comes to graphical tools, it’s hard to beat Microsoft’s free, excellent
graphical management environment known as SQL Server Management
Studio Express. Figure 1-4 shows a sample of what this product looks like.
SQL Server Management Studio Express can do much more than simply show
you tables and run queries. One handy tool is the activity monitor, which
opens a window onto all database-related activity for your server. Figure 1-5
shows a sample session; you can monitor a tremendous amount of informa-
tion using this tool.
Figure 1-4:
Viewing a
table in SQL
Server
Manage-
ment Studio
Express.
22 Part I: Welcome to SQL Server 2005 Express
Figure 1-5:
The SQL
Server
Manage-
ment Studio
Express
Activity
Monitor.
Chapter 2
In this chapter, you find out what you need to do to get ready for SQL Server
2005 Express, along with how to download, install, and run some basic tests to
make sure everything went smoothly. After a successful installation, you still
have a few things to do before you can use the product to its fullest potential;
I show you those things in Chapter 3. If you have information stored in other
locations that you want to entrust to this database, take a look at Appendix B,
which describes how to import data into SQL Server 2005 Express.
⻬ Via the Internet: If you have a fast Internet connection, you can quickly
and easily download SQL Server 2005 Express. Here’s all you need to do:
1. Point your browser to http://www.microsoft.com/sql.
2. Click the Downloads link.
You should now see a link for SQL Server 2005 Express.
3. Review the System Requirements and Instructions before down-
loading your product.
I describe some of these system requirements in the next section.
You’ll be presented with a potentially bewildering array of SQL Server
2005 Express downloads on Microsoft’s Web site. Here’s a brief overview
of each of the available products:
• Baseline SQL Server 2005 Express: This is the standalone, entry-
level SQL Server database found in SQLEXPR.EXE.
• SQL Server 2005 Express with Advanced Services: This is the
next level up in database power and capability, yet it’s still free! If
you’re interested in enhanced reporting services and full-text
searching, this might be the edition for you (see Chapter 18). It’s in
a file entitled SQLEXPR_ADV.EXE.
• SQL Server Management Studio Express: This is an excellent,
powerful, yet easy-to-use database administration and interaction
tool. I strongly recommend getting a copy; you won’t regret it.
• SQL Express toolkit: If you’re interested in developing reports with
SQL Server 2005 Express with Advanced Services, the Business
Intelligence Development Studio contained in this toolkit is a
must-have.
If you can’t get to SQL Server 2005 Express via the preceding instruc-
tions, just use the Search feature on the Microsoft Web site to find it
quickly.
⻬ Via Visual Studio 2005: SQL Server 2005 Express is part of a larger
group of low-priced Microsoft offerings, known as the Express editions.
These products are aimed at a wide audience of developers that might
not have used these types of solutions before, and include
• Visual Basic 2005 Express Edition (which is conveniently on this
book’s CD)
• Visual Web Developer 2005 Express Edition
• Visual C# 2005 Express Edition
• Visual C++ 2005 Express Edition
• Visual J# 2005 Express Edition
Microsoft also bundles SQL Server 2005 Express with Visual Studio 2005,
which is available for purchase either stand-alone or via the Microsoft
Developer Network (MSDN).
Chapter 2: Downloading and Installing SQL Server 2005 Express 25
⻬ Via the CD that ships with this book: To make things even easier for
you, a fully functional copy of SQL Server 2005 Express with Advanced
Services is on the CD that comes with this book. You can read more
about it in Appendix D.
Take the time to go through each of these major system readiness categories,
making sure that you meet or exceed each of these prerequisites. Also, if
you’re installing SQL Server 2005 Express on multiple machines, remember
that the machine that acts as a central server generally requires faster and
better hardware than one that primarily acts as a client. Finally, you need to
have administrative privileges on the computer where you’re installing SQL
Server 2005 Express.
⻬ CPU: For optimal performance, you want at least a 600 MHZ CPU,
although things might be kind of sluggish at that speed. Using a 1GHZ
CPU definitely makes things peppier and is recommended.
⻬ Memory: Because sufficient memory serves as the foundation of any
well-performing relational database, make sure that you provide 512MB
or more, as recommended by Microsoft. You could probably get away
with 192MB (minimum), but you’re pushing things at that level. In gen-
eral, just as you can’t be too rich or too thin, you can’t provide a rela-
tional database with too much CPU or memory, although SQL Server
2005 Express will not use more than 1GB of RAM.
⻬ Disk: Given that relational databases use disk drives as their primary
storage mechanism, recommending a hard-and-fast value for the right
amount of available disk capacity is difficult: Every installation is differ-
ent. Just the product and its related files take up more than 500MB of
disk space; you’ll likely want to add one or two gigabytes on top of that
for your data.
⻬ Operating system: Microsoft gives you a fairly wide choice of operating
systems that can run SQL Server 2005 Express. They include
• Windows Server 2003
• Windows Small Business Server 2003
• Windows XP Home Edition
• Windows XP Media Center Edition
26 Part I: Welcome to SQL Server 2005 Express
Figure 2-1:
A disk that
needs to be
defrag-
mented.
Figure 2-2:
The initial
SQL Server
2005
Express
installation
prerequisite
screen.
SQL Server 2005 Express runs some very sophisticated checks against
your system to make sure that the upcoming installation goes smoothly.
Each configuration check is flagged as Success, Error, or Warning.
You must correct errors; you can get away with ignoring warnings, but
things may not run very smoothly if you do so.
Figure 2-3:
The SQL
Server 2005
Express
Installation
Wizard.
Chapter 2: Downloading and Installing SQL Server 2005 Express 29
For example, Figure 2-4 shows a “close but no cigar” configuration
check. This particular machine was a little light on memory; hence the
warning. You can even get a report of what the configuration check
learned, as shown in Figure 2-5.
Figure 2-4:
Results from
the SQL
Server 2005
Express
system con-
figuration
check.
Figure 2-5:
Report from
the SQL
Server 2005
Express
system
configura-
tion check.
In addition to giving you a place to add your name and company, the
next screen, shown in Figure 2-6, lets you elect whether to install SQL
Server 2005 Express with its defaults, or customize your site’s configura-
tion by unchecking the Hide Advanced Configuration Options check box.
30 Part I: Welcome to SQL Server 2005 Express
Figure 2-6:
Electing to
make
advanced
customiza-
tions for
SQL Server
2005
Express.
For this example, I’ll go down the advanced configuration path. In many
cases, however, it’s wise to just accept the default installation options.
The next few dialog boxes prompt you for some important pieces of
information, including:
• Your instance name: Choosing the named instance of
SQLExpress suffices for most installations.
• Your service account: You can choose whether to specify a
Windows account or just use the built-in system account. The
latter is the path of least resistance. If you’re really curious about
security, check out Chapter 11.
The service account dialog box gives you a chance to request that
SQL Server and SQL Browser be started when the system starts.
This is a good idea for most installations, unless you’re really con-
strained for system resources.
• Your authentication mode: You can choose between Windows
Authentication Mode and Mixed Mode. The former is generally a
better choice; I discuss that in more detail in Chapter 11.
• Collation settings: Here’s where you can specify site-specific sort-
ing requirements.
Chapter 2: Downloading and Installing SQL Server 2005 Express 31
• Error and feature reporting: You can share, anonymously, infor-
mation about errors encountered by your SQL Server 2005 Express
installation, as well as those database features that you use.
After you finish specifying your site-specific requests, the wizard fin-
ishes installing, configuring, and validating SQL Server 2005 Express.
Figure 2-7 shows a successful installation.
You can take additional steps to further customize your SQL Server 2005
Express server. I discuss these steps in much more detail in Chapter 3.
Figure 2-7:
A successful
SQL Server
2005
Express
installation!
Although it’s not mandatory, you would be wise to also download and install
SQL Server Management Studio Express from the same place that you obtained
SQL Server 2005 Express. It’s an excellent (and free!) database administration
and query tool that can handle all of your SQL Server management tasks.
The best way to make sure that your installation went well is simply to try to
connect to your SQL Server 2005 Express database server and then run some
basic database operations. Just follow these steps:
For those of you with no access to SQL Server Management Studio, here’s
another way to connect to the database — using the SQLCMD utility — and
test your installation.
Parameter Purpose
-S Specify the server that you want to connect to
-U Provide your username
-P Provide your password
-d Which database to use
If you get in hot water, you can always ask SQLCMD for help:
SQLCMD /?
3. Type the following SQL:
CREATE DATABASE install_test
GO
If you receive another prompt (that is, no error message), then every-
thing is fine. If you want to drop this test database, just type the follow-
ing SQL:
DROP DATABASE install_test
GO
That’s all you have to do! You now have a working SQL Server 2005 Express
database server.
Chapter 3
T here are many reasons for using a database server like SQL Server 2005
Express. Perhaps you’re drawn by its no-cost price, or maybe you’re
attracted to its rich functionality. Regardless of your motivation, after you
install the database server (which I discuss in detail in Chapter 2), you still
have a few steps to take before you can take advantage of all that the product
has to offer. That’s what this chapter is all about.
To begin, I show you what to watch out for during installation, as well as how
to use the SQL Server Surface Area Configuration tool to deactivate nonessen-
tial features. Finally, you take a quick tour of how to connect to SQL Server
2005 Express from a variety of popular technologies.
When in doubt, install all capabilities from inception. You can’t easily add
certain features later. The next sections describe how to configure them after
you pass the installation stage.
36 Part I: Welcome to SQL Server 2005 Express
Don’t be in too much of a rush to start removing features and closing off pro-
tocols: Spend a little time examining your current and planned database
usage patterns before uprooting capabilities.
You can get to the SQL Server Surface Area Configuration utility in two ways.
The first lets you manage the database connectivity services and protocols;
the second is aimed at regulating available features.
Figure 3-1:
Configuring
services
and
protocols.
After you configure the protocols, your next duty is to administer the SQL
Server Browser service. This Windows service allows client computers to
locate your SQL Server 2005 Express database server.
If you plan on using only the default instance of SQL Server 2005 Express, or
your clients know the name of your server and instance details, you don’t
need to enable the SQL Server Browser service.
If you’re already running the SQL Server Surface Configuration utility, you can
skip Steps 1 through 3.
After you decide what features you want to enable, it’s easy to express your
wishes to SQL Server 2005 Express. Here’s how to make enable features:
Don’t be afraid that disabling a feature will permanently damage your server;
you can usually enable most features later.
Chapter 3: Setting Up SQL Server Express 39
Figure 3-2:
Configuring
services
and
protocols.
⻬ TCP/IP: This is, by far, the most popular communication protocol out
there. In fact, it’s the foundation of the Internet. Whenever you open a
browser and connect to a Web site, TCP/IP is the underlying standard
that makes it all possible, and is probably the best choice for your data-
base communication protocol.
⻬ Named Pipes: Generally used for both intra-machine and client/server
communication, this protocol is less frequently found on Internet-based
conversations. They are also somewhat less secure than TCP/IP.
⻬ Virtual Interface Adapter (VIA): As a protocol that is reliant on special-
ized hardware, the odds are you won’t likely encounter VIA as often as
TCP/IP or named pipes.
40 Part I: Welcome to SQL Server 2005 Express
⻬ Shared memory: As you would guess from its name, this protocol relies
on a fast, dedicated section of memory that SQL Server 2005 Express
uses for communication between the database and any clients that wish
to work with it. However, shared memory has one gotcha: Client applica-
tions and processes must reside on the same computer as the database
server, making this protocol somewhat irrelevant in a highly distributed
environment.
Now that you’re a wiz with SQL Server’s myriad protocols, it’s time to see
how to enable or disable any of the ones I just listed:
Figure 3-3:
The SQL
Server
Config-
uration
Manager.
Chapter 3: Setting Up SQL Server Express 41
• Right-click My Computer, select Manage, and then expand the
Services and Applications folder. The Computer Management
window opens (as shown in Figure 3-4).
Notice how the user interface is the same in both cases: The only differ-
ence is that in the former you’re running the utility stand-alone, while
the latter displays it as part of Computer Management.
You have three paths to follow from here:
• SQL Server 2005 Services: Here is yet another way to start, stop,
and disable your database services.
• SQL Server 2005 Network Configuration: This is where you enable,
configure, or disable any of the four services I just listed, for inbound
connections. I discuss Network Configuration in this section.
• SQL Native Client Configuration: Here is where you can specify
how you want outbound (that is, from your database to other data-
bases) protocols to work.
Figure 3-4:
The SQL
Server
Config-
uration
Manager
via
Computer
Manage-
ment.
42 Part I: Welcome to SQL Server 2005 Express
2. Click the entry for SQLEXPRESS (or whatever you named your data-
base server).
On the right side, you see entries for each of the protocols.
3. Right-click any protocol that you want to configure.
Figure 3-5 shows the TCP/IP protocol properties.
As you can see, you have several properties at your disposal, including
• Enabled: This property asks a very simple question: Do you or
don’t you want this service to run?
• Keep Alive: Aside from taking up space on your screen, this
property doesn’t do anything, so you can safely ignore it.
• Listen All: This setting controls how SQL Server 2005 Express,
your network, and your computer’s network cards all work
together. You can also switch to the IP Addresses tab for further
configuration.
• No Delay: Just like Keep Alive, this property is just there for
show; you can disregard it.
4. When you’re done, click OK to save your changes.
Figure 3-5:
Configuring
TCP/IP
properties.
Chapter 3: Setting Up SQL Server Express 43
Connecting to Your Server
You would be forgiven for assuming that after you complete all the tasks
necessary to set up your SQL Server 2005 Express database server, getting a
conversation going with it would be a cinch. As it turns out, the last step in
establishing a connection can often be the most frustrating. Try as you might,
you just can’t seem to hook up with your database.
Helping you get around this annoying obstacle is what this section is all about.
I give you an inventory of the major types of applications that you need to
connect to your server, along with what you need to do to help them “find”
your database.
SQLCMD has been around for quite a while, and consequently offers a wide vari-
ety of different options. You can get a list of all these options with these steps:
Figure 3-6:
Available
parame-
ters for
SQLCMD.
44 Part I: Welcome to SQL Server 2005 Express
Yikes! Look at all those parameters. Don’t worry — you don’t need to stay up
all night experimenting with the dozens of different options at your disposal.
Actually, when simply connecting to SQL Server 2005 Express, you only need
to concern yourself with a handful of these variables:
⻬ -U: The login ID of the user who is trying to connect to the database.
⻬ -P: The password for the user specified with the -U parameter.
If you omit the –U and –P parameters, SQLCMD tries to log in using your
Windows login.
⻬ -S: The server name, with the instance name as an optional appendage.
In many cases, just using ComputerName\SQLEXPRESS (where
ComputerName is the name of your server) works. Optionally, you can
substitute either localhost or . for ComputerName.
⻬ -E: Try to use a trusted connection, which happens to be default behav-
ior for SQLCMD. Just like its name implies, this type of connection
bypasses some of the security safeguards; if you try to pass a login and
password, SQL Server 2005 Express reports an error.
Figure 3-7:
The SQL
Server
Manage-
ment Studio
Express
connection
dialog box.
After you successfully connect, you should see a window similar to Figure 3-8.
For much more about using SQL Server Management Studio Express, check
out Chapter 4.
Figure 3-8:
A success-
ful SQL
Server
Manage-
ment Studio
Express
connection.
46 Part I: Welcome to SQL Server 2005 Express
Figure 3-9:
The ODBC
System DSN
dialog box.
3. Click Add.
The Create New Data Source dialog box appears, as shown in Figure 3-10.
4. From the list of drivers, pick either the SQL Native Client or the SQL
Server driver.
The SQL Native Client is the more current connectivity client, so I rec-
ommend that you select this option.
Chapter 3: Setting Up SQL Server Express 47
Figure 3-10:
Choosing
an ODBC
driver.
5. Click Next.
The Create a New Data Source to SQL Server dialog box appears, as
shown in Figure 3-11.
Figure 3-11:
Selecting a
database
server.
6. Enter the name and description of your connection, pick the server,
and click Next.
7. Choose the authentication method you want and click Next.
48 Part I: Welcome to SQL Server 2005 Express
Figure 3-12:
Final ODBC
settings
dialog box.
Figure 3-13:
Summary
of ODBC
settings.
Chapter 3: Setting Up SQL Server Express 49
Figure 3-14:
A suc-
cessful
connection.
⻬ Visual C# Express
⻬ Visual Basic Express
⻬ Visual C++ Express
⻬ Visual Web Developer
Connecting any of these products to SQL Server 2005 Express is a snap; for
example, here’s how to do it with Visual Basic Express:
Figure 3-15:
Choosing
SQL Server
Express.
Figure 3-16:
Advanced
SQL Server
Express
connection
settings.
Chapter 3: Setting Up SQL Server Express 51
6. Click Test to ensure that your connection is configured correctly.
If all goes well, you receive a message stating that the connection worked.
7. Click OK to complete the connection.
You now see your SQL Server 2005 Express database within the
Database Explorer window, as shown in Figure 3-17.
Figure 3-17:
A suc-
cessful
database
connection.
52 Part I: Welcome to SQL Server 2005 Express
Part II
Administering a
SQL Server 2005
Express System
In this part . . .
A database administrator’s work is never done. In a
single day, you can witness a collection of disparate
challenges requiring intervention, ranging from halting
runaway queries to satisfying new development requests
to setting up additional servers. But you don’t need to go
it alone.
First, I give you some ideas of how to plan for the future of
your SQL Server 2005 Express, as well as how you can use
some handy tools to look after your information. Next,
you discover some tips and tactics for monitoring and
managing your server’s performance. Finally, because no
database is an island, I show you how to take advantage of
replication and other techniques for accurately and safely
spreading your data across multiple servers.
Chapter 4
D on’t make the mistake of equating the zero-cost price point of SQL
Server 2005 Express with limited capabilities. On the contrary: This
product offers a rich feature set that will likely suffice for most of your data
storage needs. With that said, you should understand that there are some
restrictions that might affect you in the future.
In this chapter, I show you how to weigh any constraints that come with SQL
Server 2005 Express and decide when the time is right to upgrade. Although
many of you will never need to migrate, all of you should select a database
administration tool. Choosing and using the right administrative technology
is also a big part of this chapter.
This is more than just an academic exercise. As I show a little later in this
section, a time may come when you decide that you’ve outgrown your data-
base server, and that it’s time to upgrade. Two factors usually drive this deci-
sion: database usage and growth, which I describe now, and feature
restrictions, which is the highlight of the next part of this section.
⻬ More data: Like a drawer that becomes over packed, databases have
a tendency to accumulate more and more stuff over time. Archive and
purge as often as you like, but you’ll still probably notice your database
continuing to grow. As you see in the next section, this growth may pose
a problem when you approach 4GB of information in a single database.
Fortunately, you can create multiple databases that can each hold up
to 4GB of information.
⻬ Additional users: Set up a database with interesting information, and
the world will beat a path to your door (or at least to your database).
Fortunately, SQL Server 2005 Express has no built-in user restrictions, so
you should be able to gracefully support new users. Keep in mind that if
you want to support remote users, you need to enable and configure a
protocol such as TCP/IP or named pipes. Chapter 3 has more details
about these protocols.
⻬ Additional applications: Just as the amount of data and number of users
typically grow over time, you’ll (or people that work with you) naturally
discover new uses for SQL Server 2005 Express. You can confidently build
these new applications as long as you keep the product’s built-in restric-
tions in mind. And if you do find that you’ve outgrown SQL Server 2005
Express, you can easily move your application and database onto a more
feature-rich version of SQL Server 2005.
If you find that your needs outstrip the capabilities of SQL Server 2005 Express,
you’re probably on the upgrade path. On the other hand, these restrictions
may not be an issue for your installation. In that case, you can look forward
to running on SQL Server 2005 Express for a long time to come.
Chapter 4: Putting SQL Server 2005 Express to Work 57
⻬ Database size: This is probably the most significant limitation of SQL
Server 2005 Express. An individual database can’t exceed 4GB. This is
not a problem for many applications, but it might be for yours.
⻬ Memory: Even if your system is stuffed with memory, SQL Server 2005
Express only takes advantage of 1GB. This limitation typically hurts appli-
cations with large numbers of users or big data storage requirements.
⻬ Multiple CPUs: One way to boost performance is to run your database
server on a multiple CPU computer. Unfortunately, an additional CPU
won’t help a SQL Server 2005 Express installation. If you find that perfor-
mance is too sluggish, you can’t take advantage of this feature.
⻬ Full-text searching: Modern database-driven applications can store a
tremendous variety of information. A significant portion of this data is
often kept in the form of large blocks of text. Full-text search, which is
not entirely available in SQL Server 2005 Express, takes advantage of
sophisticated indexes to speed up retrieving this data. If your applica-
tion needs to speedily search and manipulate large volumes of this kind
of information, you want to consider upgrading. Luckily, SQL Server 2005
Express with Advanced Services does offer full-text search capabilities;
this product is also available as a free download from Microsoft. Check
out Chapter 18 for the details about using this feature.
⻬ Analysis services: In the past few years, an entire technology segment
has sprung up around business intelligence. These products help users
mine and analyze large blocks of data, which then produces meaningful
results that drive business activity. SQL Server 2005 now incorporates
its own collection of business intelligence features, which are known col-
lectively as Analysis Services. If you deal with hefty quantities of infor-
mation that you want to slice-and-dice directly via the database engine,
consider moving to a more feature-rich version of SQL Server 2005.
If you’re already using a third-party business intelligence product, you
probably won’t need to upgrade your database. Instead, these third-
party products can likely work with SQL Server 2005 Express to produce
high quality data analysis.
⻬ Integration services: No database is an island; this rule also applies to
SQL Server 2005. Most organizations have information spread among all
sorts of databases and applications. Eventually, you might need to load
this data into a SQL Server database, or vice-versa. Previously, integrat-
ing would require you to develop or purchase software to map and pos-
sibly transform the data so that it could correctly be placed into, or
extracted from, your database.
However, with SQL Server 2005, Microsoft has developed a collection
of robust transformation technologies in an effort to ease the often
painful process of synchronizing information. If you’re likely to need far-
reaching data conversions, you’ll probably benefit from moving to a
more full-featured edition.
58 Part II: Administering a SQL Server 2005 Express System
Although useful, trying to make sense of this data might cause you to reach for
the aspirin. If you’d like your information in a more palatable form, read on.
Figure 4-1:
The
SQLCMD
utility.
60 Part II: Administering a SQL Server 2005 Express System
Here are just a few uses you can find for SQL Server Management Studio
Express:
⻬ Database administration
⻬ Creating tables
⻬ Adding users
⻬ Granting permissions
⻬ Running queries
Figure 4-2:
The New
Database
dialog box.
62 Part II: Administering a SQL Server 2005 Express System
Figure 4-3:
Setting
autogrowth
policies.
In addition to the database naming and sizing parameters, you also have
all sorts of other settings to tinker with. You find them on the Options
page (shown in Figure 4-4).
In most cases you can leave these set to their default values.
Figure 4-4:
The
database
creation
options.
Chapter 4: Putting SQL Server 2005 Express to Work 63
6. After you’re done filling in details for all relevant prompts, click OK.
SQL Server 2005 Express now takes your requests and creates the data-
base. Once complete, you can see it in the Object Explorer, as shown in
Figure 4-5.
After the database is in place, here’s how you can create a table. If you left
SQL Server Management Studio Express running, you can skip Steps 1 and 2.
Figure 4-5:
A newly
created
database as
it appears in
the Object
Explorer.
64 Part II: Administering a SQL Server 2005 Express System
Figure 4-6:
Designing
a table.
Check out Chapter 8 for much more about how to design and build your
own tables.
7. After you’re ready to create the table, click the Save icon.
This generates the table, making it ready to receive information. You can
check the Object Explorer to see if things turned out the way you
wanted; Figure 4-7 shows what a completed table looks like.
After your tables are in place, SQL Server Management Studio Express has
some handy features dedicated to making interaction with your database
more straightforward. One helpful feature is its ability to generate SQL script
that you can plug into your applications. This automatically created SQL
script covers a wide variety of operations:
⻬ Create
⻬ Update
⻬ Insert
⻬ Delete
⻬ Drop
⻬ Alter
⻬ Execute
Chapter 4: Putting SQL Server 2005 Express to Work 65
Figure 4-7:
Viewing a
completed
table in the
Object
Explorer.
Note that depending on the database object in question, some of these com-
mands may not be available. Nevertheless, automatically generated SQL
scripts are a great way to jumpstart your database development.
Here’s all that you need to do to get started. (If you left SQL Server
Management Studio Express running from the earlier examples in this
chapter, you can skip Steps 1 and 2.)
5. Right-click the object you want to see, choose Script...As, and then
choose the action you want.
Depending on context, you have a range of options to choose from.
Don’t be afraid to experiment: This is a great way to figure out how to
write correct SQL statements. In this example, I’ve asked SQL Server
2005 Express to generate a SELECT statement for a table.
6. Choose the output method:
• New Query Editor Window
• File
• Clipboard
If you choose New Query Editor Window, Figure 4-8 shows what you see.
For all its benefits, SQL Server Management Studio Express has its limita-
tions. Some times you’ll probably wish that it did more, and that you didn’t
have to drop into Transact-SQL so often. If that describes you, never fear:
You have alternatives.
Figure 4-8:
Output from
the Script
Table As
command.
Chapter 4: Putting SQL Server 2005 Express to Work 67
Creating databases and tables is just a small part of what you can get done
with SQL Server Management Studio Express. As its name implies, you can
also handle all sorts of administrative tasks. For example, here’s how you
would create a new database login. (If you left SQL Server Management
Studio Express running from the earlier examples in this chapter, you can
Skip Steps 1 and 2.)
Figure 4-9:
Creating
a new
database
server login.
68 Part II: Administering a SQL Server 2005 Express System
6. Fill in the values for all the relevant settings for your new user.
There are five properties pages of information that you can provide:
• General: Here’s where you tell SQL Server 2005 Express the new
login user’s name, choose a security method, and request a default
database and language.
• Server Roles: Using this page, you can associate this new database
user with a set of predefined security profiles.
• User Mapping: Here’s where you associate a database user with
one from the Windows operating system.
• Securables: This is where you can set up highly specific security
criteria.
• Status: Here’s where you can set high level permissions, such as
whether the user can connect to the database, as well as whether
the login is enabled or not.
7. Click OK to complete the operation.
Your database login is now ready to go. If you’re curious about security,
check out Chapter 11.
Chapter 5
A lthough SQL Server 2005 Express comes with an attractive price (free!),
and a truthful promise of low maintenance requirements, you’re still not
completely off the hook with your babysitting responsibilities. In this chap-
ter, I show you how to get these chores done with the least amount of effort.
To begin, you find out how SQL Server 2005 Express allows you to easily run
separate user instances, thereby granting normal database users extra
powers within their own workspace. With that out of the way, I show you how
to configure the database server, followed by some helpful performance tips.
Even though these users are not administrators, within the context of their
own instance they have much higher privileges. However, because they’re in
their own instance, they can’t damage or otherwise disrupt the parent
instance of SQL Server 2005 Express. You enable user instances by setting a
configuration parameter, a task that I describe in the next section.
70 Part II: Administering a SQL Server 2005 Express System
The database engine automatically tunes many of the SQL Server 2005
Express parameters. In some cases, you know better than the engine; in most
cases, you’re better off leaving the parameters alone and letting the server do
its job. To keep things clear and prevent inadvertent changes, very few of the
parameters I describe are self-tuning.
⻬ The SQL Server Surface Area Configuration utility: This tool, which is
available by choosing Start➪All Programs➪Microsoft SQL Server 2005➪
Configuration Tools➪SQL Server Surface Area Configuration, lets you
decide which protocols and features to expose. Although it’s tradition-
ally used just after you install the product, you could also put it to work
when you’re in production.
⻬ SQL Server Management Studio Express: You can use this powerful and
flexible database management utility (available via download from
Microsoft) for all sorts of useful tasks, including configuring and cus-
tomizing your server. Figure 5-1 shows a list of all the pages at your dis-
posal for viewing and setting database properties. In this case, I’ve
selected the Memory page.
⻬ The sp_configure system stored procedure: No matter what your
database configuration, you should have access to the character-based
SQLCMD utility. SQLCMD — and sufficient permission — is all you need
to run this stored procedure. Because all installations have the ability to
run this stored procedure, I focus on it for the balance of this section.
Chapter 5: Maintaining a SQL Server 2005 Express System 71
Figure 5-1:
Setting
memory
options with
SQL Server
Manage-
ment Studio
Express.
First, a word or two about how to launch sp_configure. Just follow these
steps and you’ll be ready to make your changes:
5. After you run the sp_configure stored procedure, run the RECON-
FIGURE command for the change to take effect.
Depending on the setting you’ve changed, you may need to restart your
database server for the alteration to take effect. SQL Server 2005
Express sends a message telling you what to do next.
Before you embark on your database configuration adventure, note that SQL
Server 2005 Express considers some parameters to be advanced, which means
that you need to run sp_configure before even attempting to make any alter-
ations. I describe how to run this stored procedure in the preceding section.
Here’s what you need to do to gain access to these advanced parameters:
That’s it: You’re now ready to view and change advanced configuration
options. With these options now showing, you can now turn your attention to
customizing SQL Server 2005 Express to your liking. Here are some of the
major functional areas that you can control:
Figure 5-2:
The
Windows
Task
Manager.
76 Part II: Administering a SQL Server 2005 Express System
Figure 5-3:
Microsoft
Management
Console’s
SQL Server
performance
objects.
⻬ Databases in use
⻬ Active commands
⻬ Applications
Chapter 5: Maintaining a SQL Server 2005 Express System 77
⻬ Memory utilization
⻬ Locks
⻬ Object access
Figures 5-4 and 5-5 give you an idea of what you can learn from the Activity
Monitor.
Figure 5-4:
Viewing
user actions
in the
Activity
Monitor.
78 Part II: Administering a SQL Server 2005 Express System
Figure 5-5:
Viewing
locks in the
Activity
Monitor.
If SQL Server Management Studio Express isn’t to your liking, copious third-
party database monitoring and management tools are on the market. Most of
these offerings include their own views of performance management. If you’re
curious about some of these interesting products, have a look at Chapter 22
for more.
SQL Server 2005 Express also does a good job of tracking system activity
over time. You can view its logs to get a better idea of what’s been happening
on your database server. To launch the log viewer, follow these steps:
Figure 5-6:
Viewing
log files.
Figure 5-7:
Changing
virtual
memory
settings.
Chapter 5: Maintaining a SQL Server 2005 Express System 81
You may need to restart your computer for these alterations to take effect.
⻬ Defragment your disks: Like your closet and desktop, over a period of
time your disk drives become cluttered and disorganized. The damage
here is not aesthetic: A disorderly disk drive hurts performance by forc-
ing your computer to jump around to locate necessary information.
Luckily, Windows includes a handy disk defragmenter that you can use
to set things right again. Here’s how to use it:
1. Launch the Windows Disk Defragmenter by choosing Start➪
Programs➪Accessories➪System Tools➪Disk Defragmenter.
2. Click the Analyze button.
The Disk Defragmenter analyzes your disk and returns a recommen-
dation. If you’re lucky, you won’t even need to move on to Step 3.
3. If the Disk Defragmenter recommends that you defragment your
disk, click the Defragment button.
This step may take some time to complete, but be patient; it’s
worth it.
⻬ Leverage multiple computers: If you find that your database server is
overloaded, consider bringing additional computers into the picture.
Although SQL Server 2005 Express doesn’t have the full distributed com-
puting capabilities of its more expensive siblings, you can still gain bene-
fits by offloading work onto ancillary processors. If you’re curious about
using SQL Server 2005 Express in a distributed environment, take a look
at Chapter 6.
other hand, a proper index can cut out hundreds of thousands of extra
steps, often locating the right data in one read. Don’t be afraid to experi-
ment with indexes. If you want more guidance on this topic, see
Chapters 9 and 10.
⻬ Database statistics: When you ask SQL Server 2005 Express to locate or
modify information, the database engine must often choose among sev-
eral different paths. At first glance, each tactic appears to be an equally
qualified candidate. However, this is usually not the case: One path is
often much faster than its peers. To help the database server arrive at a
good decision, SQL Server 2005 Express has the ability to track statisti-
cal details about the data that makes up each index. You can use the fol-
lowing commands and stored procedures to determine the database
server’s statistics-gathering behavior.
• Collecting statistics: If you want to fine-tune the statistical accumu-
lation process, use the CREATE STATISTICS command. On the
other hand, if all you want to do is gather information across a
broad range of tables, simply use the sp_createstats system
stored procedure.
• Monitoring statistics: When statistics are in place, you can learn
more about them by invoking the DBCC SHOW_STATISTICS
command.
• Maintaining statistics: You can refresh your statistical sample by
running either the UPDATE STATISTICS command, or invoking
the sp_updatestats system stored procedure.
⻬ Better bulk operations: These tasks, which involve moving large blocks
of information in or out of your database, can often consume tremen-
dous amounts of system resources. You would be wise to consider the
optimal time to run these operations, as well as steps you can take to
reduce their effect on your server. Chapter 9 discusses bulk operations,
including the bcp utility, in more detail.
⻬ Use stored procedures, functions, and triggers: These centralized bits
of application logic stored in your database help protect your informa-
tion while standardizing and enforcing business rules. As a side benefit,
in certain cases, this concentration can also augment system respon-
siveness. Check out Chapters 14 and 15 to get a better picture of these
objects.
⻬ Efficient applications: It may sound obvious, but even the best, most
effectively structured database can collapse under the load of a badly
designed, improperly programmed software application. While you
may not win any friends among your developer compatriots, you need
to implore them to write their application code as economically as
possible.
Chapter 6
In this chapter, you discover how to take advantage of the SQL Server 2005
Express replication features, which enable you to spread your information
and processing load across multiple servers.
Replication is one of those topics that can overwhelm you with its nuances
and complexities. Luckily, it doesn’t have to. Simply stated, SQL Server’s
replication is an easy-to-implement, automated set of processes for distribut-
ing data among multiple machines. These computers can be in the same
physical location, or they may be spread across the world and connected via
the Internet. Regardless of your unique computer distribution, replication
helps keep your SQL Server 2005 Express database in sync with other data-
base servers.
84 Part II: Administering a SQL Server 2005 Express System
Given these common scenarios, replication offers many benefits for those
database administrators who take the time to implement a solid data distrib-
ution strategy. Here are some of its most compelling advantages:
Now that the fine print is out of the way, it’s time to look at all the replication
components and architecture.
Replication Concepts
At its heart, SQL Server replication consists of interaction among several
components, and each has an important role to play. To make things clearer, I
segregate them by whether they play a role in publishing or subscribing. I
also list them from the smallest objects to the largest.
Setting Up Replication
If you’ve read through the chapter to this point, you’re probably itching to
get started with replication. If so, this section is for you. Here’s what you
need to do to make replication a reality in your environment. To begin, I use
the transactional style of replication; you can easily choose one of the other
flavors if it’s more appropriate for your environment.
When setting up publications and subscriptions, you can elect to use a com-
bination of Transact-SQL and stored procedures, or you can put your effort
into SQL Server Management Studio. The graphical tools are so much easier
to use that for this example, I place all the focus on them.
Your first task is to set up the publication and articles on the publisher.
SQL Server 2005 Express lacks the capabilities to publish information: It can
only serve as a subscriber. This means that you need to run the next few
steps on a version of SQL Server 2005 (such as Workgroup, Standard, or
Enterprise) that supports information publication.
88 Part II: Administering a SQL Server 2005 Express System
Figure 6-1:
Choosing
objects
to be
published.
After you identify the objects to publish, you can also specify any filter-
ing criteria that you want applied to help reduce the number of items
sent for replication.
6. Decide if you want to create an immediate snapshot.
If you’re replicating to an empty database, choosing this option is a good
idea.
7. After you finish, review the publication’s properties, and click Finish
(as shown in Figure 6-2) to complete your work.
Chapter 6: Distributing Your Data with Replication 89
Figure 6-2:
Reviewing
details
about the
publication.
Figure 6-3:
Summariz-
ing a new
subscription.
That’s all you need to do. Depending on how you configured your publica-
tions and subscriptions, information should begin flowing around your net-
work. And the best part is that SQL Server is doing all the work. If you want
to observe the data movement, you can launch the replication monitor by
right-clicking the Replication folder in SQL Server Management Studio, and
choosing the Launch Replication Monitor option.
Part III
Adding and
Accessing a SQL
Server 2005
Express Database
In this part . . .
A fter downloading, installing, and configuring your
SQL Server 2005 Express database server, you’re
ready to start putting it to the test: storing, retrieving, and
managing information. For that reason, in this part I dis-
cuss important design concepts that you should keep in
mind as you plan your relational database.
C hances are that you went through all the work involved in acquiring and
then installing SQL Server 2005 Express so that you could store and
manage information, rather than just admire your server from afar. In this
chapter, I give you a good idea of how to set up your database to handle
whatever kind of data you throw at it.
Finally, SQL Server Management Studio Express, available for free download
from Microsoft, offers some very handy tools for designing and relating SQL
Server 2005 Express tables, so I spend some time at the end of this chapter
showing you how to make your own diagrams.
If all these data types aren’t enough for you, you can even create your own spe-
cialized data types via the SQL Server 2005 Express user-defined type feature.
You can use the CREATE TYPE statement to define your own, personalized
alias data types. This statement essentially creates a synonym for the data
type, which can be very useful when building your database.
For example, suppose your project has multiple database designers, and that
each of them is responsible for building some tables that will track addresses.
Furthermore, imagine that you want to standardize all your address fields
as variable length and character-based fields that hold up to 60 bytes
(VARCHAR(60)).
You could rely on each designer to adhere to your request, but you’re likely
to be sorely disappointed. The odds are that each designer will implement
his or her own interpretation of what an address should be. Some will choose
fixed character fields, while others will use the VARCHAR type, but set it at a
different length than the 60 you require.
Using the CREATE TYPE statement as your guide, here’s how to enforce con-
sistency for these fields:
Now, your designers can use ADDRESS whenever they create a table that
needs to track address information:
When SQL Server 2005 Express reports on your table, it helpfully provides
both the ADDRESS alias, as well as the fact that this alias translates to a
VARCHAR(60).
96 Part III: Adding and Accessing a SQL Server 2005 Express Database
Logical design
Building a logical design is quite simple. All you need to do is identify the
major entities, itemize any of their attributes, and determine how they relate
to other entities. Entities are specific, real-world objects that exist in your
database. Attributes are characteristics of each entity.
Although end-users can be picky and a real drag to deal with, interviewing
the eventual users of your database to see what they want you to build is the
only way to build a good database. As a bonus, they probably have a good
idea what real-world entities exist, as well as how the entities relate to each
other. By including the user in the design process, you can go a long way
toward building something of value and quality.
⻬ The ticket
• Ticket holder’s name
• Price paid for ticket
• Date and time ticket was purchased
⻬ The seat
• Seat location
• List price
⻬ The event
• Date of the event
• Time of the event
Chapter 7: Planning Your Database 97
After you categorize all the major entities, all you need to do now is figure out
how they relate. Armed with that intelligence, you can then build your entity
relationship model. In fact, many tools on the market make drawing your
entity relationship model a breeze. Figure 7-1 shows a nice example of a
simple entity relationship model from the ticketing scenario. I used Microsoft
Visio to draw this diagram.
As you build your entity relationship diagrams, try to use natural language to
describe their relationships. This goes a long way toward helping you design
a database that works in the real world.
Physical design
A database’s physical design refers to concrete, real-world, database-oriented
objects. These include
⻬ Tables
⻬ Columns
⻬ Relationships
⻬ Indexes
Now that your logical design is done, the last step to building a working, real-
world relational database is to convert the logical database into a physical
database.
Although exceptions always abound, the general rule is to take each major
entity and turn it into a table. In turn, all attributes for each entity become a
column. If a many-to-many relationship exists between two tables, you proba-
bly need to create a third table to serve as a storage area for the attributes
that identify the relationship.
98 Part III: Adding and Accessing a SQL Server 2005 Express Database
Make sure that you’re not turning an attribute into its own table. For exam-
ple, if you’re tracking information about a customer, the phone number is
usually an attribute of the customer entity, which means that it would belong
as a column in the Customer table. However, if you expect to track variable
quantities of phone numbers for a customer, you could consider making the
phone number its own entity and giving it a dedicated table.
When you define your tables and columns, your next step is to use the relation-
ships from your entity relationship diagram to help you figure out what kind
of indexes and keys you need to build. I discuss relationships among tables,
including primary and foreign keys, in much more detail in Chapters 8 and 10.
All this is great, but suppose that all you want to do is add a new table and
relate it to one of the other tables already on your palette. Simply follow
these steps:
Figure 7-2:
The Visual
Studio
database
diagram
tool.
100 Part III: Adding and Accessing a SQL Server 2005 Express Database
Normalization
After you define your tables and columns, making sure you conformed to the
best practices and rules of relational database design is a good idea. One of
the best-known rules is normalization, which I discuss throughout the rest of
this chapter.
While you might think that database normalization means that you’re forced
to clean up your information and remove any eccentric, troublemaking, or
otherwise wacky data, it’s actually just a collection of increasingly rigid prin-
ciples and guidelines that you can use to conceive a well-designed relational
database.
In this section, you find out about the three major normalization rules,
including when you should use them. And because all rules are made to be
broken, the next section clues you in on some situations when you can side-
step these regulations.
So far, so good. But what happens when Mike Brady joins the firm? He has
six children, a wife, and a maid, which — in addition to being an insurance
nightmare — means that you must now change this table’s structure. That’s a
risky move, one that could break applications that were built with the origi-
nal table in mind. Here’s where the first normal form comes to the rescue.
Chapter 7: Planning Your Database 101
Tables 7-3 and 7-4 can handle employees with zero, one, or many dependents;
no changes are necessary to cope with more dependents.
Now the Bradys can have ten children if they like, and your database and
applications can handle these joyous events without any extra work for you.
In this case, suppose that you have built a database to track heating and air
conditioning work that your company delivers. Table 7-5 shows a small
sample list of these procedures.
102 Part III: Adding and Accessing a SQL Server 2005 Express Database
For this table, assume that the primary key is the combination of the
Customer and ServiceDate columns, while the Procedure column con-
tains a fixed set of services offered by your firm. Storing this text in this table
violates the second normal form; it is not functionally dependent on the pri-
mary key. It would be a better design if you separated these procedures into
their own table, and placed an identifier in the maintenance history table.
Tables 7-6 and 7-7 make this clear.
This design is cleaner and more efficient. For one thing, if you decide to
change the exact wording of a procedure, you need to change it in one place
only. You reduce the chance for errors, and help improve consistency. You
Chapter 7: Planning Your Database 103
also store substantially less data in the Maintenance History table,
because the ProcedureID column now holds a simple number, rather than a
long set of text.
Although it’s not obvious, this table violates the third normal form. The
Customer column is not the primary key (although the combination of it
plus the ServiceDate column is). However, it does define the Outstanding
Balance column, which really belongs in a master table, rather than in this
set of detailed data. To get in line with the third normal form is pretty easy in
this case, as you can see in Tables 7-9 and 7-10.
Now all the header information is contained in the Customer Master table
(Table 7-9), and the detailed maintenance records are in the Maintenance
History table (Table 7-10). It can be tricky to figure out when you break any
of these rules. As you’ll see in a moment, sometimes breaking a rule is smart.
Historical data
Imagine that you’re processing millions of rows a month. These rows are stored
in one main transaction table. In most cases, customers are only interested in
recent transactions — those that have happened in the past two months.
For situations like this, splitting your data into at least two tables is okay: cur-
rent and historic information. These tables would have an identical structure,
but would contain fresh and old data, respectively. Every month, you could
move records from the current table into the archive table, perhaps as part of
a large batch processing operation.
Calculated values
In most cases, permanently storing any calculated values (sums, averages,
and so on) in your database is not wise. Instead, you’re better off calculating
them at runtime. This avoids problems with stale data, especially if the under-
lying detail data changes often. In some cases, however breaking this rule and
keeping these calculated values in your database makes sense. This usually
happens with massive amounts of data to process, and very little time to do it.
Chapter 7: Planning Your Database 105
For example, suppose that you’re maintaining a distributed retail management
system. Your company is doing very well; you have tens of thousands of
customers each day, which yields hundreds of thousands of transactions
each month. What if your users want to run queries that summarize these
transactions in a number of different ways? If you try to calculate these
answers at runtime, you run the risk of performance degradation. In this type
of scenario, maintaining a lookup table that contains commonly requested
calculated values makes sense. You could then update this table during times
when there isn’t much activity. Table 7-11 is an example of a summary table.
Now, when users need to get calculated summary data, they can consult
this table instead of launching fishing expeditions through the main transac-
tion table.
When you’re faced with a massive data table that you want to split up and de-
normalize, and you’ve chosen to upgrade to a more feature-rich edition of the
SQL Server product family, consider using the partitioning feature. This fea-
ture lets you break up a table and spread its load across your environment.
Three types of partitioning are available:
W hen you want to store information in SQL Server 2005 Express, your
first responsibility is to define a database that will serve as a container
for your records. Your next job is to create the tables where the actual data
will reside, along with any restrictions on what you can place in these tables.
Finally, by defining relationships among your information, you help SQL Server
2005 Express ensure good data integrity and protect your business rules.
In this chapter, you see how to accomplish all these tasks. To begin, you get
the hang of using the handy (and free) SQL Server Management Studio Express
tool, which lets you do all the database management tasks I describe through-
out the chapter. Because you may have other preferences when working with a
data management tool, I also show you some different approaches you can take
to achieve the same results.
108 Part III: Adding and Accessing a SQL Server 2005 Express Database
⻬ View the structure of your SQL Server 2005 Express instance, including
databases, tables, views, stored procedures, and so on.
⻬ Connect to other SQL Server instances.
⻬ Perform many administrative tasks.
⻬ Run queries and other data access jobs.
⻬ View results, or export them to text files.
Not bad for a free tool! You can download it from the Microsoft Web site
(www.microsoft.com/sql/editions/express/default.mspx); instal-
lation is a snap. Here’s a brief tour through the product, highlighting those
features that you’re most likely to use right away.
Depending on how you’ve configured your environment, you’ll notice that the
user interface is divided among several components. One of the most impor-
tant of these entities is the Object Explorer, which I describe next.
⻬ The connection: This portion of the tree tells you about the connection,
including the names of the computer and SQL Server 2005 Express
instances.
⻬ Database details: If you expand the Databases folder, you’re treated to a
collection of really important system folders. These include a list of
system databases, as well as an inventory of your own databases.
Chapter 8: Creating Databases, Tables, and Relationships 109
Expand any of your database folders and you see details broken out as
follows:
• Database Diagrams: Here’s where you can get a graphical view of
your information, including the relationships you’ve defined
among objects in your database.
• Tables: The contents of this folder are divided between system
tables, which are provided for and looked after by SQL Server 2005
Express, and user tables. Each table further breaks down into
columns and indexes.
• Views: Views are virtual tables, composed of information from one
or more “real” tables. If you expand this folder, you see a list of
both system and user-defined views. Opening a particular view
yields a list of the columns that make up the view.
• Synonyms: These are substitute names for objects in your
database.
• Programmability: Here’s where you can get a list of all your
system and user-defined stored procedures, including their input
and output parameters. You can also find out about your functions
via this tree entry.
• Security: This folder itemizes all the users who have access to
your database.
⻬ Security: The Security folder contains all the login names for people
who are authorized to use your database server, along with the server
roles and credentials you’ve set up. Note that this folder is different than
the Security folder within a database. The latter simply lists all those
already authorized database server users who also have access to that
database.
⻬ Server Objects: This folder holds details about those devices that
you’ve defined for backup purposes, as well as any servers linked to this
database server, and any triggers that have been defined on the server.
⻬ Replication: SQL Server 2005 Express offers the ability to subscribe to
data feeds from other SQL Server instances. This folder cites any active
subscriptions.
⻬ Management: You can view a collection of your SQL Server logs, includ-
ing current and archived versions. These are excellent sources of diag-
nostic information about your database server.
Figure 8-1:
The SQL
Server
Management
Studio
Express
Object
Explorer.
To get the latest-and-greatest view of everything about your SQL Server 2005
Express instance, right-click anywhere on the Object Explorer tree and
choose Refresh.
When you’re comfortable working in the workspace, you can decide how and
where you want your results to appear. You have three options; click one of
these icons at the top of the window:
Chapter 8: Creating Databases, Tables, and Relationships 111
⻬ Text: This formats your output into simple text, and places it in the
Output window.
⻬ Grid: This option provides more attractive results, placing them into a
grid at the bottom of the Output window.
⻬ File: This is the “to-go” option for your queries. SQL Server 2005 Express
takes the results and nicely places them in a text file.
Databases
Creating, altering, and deleting databases are significant events in the life of
your SQL Server 2005 Express environment. However, none of these tasks
requires much heavy lifting, as you’ll now see.
Creating a database
To create a database, just follow these steps:
Figure 8-2:
Creating a
database in
SQL Server
Management
Studio
Express.
Figure 8-3:
Setting
database
properties in
SQL Server
Management
Studio
Express.
Chapter 8: Creating Databases, Tables, and Relationships 113
Renaming a database
After you have a database in place, renaming it is easy:
Deleting a database
When the time comes to say goodbye to a database, all you need to do is
follow these steps:
Tables
Tables are where the rubber meets the road in a database: they dutifully
store your vital information. I show you how to create and maintain these
important structures.
Creating a table
After you decide that you want to create a new table, bringing it into exis-
tence is easy. You have two major routes that you can follow: SQL/application
114 Part III: Adding and Accessing a SQL Server 2005 Express Database
code versus a graphical tool. In the following list, I describe the advantages
and drawbacks of each:
Figure 8-4:
Creating a
table with
SQL Server
Management
Studio
Express.
Chapter 8: Creating Databases, Tables, and Relationships 115
If you change your mind, and suddenly become very curious about the
CREATE TABLE statement, many of these graphical tools can generate the
SQL for you, as well as show you what SQL they used to create your table.
You now have a table that’s ready to be filled with important data, plus the
actual code that built the table. How can you run this code again? You can
run the code in at least two ways. First, you can simply open the file in SQL
Server Management Studio Express, and click the Execute button to launch
the SQL. Alternatively, you can use the SQLCMD tool to run the script from
the command line.
SQLCMD is a very helpful utility that allows both batch and interactive
access to SQL Server 2005 Express. Follow these steps to use SQLCMD:
Make sure that your script file is in the right directory; SQLCMD can’t find it
otherwise. Alternatively, provide a full path to the file.
Modifying a table
If you made a mistake when you created a table, don’t despair! Modifying the
table to your liking is no big deal. You can choose from several approaches
when amending an existing table. The right approach is largely dependent on
what kind of modification you’re making.
If you’re only renaming a table, here’s the simplest way to make it happen:
That’s all renaming takes! Now, if you want to make more complex changes,
you’ll probably need to use straight SQL or a more robust graphical tool. This
is true for any of these kinds of adjustments:
⻬ Adding a column
⻬ Changing a column’s data type
⻬ Removing a column
⻬ Changing default values, constraints, and so on
This is just a partial list; several other types of alterations require a visit to
SQL land. Luckily, the SQL for these kinds of modifications is quite easy.
Here’s how to proceed:
Removing a table
Getting rid of tables you no longer need is very easy. Just follow these
simple steps.
Relationships
In terms of SQL Server 2005 Express, relationships do not mean how well
your data gets along with its friends, co-workers, or neighbors. Instead, rela-
tionships describe the interdependencies among the data stored in different
tables. Relationships have three main classes:
Enforcing relationships
As a database designer or developer, you specify relationships when you
create the table. You can also add them after the fact, by creating or altering
tables. But after you create your relationships, how do you enforce them?
Thankfully, enforcement in SQL Server 2005 Express doesn’t require guilt or
the threat of force. Instead, all you need to do is use a combination of indexes
and your table definition syntax.
If, for some reason, the order gets added without a corresponding customer,
then your relationships have been damaged. Foreign keys help you make sure
that SQL Server 2005 Express automatically enforces these rules.
Constraints
Primary and foreign keys actually belong to a large class of database rules
known as constraints. There are two other constraints, both of which keep
your data nice and clean, and your database applications running smoothly:
⻬ UNIQUE: This constraint tells SQL Server 2005 Express not to allow two
or more rows to have the same values for a given column or group of
columns. This is very similar to the primary key constraint, but the
unique constraint does allow null values in a column.
Chapter 8: Creating Databases, Tables, and Relationships 121
⻬ CHECK: This is a very interesting and useful constraint. Basically, it
tells SQL Server to prevent any violations of business or data rules that
you specify when you create the table. For example, you might define a
column to hold age information, and require that any values placed into
this column range between 0 and 110. With this constraint in place, SQL
Server 2005 Express carefully monitors activity related to this column.
Any attempts to violate the constraint results in an error, and Express
rejects the invalid data.
Creating a relationship
Ideally, you’ll create all your relationships when you define your tables.
However, what happens if you forget to set up an important relationship,
such as a foreign key relationship? Never fear — you can never be too late in
building good relationships among your data.
For this example, I show you how to use the SQL Server Management Studio
Express data diagramming tool to create a foreign key relationship. Assume
that you’re building a system to track sweepstakes entries. A Contests
table, which holds information about all your contests, and an Entries
table, which holds details about each entry for a given contest, are the two
most important tables. Here’s a portion of each of these two tables:
After you create the tables, you suddenly realize that you need to set up a
foreign key relationship between the two tables. Here’s how to fix things:
Figure 8-5:
Setting up a
relationship
with SQL
Server
Management
Studio
Express.
The first one is the Tables and Columns dialog box. It generates an auto-
matic name for the relationship, as well as displays the columns and
tables that make up the relationship.
8. Assuming that you built your diagram correctly, click OK in this
dialog box.
The Tables and Columns dialog box closes, and the Foreign Key
Relationship dialog box opens.
Chapter 8: Creating Databases, Tables, and Relationships 123
9. Feel free to make any additional changes to the data in this dialog box.
For example, you may want to set up a rule about what should happen
when you delete a row in the primary table, which is what’s happening
in Figure 8-6.
Figure 8-6:
Defining
behavior for
DELETE
with SQL
Server
Management
Studio
Express.
Figure 8-7:
The Foreign
Key Rela-
tionships
dialog box.
To begin, I tell you all about the SQL standard, along with Microsoft’s flavor
of it, known as Transact-SQL. The next part of the chapter dives into a brief
overview of the various types of tools at your disposal for easy communica-
tion with SQL Server 2005 Express. Finally, I show how you can use SQL to
straightforwardly create, modify, and remove information in your SQL Server
2005 Express database.
What Is Transact-SQL?
Like many people new to SQL Server 2005 Express, you probably keep hear-
ing of “Transact-SQL,” and you wonder what it is. Another question you may
be pondering is what the difference is between Transact-SQL and plain old
SQL. Not to worry: In this section, I answer these and many other questions.
126 Part III: Adding and Accessing a SQL Server 2005 Express Database
⻬ Web pages
⻬ Application code, such as Visual Basic, Visual C#, and so on
Chapter 9: Talking to a SQL Server 127
⻬ Scripts that can be run from the SQLCMD utility
⻬ Packaged enterprise applications
Here’s an example of some basic, standard SQL for inserting a record into a
table:
With this code, you can’t easily recover from a problem. Many kinds of prob-
lems can derail even a simple INSERT statement such as this one. These
include referential integrity violations, data type issues, permission prob-
lems, and so on.
BEGIN TRY
INSERT INTO inventory (part_number, part_name,
part_count)
VALUES (‘Gasket’,1811,12);
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() as ErrorNumber,
ERROR_MESSAGE() as ErrorMessage;
END CATCH;
In this case, notice the error handling logic. Gracefully handling a problem
is much easier. This particular INSERT statement is erroneous; the part_
number and part_name fields are reversed. Transact-SQL provides great
diagnostics to help resolve the problem:
245
Conversion failed when converting the varchar value ‘Gasket’ to data type int.
You can add logic to check the error number and take appropriate action
based on the kind of error that you run into. By chaining these kinds of error
handlers together, you can build more sophisticated and robust database
applications.
Accessing Information
After you master the history of SQL and its powerful progeny, Transact-SQL
(refer to the earlier sections of this chapter), you can use the SQL Server
2005 Express database for what it does best: store, manage, and retrieve
information.
128 Part III: Adding and Accessing a SQL Server 2005 Express Database
Your first decision is to pick one or more tools to get access to your data. The
market abounds with choices:
Figure 9-1:
A query in
SQL Server
Manage-
ment Studio
Express.
Chapter 9: Talking to a SQL Server 129
Figure 9-2:
Microsoft
Access
working
with SQL
Server 2005
Express.
Figure 9-3:
Microsoft
Query
identifying
information
to return to
a spread-
sheet.
130 Part III: Adding and Accessing a SQL Server 2005 Express Database
After you make your request, Microsoft Query returns data to your
spreadsheet, which is what Figure 9-4 shows.
⻬ Application development platforms: Professional application develop-
ers use these technologies to build robust, powerful database-driven
applications. Figure 9-5 shows Microsoft Visual Studio interacting with a
SQL Server 2005 Express database. In this case, a window shows all the
tables for a given database, along with an active Query window for a par-
ticular table.
⻬ Packaged enterprise applications: Many of today’s enterprise applica-
tions embed a relational database to store their information. Usually, the
application vendor does not broadcast this reality. In fact, certain ven-
dors hide the database from anyone who wants to access its information
without going through the packaged application. In many cases, you can
use one of the tools that I mention in this section to work with your
embedded SQL Server 2005 Express database.
⻬ Homegrown applications: This final category refers to any database-
accessing applications that may have been built for you, or by you. In
fact, you may be developing your own database application right now. In
any case, just like clothing that’s made to measure, these applications
are tailored for your organization’s specific data processing needs.
Figure 9-4:
Microsoft
Excel
displaying
SQL Server
2005
Express
data.
Chapter 9: Talking to a SQL Server 131
Figure 9-5:
Microsoft
Visual
Studio
interacting
with SQL
Server 2005
Express.
For the purposes of these next sections, imagine that you’re starting the first
premium ice cream stand of a chain. You use these few simple tables to help
track vital information about your growing business.
Because an ice cream store without any products wouldn’t be much use,
Table 9-1 tracks details about your exciting flavors.
132 Part III: Adding and Accessing a SQL Server 2005 Express Database
The PRIMARY KEY instruction in this SQL tells SQL Server 2005 Express to
make sure that no duplicates are in the FlavorID column. Primary keys help
keep the information you store in your database accurate.
Next, your business will melt faster than a Mr. Softee cone in August if you
don’t have any sales, so you use Table 9-2 to keep an eye on your revenue.
The REFERENCES section of the preceding SQL is known as a foreign key con-
straint: It prevents any records being entered into this table that do not have
a corresponding flavor in the Flavors table.
With your tables now ready for business, you can start filling them with data.
You can use the INSERT statement for this job. First, you insert data into the
Flavors table:
INSERT INTO Flavors VALUES (1, ‘Apricot Ambush’, 0.54, 2.35, 3.25)
INSERT INTO Flavors VALUES (2, ‘Banana Blizzard’, 0.73, 2.35, 3.25)
INSERT INTO Flavors VALUES (3, ‘Chocolate Chug’, 1.08, 2.35, 3.25)
After you put information into the Flavors table, you’re now ready to add
data to the Sales table:
This statement means that on June 10, 2006, you sold $5.75 worth of Chocolate
Chug. You could simply key in the flavor name in the Sales table, but doing so
would be redundant; using a numeric code that you can use to look up the
name in the Flavors table is for the best.
What happens if you try to insert a row in the Sales table without a corre-
sponding row in the Flavors table? Because I thoughtfully put a foreign key
constraint on the Sales table, any attempt to violate this referential integrity
directive causes an error:
In addition to the foreign key constraint you just saw, SQL Server 2005
Express has other capabilities that help protect your information. For exam-
ple, see what happens if you try to insert a row with a duplicate primary key
in the Sales table:
These kinds of protection are very important. Without it, you could easily
end up with duplicate or otherwise damaged information — causing you to
make incorrect decisions.
Bulk Inserts
Many applications require you to load large quantities of information into
your database at one time. SQL Server 2005 Express offers two helpful tools
that simplify and speed this previously challenging task. You can use the
BULK INSERT statement from SQL, or the bcp utility from the command line.
For example, imagine that your cash registers generate a large file (called
Register.txt) at the end of the day, and that you want to load this file into
your Sales table. Suppose that the raw file looks like this:
3422,3,6/10/2007,9.00
3423,8,6/10/2007,3.50
3424,1,6/10/2007,2.75
3425,15,6/10/2007,12.25
3426,22,6/10/2007,10.00
3427,30,6/10/2007,18.00
Pay attention to the layout of your raw data files. Getting confused about the
exact character that separates each field is very easy. The fields themselves
may be in the wrong order, which causes no end of aggravation as you try to
decipher what’s happening when you insert information.
A lot can go wrong with a bulk insert process. Problems can range from
syntax errors, data issues, and so on. Test this type of operation with a small
data file before attempting a massive upload. Otherwise you may potentially
damage your database, which is not much fun.
Format file
Ideally, your raw data files exactly match the layout of your tables.
Unfortunately, things are rarely this simple in the real world. Significant
differences likely exist between what you’re given and what you need.
Fortunately, you can create a format file that tells SQL Server 2005 Express
exactly what to expect from these data files.
To easily generate a format file, just run the bcp utility as I show here. SQL
Server 2005 Express walks through the specified table and file, and gives you
the option to create a format file at the end:
After you finish defining this file, you can use it for all future bcp runs.
In this section, you get the hang of using SQL to write powerful queries to
make sense of what’s in your database. For clarity’s sake, I continue with
the ice cream store example.
For example, imagine that you want to get a list of all the flavors that you sell.
Here’s what your query looks like:
This information is the minimum amount that you can provide to the SELECT
statement. Here’s a small segment of its results:
Because you provide a wildcard, this query returns all columns and all rows.
But what if you only want the name of the flavors, and no other columns? A
simple change to the query does the trick:
FlavorName
---------------------------
Apricot Ambush
Banana Blizzard
Chocolate Chug
...
...
Watermelon Whale
Vanilla Vertigo
Vanilla Volcano
If you mistakenly enter a non-existent table or column name, SQL Server sets
you straight:
If you want to see multiple columns, just put commas between their names:
FlavorName SinglePrice
----------------------------------- -----------
Apricot Ambush 2.35
Banana Blizzard 2.35
Chocolate Chug 2.35
...
...
Watermelon Whale 2.35
Vanilla Vertigo 2.35
Vanilla Volcano 2.35
You can change the output order of the columns by simply moving them
around in the SQL statement.
FlavorName CostServing
---------------------------------------- -----------
Apricot Ambush .54
Banana Blizzard .73
Vanilla Vertigo .59
You can get fancier with filters. Here’s a query with two filters:
This query returns all your low-cost vanilla-named flavors. The AND keyword
does just what it says — it tells SQL Server 2005 Express to combine the two
parts of the WHERE clause. In this case, both sides must be true to return a
row: The row must have a CostServing less than 1.00, and a FlavorName
that begins with Vanilla. If only one of these is true, SQL Server 2005
Express doesn’t return that row.
You can build very rich filters that combine multiple criteria in a single state-
ment. You can use AND, OR, and NOT to construct various combinations of
filter conditions. These are known as Boolean searches. Here’s an example of
a more complex Boolean search:
What’s this query doing, exactly? SQL Server 2005 Express interprets it, and
applies the following logic:
FlavorName CostServing
---------------------------------------- -----------
Apricot Ambush .54
Vanilla Vertigo .59
Banana Blizzard .73
Chocolate Chug 1.08
Watermelon Whale 1.17
Vanilla Volcano 1.17
See how the CostServing column nicely sorts the rows? You can sort by
multiple columns; just separate them with a comma:
In this example, SQL Server 2005 Express firsts sort the results by the
CostServing column, and then uses the contents of the FlavorName
column to sort any rows that have the same CostServing value.
Built-in functions
SQL Server 2005 Express includes many helpful built-in functions. These func-
tions take large quantities of data and group them into a single result. Here
are some of the more popular basic aggregation functions, along with how
you can use them:
⻬ Summing up data: You can use the SUM() function to add up the values
in a particular numeric column. For example, here’s how you would get
the sum of all transactions in the Sales table:
SELECT SUM(Amount)
FROM Sales
Chapter 9: Talking to a SQL Server 141
SQL Server 2005 Express adds up the values of the Amount column for
all the rows in the table. Of course, you’re free to provide a filter if you
only want the sum of values for a smaller set of data:
SELECT SUM(Amount)
FROM Sales
WHERE DateOfSale BETWEEN ‘1/1/2006’ AND ‘12/31/2006’
These functions generally require numeric columns. If you try to run a
function on a character column, SQL Server 2005 Express complains:
SELECT SUM(FlavorName)
FROM Flavors
Suppose that you run a query that includes a variety of aggregation functions.
If you don’t provide column names, your output is difficult to comprehend, as
shown in Figure 9-6.
You can slightly alter your SQL to provide meaningful output column names,
which Figure 9-7 shows.
Joining tables
You can build powerful queries with relatively simple SQL. So far in this chap-
ter, though, I’ve showed you only single-table queries. Of course, the real
world is rarely that black-and-white. It’s now time to enter the colorful world
of multi-table joins.
Figure 9-6:
Unaltered
aggregation
function
output.
Chapter 9: Talking to a SQL Server 143
Figure 9-7:
Aggregation
function
output with
easier-to-
understand
column
names.
Joins are possible only with common keys, so before you write a join, you
need to figure out what the two tables have in common. You can then use
that common key to construct your query. For example, suppose that you
want to get a list of all the sales for a particular flavor of ice cream. Here’s
what that query would look like:
Here’s how SQL Server 2005 Express works with this query:
2. Join the data from each table for any rows that have the FlavorID
columns in common.
3. Apply a filter to make sure the flavor is Watermelon Whale.
4. Return the results sorted by the date of sale.
The join takes place during Step 2. Note that SQL Server 2005 Express may
first elect to filter for any rows that are Watermelon Whale, and then locate
transactions for that flavor.
Standard joins return only those rows that are present in both tables. What
happens when only one table has a given row? For example, how would you
get a list of those flavors that haven’t seen any sales? You use outer joins in
these situations to find the exact information you need. Here’s an example of
an outer join:
FlavorName DateOfSale
---------------------------------- -----------------------
Chocolate Chug 2006-12-30 18:35:01.000
...
Walnut Wipeout NULL
...
Banana Boom 2006-12-30 21:14:23.000
Grape Gusher NULL
What can you infer from this data? Unfortunately, the Walnut Wipeout and
Grape Gusher flavors have not sold at all. The LEFT OUTER JOIN clause
tells SQL Server 2005 Express to return flavors, even the ones with no sales.
That’s why the DateOfSale column has a value of NULL; the Sales table
has no related rows. You use LEFT OUTER JOIN here because the Flavors
table is on the left part of the statement; if it were on the other side you
would use RIGHT OUTER JOIN instead:
For example, imagine that you want to get a list of the names for all the fla-
vors that have had at least one sale between $10 and $15. You could write a
program to retrieve all rows from the Sales table, and then keep internal
counters, but a subquery does the job quickly:
SELECT FlavorName
FROM Flavors
WHERE FlavorID IN
(SELECT FlavorID
FROM Sales
WHERE Amount BETWEEN 10.00 AND 15.00)
What’s happening here? When you’re faced with either building or analyzing
a subquery, starting with the innermost query and then working your way
out is always best. In this case, SQL Server 2005 Express processes the query
as follows:
1. Get the values from the FlavorID column in the Sales table.
2. Apply a filter so that only those rows that have an Amount of between
$10 and $15.
This step likely finds thousands of candidates.
3. Return those FlavorID values to the outer query.
4. Using the returned FlavorID list, look up the values in the
FlavorName column from within the Flavor table.
5. Only return a unique list of FlavorName column values to the user;
there’s no need to show the same value twice or more.
Subqueries are helpful for other types of operation, too. For example, a slight
tweak to the SQL statement instructs it to delete all those flavors where any
transaction was less than $2.99. This treatment is somewhat harsh for your
less-than-popular flavors, but it works:
DELETE
FROM Flavors
WHERE FlavorID IN
(SELECT FlavorID
FROM Sales
WHERE Amount < 2.99)
146 Part III: Adding and Accessing a SQL Server 2005 Express Database
The simplest thing you can do to increase your queries’ speed is to provide
proper indexing. Think of an index as a shortcut that SQL Server 2005
Express can use to find your data.
For example, suppose that you need to find your friend’s entry in the phone
book for a large city. The phone book for this city contains millions of entries.
Furthermore, imagine that you have a poorly designed phone book: All the
entries are in random order, rather than in the familiar last-name order of
most sane phone books. Of course, in reality a normal phone book is indexed
by last name. Without this index, you would have to open the book and start
paging through all the names until you ran across your friend’s name. Chances
are that after five or ten pages, your eyes would glaze over and you’d probably
miss it. SQL Server 2005 Express doesn’t get tired, but it can take a long time
to find information when no index is available.
Contrast this fatiguing experience with what happens when the phone book is
indexed: You immediately open the book to the vicinity of your friend’s name,
and then review a much smaller set of information to find the right entry. For
SQL Server 2005 Express, things are even better: Rather than churning
through the entire table, it is able to find the right record in milliseconds.
Figure 9-8 shows an example of two tables, their columns, and their primary
key indexes. I’ve also opened a window showing properties for one of the
indexes.
Figure 9-8:
Index
information
as reported
by SQL
Server
Manage-
ment Studio
Express.
148 Part III: Adding and Accessing a SQL Server 2005 Express Database
By speaking with your users, you know that they’re searching for customers
based on the combination of LastName, FirstName. Given this fact, you can
create a composite index on these two columns. This composite index helps
future queries and other database activities that need to filter or sort on
these two columns.
When building a composite index, make sure that users are employing the
index from left to right. That is, if a given composite index is built on columns
A, B, and C (in that order), searches and sorts that successfully use this index
can include any of the following combinations:
⻬ Column A, B, C
⻬ Column A, B
⻬ Column A
150 Part III: Adding and Accessing a SQL Server 2005 Express Database
Creating indexes
Indexes have many benefits to offer, so you’re probably wondering how you
can create one of these wonderful creatures. Fear not — they’re very easy to
generate. In fact, SQL Server 2005 Express often creates them for you by
default. For example, when you define a primary key, SQL Server 2005
Express automatically generates a unique index for that column(s).
However, what if you want to build an index for another kind of column?
Here’s an example of putting an index on the FlavorName column from the
Flavors table:
The syntax is identical if you want to create a composite index; you just need
to add the additional column name:
SQL Server 2005 Express lets you define your indexes as unique or non-
unique, as well as clustered or non-clustered. By choosing unique, you’re
telling SQL Server 2005 Express not to permit any duplicates in the index
keys. For example, if you create an index on the LastName column, you can’t
insert or update any values if they would create two rows with the same data
in that column.
When you elect to define an index as clustered, you’re telling SQL Server 2005
Express that you want the table to be physically ordered by that index.
Continuing with the example of placing an index on LastName, if you
instructed SQL Server 2005 Express to make this index clustered, it lays the
table out on disk in LastName order. Naturally, you can only have one clus-
tered index per table.
If you decide to use clustered indexes, define them first before requesting
non-clustered indexes.
Changing Data
Putting information into a database is not like chiseling it in stone: You can
easily make changes any time you need. In this section, I show you how easy
changing your data is.
Chapter 9: Talking to a SQL Server 151
Just like the INSERT statement places data into a SQL Server 2005 Express
database and the SELECT statement retrieves information, the UPDATE state-
ment is responsible for adjusting this data.
For the sake of simplicity, I’m continuing with the ice cream example that I
lay out earlier in this chapter (in the “Storing Information in Your Database”
section). Suppose that you decide to improve your products by purchasing
higher-quality ingredients. Of course, you’re running a business, not a char-
ity, so you need to pass on some of these costs to your customers. You need
to record these higher costs in your database, so you write a simple UPDATE
statement to make the changes:
UPDATE Flavors
SET CostServing = CostServing * 1.10,
SinglePrice = SinglePrice * 1.05,
DoublePrice = DoublePrice * 1.05
Can you spot a potentially dangerous problem with this statement? It doesn’t
contain a filtering WHERE clause; all the rows in the table are updated.
In this case, given the terrible reception that the Walnut Wipeout and Grape
Gusher flavors have received in the market, perhaps you shouldn’t be raising
prices on those two flavors. You can easily change the query so that all the
rows except for those two problem children are updated:
UPDATE Flavors
SET CostServing = CostServing * 1.10,
SinglePrice = SinglePrice * 1.05,
DoublePrice = DoublePrice * 1.05
WHERE FlavorName NOT IN (‘Grape Gusher’,’Walnut Wipeout’)
This statement is a more selective UPDATE statement: The two poorly sell-
ing flavors still remain a bargain. Perhaps this pricing can improve sales of
those two.
152 Part III: Adding and Accessing a SQL Server 2005 Express Database
Naturally, you can write more complicated UPDATE statements. To do so, you
often use the same advanced search syntax that you use in your SELECT
statements.
Deleting Data
Nothing lasts forever, including data. The time likely arises when you need to
remove certain information from your SQL Server 2005 Express database.
Several useful statements are at your disposal for removing this unneeded
data.
To begin, the DELETE statement offers an easy way to get rid of redundant
rows in a particular table. In this case, suppose that you’re tired of seeing the
lackluster sales for the Grape Gusher and Walnut Wipeout flavors. The time
has come to remove them from your Flavors table:
Because you have sales transactions in your Sales table, perhaps a better
idea is to first remove the sales records, and then the flavor itself. Here’s how
you would do that:
If you have foreign key constraints in place, you must process DELETE state-
ments in this order (that is, children first, parents last). A little earlier in this
chapter, I placed a foreign key on the Sales table (refer to Table 9-2). The
reason for doing this is to prevent erroneous deletion of parent (that is,
Flavor) rows while child (that is, Sales) rows still exist. In fact, if you try
Chapter 9: Talking to a SQL Server 153
to delete the parent before the child — thereby violating the foreign key con-
straint — you receive a warning message like this one:
This statement removes all the rows from the Sales table, leaving the table
structure and all its constraints, indexes, and so on in place. However, it
doesn’t bypass any referential integrity constraints that you have specified.
For example, what happens if you try to remove all the rows from the
Flavors table?
After you truncate a table, you can continue using it: no application code has
to change (but the data is gone, of course).
If you’re sure that you won’t ever need the table or its data again, you can
simply use the DROP TABLE statement:
Unlike the TRUNCATE TABLE statement, DROP TABLE obliterates all con-
straints, indexes, and other table structures, so be very careful when you
use it.
154 Part III: Adding and Accessing a SQL Server 2005 Express Database
In most cases in which you need to remove a subset of the table’s data, just
appending a filter to your DELETE statement is all you must do to identify
and eliminate the right information.
For example, suppose that you’ve been selling ice cream like crazy, and you
want to delete a number of your older transactions. How can you isolate
and delete the right candidate rows without affecting newer data? One
option would be to write a program that looks at all the rows in the table,
and deletes only those that meet a certain criteria. However, this action
requires much more effort than is necessary.
In this case, how about using the TOP extension to Transact-SQL? You can
instruct SQL Server 2005 Express to remove a percentage of sales data that is
older than a given date:
DELETE TOP(10)
FROM sales
WHERE DateOfSale < ‘12/30/2006’
This operation tells SQL Server 2005 Express to remove ten rows from
the Sales table, as long as those rows are from a date earlier than
December 30, 2006.
Chapter 9: Talking to a SQL Server 155
Unfortunately, this statement has a problem: Eligible rows are removed at
random. As long as the rows are old enough, SQL Server 2005 Express deletes
them until ten rows are gone. After the dust settles, the ten oldest rows may
not have been deleted. You can easily see why: What if more than ten rows
with a DateOfSale are older than December 30, 2006?
To make matters worse, because the rows are removed at random, a good
chance some very old rows may survive, while some younger rows are
eradicated.
If you want to ensure a more orderly removal process, try this statement
instead:
This statement removes the oldest ten rows from the Sales table, as long as
the rows are older than the target date. You still may have rows that were cre-
ated before December 30, 2006, but the ten oldest rows are gone.
Can you see what’s happening here? You’ve told SQL Server 2005 Express that
you want to delete the top (that is, oldest) ten percent of those rows for trans-
actions that happened prior to December 30, 2006. If this operation still leaves
candidate rows, you can repeat the statement until all eligible rows are gone.
You see a shrinking number of rows until all the relevant rows are history:
I f you have an appetite for some more advanced interaction with your SQL
Server 2005 Express database, this chapter is for you. I begin by showing
you how to define your data structures to increase the reliability of your
information. You also find out how to speed up your database operations by
creating and using indexes. Finally, I tell you all about some cutting edge
capabilities for locating and organizing information in your database.
Constraints
When you build a database application, you’re responsible for making sure
that no bad data gets put into your database. If you fall down on the job, you
may make a bad decision, because what’s stored in your database doesn’t
accurately reflect reality. Constraints are a way for you to define, at the data-
base level, rules that help protect your database from data anomalies. Your
toolbox includes a number of constraints: primary and foreign keys and NOT
NULL, UNIQUE, and CHECK constraints.
158 Part III: Adding and Accessing a SQL Server 2005 Express Database
Primary key
By defining a primary key constraint, you’re telling SQL Server 2005 Express
that the values contained in one or more columns must be unique across all
rows. As well as protecting your data’s integrity, a primary key constraint is a
great help to database performance: Using the primary key, SQL Server 2005
Express can find a row almost instantaneously.
In fact, the database server thinks so highly of primary keys that it even takes
ownership of generating them for you automatically. All you need to do is
specify IDENTITY when creating your table:
Now, all you need to do to insert rows into this table is to provide a value for
the ManufacturerName column; SQL Server Express does the rest:
ManufacturerID ManufacturerName
-------------- ------------------------------
1 Aston Martin
2 BMW
The first row in this table has a ManufacturerID value of 1000; the second
row has 1250, and so on.
Chapter 10: Transact-SQL: Beyond the Basics 159
A Global Unique Identifier (GUID) is another choice for primary keys. These
are system-generated values that are built using truly unique information:
your network card’s internal serial number. In addition to their unique prop-
erties (which can come in handy in networked applications), GUIDs can hold
extremely large numbers. However, they can be confusing to people, and they
consume extra storage and CPU resources.
To use GUIDs, all you must do is have your primary key column use the
uniqueidentifier data type. With that task out of the way, your next step
is to set the column’s Is RowGuid property to Yes. After you do this, SQL
Server 2005 Express automatically generates lovely values like the following
for your primary key:
B3E1988C-38F2-411F-AC4C-BC3ED64D0ED3
EB7BA81A-DB19-4F9A-9011-37DACBABADF2
9011785F-B0C4-4306-99A5-7B637D71C4B5
These primary key values are for a 3-row table. As you can see, these values —
at least to the human eye — have no rhyme or reason. However, GUIDs are
great when you may need to merge values from the same table deployed in
multiple locations.
Foreign key
Most relational database applications spread their knowledge among multi-
ple tables. Each table ordinarily holds a specialized type of data. For example,
suppose that you’re building an application to track student grades. A common
way of maintaining this information is to store demographic details about the
students (name, address, and so on) in one table, and test-specific aspects of
their grades (class, date of test, score, and so on) in a second table.
Here’s where things can get tricky. If you’re not careful, your application
could delete a student’s demographic data without deleting the associated
test data. Alternatively, you could create a detailed test score record but omit
creating a student demographic record. You’ve damaged your data’s integrity
in both of these cases. Foreign key constraints are specifically designed to
prevent these unhappy situations from ever occurring.
When you place a foreign key constraint on two or more tables, you’re telling
SQL Server 2005 Express to intercept any attempts, deliberate or otherwise,
where your data’s integrity can be compromised.
NOT NULL
The NOT NULL constraint helps make sure that any database applications
provide data for one or more of your columns. If you attempt to enter an
160 Part III: Adding and Accessing a SQL Server 2005 Express Database
empty (that is, NULL) value on a column that has a NOT NULL constraint, SQL
Server 2005 Express intercepts the call:
UNIQUE
The UNIQUE constraint is very similar to a primary key constraint, but unlike
primary keys, UNIQUE constraints let you place a NULL value in the column.
However, you generally define a UNIQUE constraint when you already have a
primary key in place, but also want to enforce non-duplication on another
column. For example, look at this table’s syntax:
For this table, you’re using the EmployeeID column as the primary key, but
you also want to prevent duplicates in the SocialSecurity column. This is
a job for a UNIQUE constraint.
CHECK
Think of CHECK constraints as bits of application logic that you can place on
your tables to guarantee that they reject any attempts to violate a business
or other data rule that you want to enforce.
For example, imagine that you’ve extended the Employees table from the previ-
ous UNIQUE constraint example. You’ve now been asked to track the employee’s
work status. An employee can either be full or part-time; no other value is per-
mitted in that column. This scenario is ideal for a CHECK constraint:
Views
When you want to access or modify information that is spread among multiple
tables, you must first build your Transact-SQL statement so that it joins these
tables to produce a cohesive result set. This often isn’t so simple, especially if
any or all the following sets of circumstances are true for your organization:
Any of these situations can cause all kinds of problems as people attempt
to navigate the complexities of your SQL Server 2005 Express installation.
Fortunately, as a database designer or administrator, you have the power to
present a much simpler — and more secure — picture of this information to
these folks. To do this, you create what is known as a view.
In this next section, I describe some ways that you can use views to give your
users a better experience with information you’ve entrusted to SQL Server
2005 Express.
3. On the Databases entry, expand the database entry for the database
you’re interested in.
4. Expand the Views folder.
With the Views folder expanded, you now see a System Views subfolder.
If you’re curious about the dozens of built-in views available, just open
this folder.
If, on the other hand, you’re interested only in the database-specific
views that have been created by users and database administrators, you
see a list of them here as well. If you’re curious about what makes up a
particular view, go to the next step.
5. Expand the view you’re interested in examining.
Each user-defined view entry contains several columns of interest.
These include
• Columns: Expanding this folder gives you a list of all the columns
that make up the view.
• Triggers: A trigger is a set of activities that SQL Server 2005
Express performs when a certain event occurs. These events can
be INSERT, UPDATE, or DELETE. By using an INSTEAD OF trigger,
you can instruct SQL Server 2005 Express to take actions on the
base tables when any of these events happen. This folder offers a
list of any triggers driven by this view.
• Indexes: Here’s a list of all indexes that relate to this view. Note
that while you can create indexes on views in SQL Server 2005
Express, they won’t be of benefit to you unless you upgrade to the
Enterprise edition.
• Statistics: To help improve performance, SQL Server 2005 Express’
Query Optimizer keeps track of a number of important facts about
your data. Expanding this folder shows you what the optimizer
currently knows; you can also create new statistical profiles.
If you’re more of a Transact-SQL person, you can also get a list of views by
consulting the sys.views table:
sp_helptext MyViewName
This table holds some sensitive material, such as employee salaries, their
Social Security numbers, and their rankings. You might want to restrict
access to some of this intelligence, but people still need to view other parts
of the data. One option is to set permissions for various users, but this can
be cumbersome. In this case, a better choice is to create a view. You could
then instruct users to work with the view; they would never know that the
underlying table even existed.
Users can now interact with this view. Figure 10-1 shows query results for
both the base table as well as the view.
164 Part III: Adding and Accessing a SQL Server 2005 Express Database
Figure 10-1:
Comparing
query
results from
a view
versus a
table.
From the users’ perspective, this view walks and talks just like a regular
table. In fact, because it’s a single table-based view, you can even make data
alterations via the INSERT, UPDATE, or DELETE statements:
This statement actually creates a new row in the Employees table; the view
also shows this new row instantaneously.
Multiple table views are very helpful for retrieving information; however,
unlike a single table view, you can’t update a multiple table view.
Figure 10-2:
Creating a
view from
within SQL
Server
Management
Studio
Express.
Using XML
Since its introduction in the mid 1990s, the Extensible Markup Language
(XML) has become an incredibly popular way of representing, manipulating,
and transmitting information. It offers many advantages over older
approaches, including
Now that you know how to store XML information in your database, in the
next section, I show you how to derive value from these highly structured
documents.
If you want to know a lot more about using XML in conjunction with SQL
Server 2005 Express, check out Chapter 21.
168 Part III: Adding and Accessing a SQL Server 2005 Express Database
Indexing
When improving query and other data access performance, database design-
ers and administrators have to come up with a good indexing strategy. What
makes things a little complicated is that each application has its own, unique
performance needs that then translate to different indexing approaches.
In this section, you find out what must be indexed, and why. You also check
out some additional SQL Server Express indexing features that you might
want to use, depending on your application profile and performance needs.
All of the SQL Server 2005 database products offer a specialized type of struc-
ture known as a clustered index. When a clustered index is in place on a table,
that table is then physically stored in the order of the index. For example,
suppose that you have a table that contains a column that stores people’s
last names. If you create a clustered index on that column, SQL Server 2005
Express physically sorts the table by last name, and rearrange its internal
structures so that the table is in that order. Note that you can only have one
clustered index per table. If you don’t define any indexes as clustered, your
primary key serves as the clustered index.
Creating an index
Building an index is very easy. Just follow these straightforward steps:
9. Click the Columns property, and then click the ellipses to get a list of
candidate columns.
10. Choose as many columns as you like, and specify whether the index
will be ascending or descending for each column.
11. Set other properties for the index and then click Close when you’re
finished; save the modified table by choosing File➪Save.
These can include properties like its name, and whether you want SQL
Server 2005 Express to re-compute its internal statistics after creating
the index.
Figure 10-3 shows the rich user interface that Visual Studio offers for
constructing indexes.
Figure 10-3:
Creating an
index from
within SQL
Server
Management
Studio
Express.
Doing things graphically is fine, but what if you want to directly enter the SQL
to create this index? That’s easy enough — here it is for a scenario where you
want to use the SQLCMD utility to generate an index on the LastName
column in the Employees table:
Note: For simplicity, I’ve included the item and region’s name in this table. In
reality, if you subscribed to good relational database design theory, this
would likely be represented by a number that pointed to a table containing a
master list of all items, as well as a number that referred to a list of regions.
GROUP BY
You can use GROUP BY to help aggregate information, which is very benefi-
cial when you want to provide higher-level summarization of your data. For
example, suppose that you need to break out and total your sales figures by
region. It’s easy to do with GROUP BY:
SQL Server 2005 Express neatly sums up your information and returns the
results:
Central 234252.75
Japan 242278.92
East 227365.08
Latin America 235740.14
UK 306054.29
West 246750.58
China 248140.43
Germany 258725.60
Of course, you’re free to add other requirements to your query, such as filter-
ing, sorting, and so on:
172 Part III: Adding and Accessing a SQL Server 2005 Express Database
This query focuses on one item, and sorts the results in descending order of
the total amount sold.
ROLLUP
Including ROLLUP with your query instructs SQL Server 2005 Express to take
your query results and help create subtotals and totals. For example, sup-
pose that you want to run a search that summarizes sales by region and item.
Here’s how you would use ROLLUP:
SQL Server 2005 Express has considerately reported on how each item sold
within each region. Total sales for the region are tabulated at the bottom of
each region; their item name is NULL. The very last row reports on total sales
for all items for all regions.
CUBE
Adding CUBE to your query produces very similar results as ROLLUP. The
main exception is that CUBE also summarizes all combination of your
Chapter 10: Transact-SQL: Beyond the Basics 173
output columns. For example, look at the slight modification to the previous
query:
SQL Server 2005 Express would report on further combinations if you had
requested added columns as part of your query.
HAVING
In a nutshell, including HAVING with your aggregation query tells SQL Server
2005 Express to further filter your results. This is very powerful, and really
helps you isolate and focus on important data.
For example, suppose that you want to see only sales summaries from those
regions that sold more than $250,000. You could write an application that
walked through the data and then reported only relevant results. However, a
better idea would be to use HAVING:
By adding HAVING, you ask SQL Server 2005 Express to avoid reporting on
regions that didn’t hit the revenue target. Your result set is quite small, but
exactly what you wanted to see:
UK 306054.29
Germany 258725.60
TIMESTAMP
Keeping track of changes in your database can be tricky, especially when
you’re actively working with a row and want to make sure that nothing has
changed before you update the database with your own alterations. In cases
like this, try taking advantage of the TIMESTAMP data type to help you stay
on top of the exact state of your information.
174 Part III: Adding and Accessing a SQL Server 2005 Express Database
When you build a table that includes a TIMESTAMP column, SQL Server 2005
Express automatically inserts an internal identifier into the column anytime a
given row is inserted or updated. You can then use this value to see if some-
thing has changed. Here’s the exact set of steps to follow:
1. Create your table, making sure to include one (and only one) column
defined as TIMESTAMP:
CREATE TABLE Accounts
(
CustomerID INTEGER PRIMARY KEY NOT NULL,
CurrentBalance DECIMAL(10,2) NOT NULL,
TIMESTAMP
)
Notice that you don’t need to give the TIMESTAMP column a name. Also,
note that you can’t insert a value into this column directly, so you need
to specify your column names (and omit the timestamp) when adding
data to your table.
2. Use your table normally: Add, alter, and retrieve information with
standard Transact-SQL.
The timestamp value doesn’t change unless you change a row.
3. Check the timestamp value before you update a row.
A good way to do this step is to first retrieve the timestamp, make your
changes in your application, and then retrieve the timestamp one more
time (but put it into a different variable). If the two timestamps match,
the row has not changed from the time you first retrieved it. Otherwise,
someone has updated the row while you were working with it.
SELECT @@DBTS
0x00000000A9C20FA0
This returns a hexadecimal value, which changes every time someone alters
timestamped information in the database.
Don’t confuse TIMESTAMP with the DATETIME data type: The former refers to
the internal database identifier; the latter refers to a point in time.
Part IV
Keeping Your Data
Safe from Harm
In this part . . .
W hat’s a harried database owner to do? Sometimes
you’ll feel like everyone’s out to get you, or at least
your data. Uneducated users, apathetic developers, mali-
cious hackers, mutant viruses, and even cosmic rays all
seem to conspire to deliberately or carelessly damage or
even destroy your vital information. Luckily, you can do a
lot to protect yourself.
I n a perfect world, you wouldn’t need this chapter. You would also have no
need for police or locks on doors, but, alas, that is not reality. As it turns
out, you have good reason to be concerned about the safety of the informa-
tion entrusted to your SQL Server 2005 Express database. Fortunately,
Microsoft has done a very good job of creating a robust security infrastruc-
ture for the entire SQL Server database product family. However, the sheer
volume of security-related capabilities can be somewhat daunting.
This chapter is all about quickly helping you make the most of the security
features at your disposal. To begin, I list some questions that you can use to
help determine the degree of emphasis you need to place on security.
Because you likely require at least some security configuration, the next sec-
tion talks about the broad range of database objects that you can lock down.
Finally, with the overview complete, I show you how to perform some of the
most commonplace security tasks.
This chapter is not a comprehensive guide to all the possible SQL Server
2005 Express security permutations; that would fill its own book!
Things get worse in the second type of security exposure: unauthorized data
modifications. In this case, that rogue employee who was viewing salary data
has decided to give himself a raise, while rolling back the wages of all his co-
workers to 1970s levels. Of course, you may eventually figure out what has
happened to your information, but obviously a tremendous amount of
damage can happen before you can correct things. This example is actually
fairly mild; a security gap can lead to much more serious information injuries.
Chances are that at least one of the preceding questions applies to you. With
that in mind, you can get started setting up the right security plan for your
database.
To give you an idea of how many security options you have, take a look at the
following list, which is categorized by the SQL Server 2005 Express three
securable scopes, each containing its own securables:
Server:
Endpoint Login
Database
Database:
User Role
Application role Assembly
Message type Route
Service Remote service binding
Fulltext catalog Certificate
Asymmetric key Symmetric key
Contract
Schema:
Type XML Schema Collection
Object
The Object securable is of most interest for this chapter. It contains the fol-
lowing components:
Aggregate Statistic
Constraint Synonym
Function Table
Procedure View
Queue
If some of the items in these lists look a little unfamiliar to you, don’t worry:
The balance of the chapter focuses on securing the more recognizable
objects, such as tables and views.
180 Part IV: Keeping Your Data Safe from Harm
SQL Server 2005 Express also supports the concept of prepackaged permis-
sions. These are known as roles, but you can think of them as a one-stop shop
that lets you grant permissions en masse. Table 11-1 lists all the fixed server-
level roles along with their purposes. Table 11-2 does the same for fixed
database-level roles.
Understanding that all new database users are associated with the public data-
base role is important. If you don’t explicitly set permissions for a given secur-
able, these users automatically inherit the permissions that have been granted
to the public database role for the securable in question. Later in this chapter,
I show you how to define permissions, including for the public database role.
A great start is to simply figure out the types of users that you need to sup-
port. In this section, I list some of the typical SQL Server 2005 Express user
profiles that you’re likely to encounter, in increasing order of responsibility.
Note that your site may not have all these functions; you may also have the
same person handling multiple jobs, or you may be faced with additional roles
and responsibilities. Nevertheless, use this handy list as a starting point:
Implementing Security
After you read through the previous sections and get up to speed on all the
clever SQL Server 2005 Express security possibilities, you can put them to
the test. To begin, I show you how to figure out who can already access your
server and databases. When you know that, you then get the hang of granting
access to your database server and databases, followed by how you can set
specific permissions on particular objects.
Because the graphical SQL Server Management Studio Express (SSMSE) is the
most straightforward way of getting administrative tasks done, I focus on this
helpful tool. You could also use SQLCMD to manage security, but you have to
wield a combination of stored procedures and Transact-SQL.
That’s all there is to it. All the people or processes listed in the Logins folder
(see Figure 11-1) can log in to your system.
Figure 11-1:
Getting a list
of server
logins.
Of course, the next thing you need to know is who can actually work with
your databases, which is what I show you next.
Figure 11-2:
A consol-
idated list
of server
logins and
database
users.
Granting access
Authorizing people and applications to work with your SQL Server 2005
Express system is the most common security-related administrative task that
you’re likely to face. In this section, I show you the sequence of events you
need to follow to make that happen.
For this example, assume that a new employee named Hal has just joined
your organization. His job is to analyze sales and marketing trends, so he
needs direct access to a specific database named Marketing. Also assume
that your Windows system administrator has already created an appropriate
Windows login and profile for Hal.
Figure 11-3:
The Login –
New
General
Properties
page.
Chapter 11: Securing Your Data 187
8. Switch to the Server Roles page, and authorize any server roles that
you want this login to have.
I list the available server roles in the section “Who Can You Let Use Your
Database?” (earlier in the chapter); be careful about giving new logins
broad capabilities. In this example, because Hal is just a run-of-the-mill
user, he doesn’t need server-wide permissions.
9. Switch to the User Mapping page, and enable connectivity to all rele-
vant databases.
By enabling database connectivity here, SQL Server 2005 Express auto-
matically creates a user with this name in each database, which saves
you time later. In this case, simply checking the Map box next to the
Marketing database and picking a database role is all that’s necessary to
grant Hal connectivity to the database.
10. After you finish setting the properties for this login, click OK to
save it.
This login is now ready to connect to your database server. If you associ-
ated the login with one or more databases, and those databases have
public permissions set, this login can now work with those databases.
Figure 11-4:
The new
user
General
Properties
page.
Figure 11-5:
Searching
for objects
to authorize.
Chapter 11: Securing Your Data 189
After you pick one or more types of securables, SQL Server 2005 Express
returns a list of the available objects to secure, as shown in Figure 11-6.
Figure 11-6:
Authorizing
access for
a given
object.
10. After setting the right security profile for the new user, click OK to
save the record.
Your user is now ready to work with all authorized objects in this
database.
For example, suppose that you want to set permissions on a given table.
Here’s what you need to do to make this possible:
Figure 11-7:
Authorizing
access
for a given
object.
You may also elect to set user-specific permissions. In Figure 11-8, I’ve
checked the Deny box to specifically prevent Hal from creating any new
Chapter 11: Securing Your Data 191
records in this particular table. For Hal, this overrides the Insert permis-
sion that I granted to the public group.
Figure 11-8:
Denying
permission
for a
specific
user to
insert
records in
the table.
192 Part IV: Keeping Your Data Safe from Harm
Chapter 12
U nlike many other databases, SQL Server 2005 Express combines ease-of-
use and low cost (actually, it’s free) with very sophisticated database
engine features. Transactions are one of the most important capabilities
offered by any high-end database. In this chapter, you get a good idea of data
integrity, and why transactions are important in keeping your data nice and
clean. Because transactions are one of the main guardians of your data, you
also see how you can use them to keep everything running smoothly.
⻬ Parent and child differences: Imagine that your database includes data
stored in parent (header) and child (detail) tables. Furthermore, suppose
that you keep a running total of information in the parent table about
records in the child table. A good example is customer details (name,
address, financial summary) in the parent table, and customer transac-
tions (transaction date, amount, and so on) in the child table. If you’re
not careful, these two tables can get out of sync, which might lead to
someone looking at data in the parent table to make an incorrect
assumption.
⻬ Orphans: Continuing with the preceding example, what happens if you
intentionally delete a parent record but somehow overlook deleting its
related children? You’re left with the sad prospect of orphaned child
records forever doomed to a lonely existence in your database.
⻬ Partial updates: A partial update can happen when all the tables that
are supposed to be updated at one time don’t actually successfully com-
plete their modifications. The classic example of this problem is a failure
when transferring money between savings and checking tables. If the
application only reduces the savings balance but does not increase
the checking balance, the customer is quite unhappy, and the data’s
integrity (and possibly the bank manager’s office) is damaged.
⻬ Business rule violations: Although rules are generally meant to be broken
from time to time, this is not true with information carefully entrusted to
your SQL Server Express database. For example, you might be building an
application to track credit ratings for your customers. Valid values for the
credit score range between 0 and 100. If a rogue person or program places
a value of –291 or 1,259 in this column, your data’s integrity is no longer
intact.
⻬ Log cache: SQL Server 2005 Express uses this memory-based structure
as a temporary storage buffer for details about a transaction. Because
it’s based in memory, and separate from the standard buffer cache used
for data, it’s very fast and efficient.
⻬ Transaction log: This file, or group of files, is a journal that contains
information about your transactions. It works in conjunction with the
log cache. If you need to roll back your transaction, or restore from a
backup, this journal is vital to setting things right with your database. It
also serves as a source of guidance for database replication and standby
servers. Administrators typically back up their transaction logs as part
of normal maintenance.
⻬ Locks: Because SQL Server 2005 Express supports multiple concurrent
users and processes, a series of locking mechanisms must coordinate
access to information. A lock’s scope can be very granular — such as at
the data page level — or very wide — such as at the table or even data-
base level.
⻬ Checkpoints: As you might guess from its name, a checkpoint is an intri-
cate, internal SQL Server 2005 Express event that serves to synchronize
all the other internal transaction structures so that everything is
consistent.
Isolation Levels
Each SQL Server 2005 Express transaction has an isolation level. This term
describes how the transaction interacts with other database users and
processes.
To make transaction isolation levels work, SQL Server 2005 Express employs
a variety of locks on data and indexes, as well as other internal controls.
Locks may be at the row, page, or table level, and they may be exclusive
(completely restricting access to data) or shared (which allows other
transactions to access information).
Chapter 12: Keeping It Together: Using Transactions to Maintain Data Integrity 197
SQL Server 2005 Express offers a series of increasingly stringent isolation
levels:
Be careful when using the more restrictive isolation levels. Although they do
a great job of preserving data integrity, the cost can be significantly reduced
system speed and throughput.
Using Transactions
In the previous sections of this chapter, I tell you all about transactions. So
now you’re probably wondering how you can put these powerful features to
work. Fortunately, despite their rich capabilities, transactions are quite
simple to use. In a nutshell, just follow these steps:
BEGIN TRANSACTION;
The @@ERROR function tells you if anything has gone wrong with your trans-
action, which gives you the chance to roll it back in time. To find out more
about handling errors, take a look at Chapter 17.
200 Part IV: Keeping Your Data Safe from Harm
Chapter 13
W aking up one morning to find some or all your precious data lost for-
ever ranks with some of life’s great moments — like root canals, tax
audits, or endless flight delays. However, in this chapter, I show you that
unlike death and taxes, you can avoid losing data.
To begin, I show you why using transactions can be one of the smartest
things a software developer can do. Next, I expound on ways to keep your
database server’s memory consistent with the permanent information stored
on disk. Finally, you see how to use the sophisticated backup and recovery
features built into SQL Server 2005 Express to help safeguard your data.
For example, suppose that you write a program that updates rows in tables
A, B, and C as part of the same unit of work. Furthermore, imagine that tables
A and C happily accept your changes, but something is wrong with the modi-
fication that you want to apply to table B’s data. If you’re not careful, you
could easily end up in a state where tables A and C think everything was fine,
and table B does not. This translates into a corrupted and out-of-sync database.
Months may go by before anyone notices, but rest assured: Your data has been
damaged.
202 Part IV: Keeping Your Data Safe from Harm
This situation is where transactions come in. By grouping all your data updates
into one batch, you can definitively tell SQL Server 2005 Express to either
keep or reject all your changes. In the preceding example, you could have put
tables A, B, and C back to their original states if even one of them had a prob-
lem with your change. Your data remains in sync, and is safely preserved.
But wait a minute. What if something went wrong during all these operations?
Fear not, because transactions let you change your mind. For example, sup-
pose that you start a transaction, issue a bunch of statements, and then
change your mind and want to go back to the way things were before?
Luckily, you have the ROLLBACK TRANSACTION statement waiting in the
wings. If you issue this statement instead of COMMIT TRANSACTION, SQL
Server can rollback all your modifications, putting the database back into the
state that it was just prior to the BEGIN TRANSACTION statement.
When you start a transaction, the database server records this event in a
memory structure known as the log cache. In addition, all your changes are
also written into the log cache. This cache is then periodically written to the
log cache’s disk-based counterpart, which is known as the transaction log.
If the server were to crash in the middle of a transaction, SQL Server 2005
Express would use the transaction log as a guide to determine which transac-
tions to rollback. On the other hand, if you simply change your mind, SQL
Server 2005 Express can use the transaction log as a guide to reinstating your
data to the way it was prior to the start of the transaction. If this rollback
Chapter 13: Preventing Data Loss 203
wasn’t helpful enough, the transaction log is also useful when you need to
restore from a backup. In any case, when the transaction completes, SQL Server
2005 Express also records this event in the log cache and transaction log.
However, eventually all this fun has to come to an end, even if temporarily.
Sooner or later, SQL Server 2005 Express must write the contents of its
memory to disk, as part of an event known as a checkpoint. Otherwise, what
would happen if the computer suddenly lost power? All your changes would
be lost forever, vanishing into the ether before SQL Server 2005 Express
could get the chance to commit them onto disk. Try explaining that to a user
looking for last month’s sales figures.
As you work with database information, SQL Server 2005 Express accumu-
lates data on pages within a section of server memory known as the buffer
cache. When you create, modify, or remove data, SQL Server 2005 Express
records these alterations in the buffer cache on what are known as dirty
pages. These pages are then synchronized to disk during a checkpoint.
Now that you know how checkpoints work, what do you have to do to make
sure that your own checkpoints get run correctly? The good news here is that
SQL Server 2005 Express handles all these chores automatically: You don’t
have to do anything.
204 Part IV: Keeping Your Data Safe from Harm
However, you may want to tinker with the amount of resources that SQL
Server 2005 Express dedicates to your checkpoint process. You can influence
its behavior by running the CHECKPOINT command, passing in a value that
states the maximum amount of time, expressed in seconds, that you want
your checkpoints to take.
Normally, SQL Server 2005 Express uses its own internal algorithms to opti-
mize how long a checkpoint takes. If you run this command with a low value
(less than 60 seconds), the database server shuffles its resources to dedicate
more to the job of getting your checkpoint done quickly. Conversely, a high
value lets SQL Server 2005 Express make its own decisions about how to allo-
cate resources to get checkpoints done as quickly as possible.
Unless you’re really worried about squeezing the last bit of performance out
of your SQL Server 2005 Express system, don’t mess around with this setting.
The database usually knows best!
On the other hand, if you have relatively static data or have deployed alterna-
tive redundancy measures, you may not need a very strict data archiving
regimen.
Recovery models
The full SQL Server 2005 product line offers three distinct classes of backup
and recovery. Known as recovery models, these include
⻬ The full recovery model: This recovery model is the most robust
offered in the SQL Server product family. It provides maximal protection
from just about any kind of data disaster you can think of, and lets you
restore your information to a particular point in time.
However, this power and protection comes with more work and respon-
sibilities for the database administrator. To begin, the transaction log
has to be backed up on a regular basis, or data alterations can get lost.
If your transaction log fills up, you won’t be able to make any changes
until the log file is backed up.
If you’re running a very dynamic database server, and want to have
point-in-time recovery capabilities, you may need to use this model. You
need to upgrade to the Enterprise edition of SQL Server.
⻬ The bulk-logged recovery model: Using the full recovery model adds
some performance overhead to your database server. This overhead can
get very expensive when you perform bulk operations, such as loading a
large data file into your database. One way to reduce these extra costs is
to temporarily switch to the bulk-logged recovery model until the bulk
operation finishes. The bulk recovery model saves on overhead costs by
206 Part IV: Keeping Your Data Safe from Harm
If all this info has your head spinning — not to worry: SQL Server lets you
switch recovery models anytime you like.
To change your recovery model, simply use the ALTER DATABASE command.
Here’s an example of setting a database’s recovery model to simple recovery:
⻬ Use redundant hardware. Hardware prices keep falling. It’s now possi-
ble to purchase and configure inexpensive, redundant components. For
example, you can set up a Redundant Array of Inexpensive Disks (RAID)
storage system for much less than you might think. These extra disks
can greatly reduce the likelihood of a serious data loss should one of
your disks encounter a problem.
⻬ Maintain a standby server. Speaking of redundant hardware that can
come to your rescue during difficult times, a standby server can be a
great investment, especially if you keep it up to date by regularly restor-
ing backups or replicating information onto it. Then, if something cata-
strophic happens to your production server, you can always switch over
to the backup server.
Chapter 13: Preventing Data Loss 207
⻬ Restore backups regularly. You can devise the most brilliant backup
strategy of all time, but if you can’t restore a given backup, all your
investment has been for naught. This is why you need to test your
backup validity on a consistent basis. You can also combine two good
ideas (restoring regular backups onto your standby server) to help
ensure that you can gracefully recover from a database problem.
For the balance of this chapter, I focus on full and full differential backups
because these make the most sense for the largest number of SQL Server
2005 Express installations. Although these backup types take longer and con-
sume more media, they’re also more straightforward to envision.
Figure 13-1:
General
backup
settings.
Figure 13-2:
Backup
option
settings.
On the Options page, you choose how you want your media managed,
what should be done with the transaction log (if you chose the
full recovery model), as well as if you want extra reliability checks
performed.
Opting for backup verification and a media checksum operation adds
a little extra time to your backup. However, these checks can identify a
problem before you reach a crisis, and are generally worth the extra
effort.
5. Watch for any error messages.
If everything went well, you should receive a message telling you that
the backup completed successfully.
210 Part IV: Keeping Your Data Safe from Harm
By creating a text-based backup version of your data, you give yourself one
more chance to recover from a catastrophic problem. Of course, you must
take the same precautions with your text-based backup data as you do with
your traditional data backups.
Restoring your database back to its original pristine state is pretty straight-
forward if you’ve done your backups correctly. Just follow these steps:
1. Launch the backup utility you used to create the original data archive.
Throughout this chapter, I cite the built-in SQL Server 2005 Express util-
ity, which you can access from within any SQL-ready tool. I continue to
refer to this tool in this section, as well as assume that you’re using SQL
Server Management Studio Express.
2. Connect to the right instance of your database server.
3. Expand the Databases folder, right-click the database you want to
restore, and choose Restore from the Tasks menu.
Figure 13-3 shows the restore settings at your disposal.
Chapter 13: Preventing Data Loss 211
Figure 13-3:
General
restore
settings.
You can choose the database where you want the restore to be written,
as well as whether you want to restore to a point in time. You may only
restore to a point in time if you’ve chosen the full or bulk-logged recov-
ery models.
You can also select whether you want the restore utility to locate the
candidate backup set, using the database’s internal record, or to use a
backup set found on a device.
4. Fill in the required information on both the General page (shown in
Figure 13-3) and the Options page (shown in Figure 13-4), and click OK
to launch the restore.
Figure 13-4:
Restore
option
settings.
212 Part IV: Keeping Your Data Safe from Harm
The options page offers settings that help control the behavior of the
restore operation, as well as the state of the database after the restore
has been completed.
For the simple recovery model, choose the Restore With Recovery
option in the Recovery state portion of the options page.
5. Watch for any error messages.
If everything went well, you should receive a message telling you that
the restore completed successfully.
That’s it. You’re now ready to connect to your database and run some basic
tests to see if everything restored correctly. After you’re satisfied that things
are in good shape, you can let users connect to the newly restored database
to resume their work.
Part V
Putting the Tools to
Work: Programming
with SQL Server
2005 Express
In this part . . .
Y ou’ll primarily use SQL Server 2005 Express as a data
repository in conjunction with packaged, pre-built
tools and applications. However, you may use it as the
foundation of a new application. If you’re building a new
solution that relies on SQL Server 2005 Express, this part
is for you.
After you encrypt a stored procedure or function, you can’t have SQL Server
2005 Express print out the original source code. For this reason, always store
an unencrypted copy someplace safe for future reference.
This example is very simple; SQL Server 2005 Express lets you build much
more powerful stored procedures that run rich sets of business algorithms.
Now, here’s an example of a function that performs the highly complex task
of converting meters to inches:
Generally, you include a function call directly within your SQL as part of a
larger statement:
On the other hand, most applications that use stored procedures look to
these objects to help outsource longer-lived, more involved processing,
thereby passing control to them until the procedures finish their work. Of
course, these rules have exceptions, but in most cases this is how things
shake out.
Microsoft prefixes system stored procedures with either an sp_ or xp_. Try
not to use these prefixes when building your own procedures.
While this book doesn’t have enough room to go through each of these built-
in stored procedures and functions, in this section I show you how you can
get a list of what’s installed on your server, as well as go through some exam-
ples of some particularly appealing components.
220 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
Figure 14-1 shows an example of a stored procedure hierarchy, all the way
down to an individual procedure’s parameters.
This listing is chock-full of important information that you can use to figure
out how to work with the stored procedure. These details include
Figure 14-1:
A detailed
view of the
sp_Active
Directory_
Obj stored
procedure.
Some of the current built-in stored procedures and functions (but none of the
ones I name in the following list) are destined for that great CPU in the sky, so
before relying on a particular procedure, consider consulting the documenta-
tion to check on its life expectancy.
To make things clearer, I divide this list of sample built-in stored procedures
into three main categories, based on the primary role that the procedure
plays. Note that there are many other ways to pigeonhole these objects:
222 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
Figure 14-2:
Output from
the sp_
helpdb
and sp_
depends
system
stored
procedures.
Chapter 14: Using Stored Procedures and Functions 223
Figure 14-3:
Output
from the
sp_data
type_info
and sp_
columns
system
stored
procedures.
If you forget to include a parameter, don’t worry: SQL Server 2005 Express is
on the job. For example, if you don’t tell sp_defaultdb what database you
want it to use, it complains:
Using Transact-SQL
As it turns out, in most cases Transact-SQL can meet your processing needs.
If you’re unsure about whether to use Transact-SQL or SQLCLR, see the next
section for more about when SQLCLR is the right choice.
224 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
After you’re ready to write your stored procedure or function, you can use
any of the following tools offered by Microsoft:
In fact, because you can write stored procedures and functions in Transact-
SQL, you can use any third-party tool that gives you direct SQL capabilities.
Assuming that you’re using SQL Server Management Studio Express, here’s
all you need to do to create your logic, using stored procedures as a model:
Figure 14-4:
New stored
procedure
template.
If everything goes according to plan, SQL Server 2005 Express reports that
your command executed successfully. You can then see your stored proce-
dure or function by following the steps in the “Getting a list of stored proce-
dures and functions” section, earlier in this chapter.
If any of these features seem particularly appealing, check out Chapter 16 for
a detailed exposé on how to take advantage of SQLCLR to build stored proce-
dures or functions.
In this example, you need to declare a variable to hold the results from the
stored procedure; the PRINT statement simply displays what came back.
Inches
------------
4860.473
Chapter 15
Understanding Triggers
In This Chapter
䊳 Understanding what triggers do
䊳 Reviewing the two types of SQL Server 2005 Express triggers
䊳 Deciding when to use triggers, and when not to
䊳 Creating, invoking, changing, and dropping triggers
T riggers are a great tool for centralizing and consolidating processing rules
for your database, helping to improve your applications’ accuracy and
consistency. If that isn’t enough of an incentive to find out what this feature
does, triggers may also help boost application performance. In fact, triggers
are so valuable that Microsoft offers two types: Data Definition Language (DDL)
triggers, which handle changes to your data structure, and Data Manipulation
Language (DML) triggers, which handle changes to your actual information.
This chapter introduces you to triggers. You begin by figuring out what they
are, what they do, and how they work. After you pass that easy hurdle, your
next step is to check out the differences between DML and DDL triggers.
As with any powerful feature, you need to understand when to use a trigger,
as well as when it’s not the right choice for the task at hand. For this reason,
this chapter reviews several scenarios to help guide you toward the right
decision.
Finally, after examining all these topics, you can easily create your own set of
triggers.
without any delays. Different post office triggers would be invoked if you pro-
vided enough postage but forgot to write your friend’s address, wrote the
address in Bulgarian, or tried to mail your cat.
From the post office’s perspective, these triggers (or business rules) are vital.
Without them, each letter carrier would make his or her own decisions about
what constitutes a valid letter. Some overly zealous letter carriers would
reject valid mail, while other, more easygoing civil servants would let invalid
shipments gum up the works. By centralizing these rules, the post office
enforces consistency, which makes the mail more predictable and easier to
use for the customer.
Trigger scope
You can define a trigger to be processed for a particular table or even a view
that is made up of many tables. As I show you a little later in this chapter (in
the “Writing new triggers” section), you can set up triggers to be invoked for
a wide variety of statements that affect these tables or views. In fact, you can
set up multiple triggers for the same object. After you decide on the type of
statement that you want to invoke a trigger, you can nest your triggers: They
can call other triggers or stored procedures as well.
For each trigger that you create, SQL Server 2005 Express also writes detail
entries in the sys.sql_modules and sys.trigger_events tables. These
tables hold additional information about the trigger:
When the trigger is in place, the SQL Server 2005 Express engine consults
these tables to find any relevant triggers for a given table or view. If it finds an
appropriate candidate, it runs the trigger.
Types of Triggers
SQL Server 2005 Express divides its triggers into two categories: triggers that
affect data definition tasks, and triggers that affect data manipulation tasks. I
cover each category in this section.
⻬ CREATE
⻬ ALTER
⻬ GRANT
230 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
⻬ DENY
⻬ REVOKE
⻬ UPDATE STATISTICS
⻬ DROP
⻬ INSERT
⻬ UPDATE
⻬ DELETE
DML triggers are incredibly useful for centralizing all kinds of important
application processing. While you may never need or want to use a DDL trig-
ger, you have a good chance of benefiting from a DML trigger. I show you a
bunch of examples in the next section of this chapter.
⻬ Enforcing business rules: Suppose that you want to make sure that only
your best customers get the VIP discount. You can rely on your program-
mers to make that determination, but a better, more consistent way is to
use a trigger.
⻬ Protecting data integrity: While SQL Server 2005 Express includes a host of
referential integrity tools, you may at times need very specialized process-
ing to protect and preserve data integrity. A trigger can be just the ticket to
solve this kind of problem. In fact, this trigger is the most common.
⻬ Launching additional actions: Because you can write very powerful and
flexible triggers, using Transact-SQL and other languages, you can have
these triggers launch follow-on actions. For example, suppose that you
want to be notified if a particular part in your warehouse reaches a criti-
cally low inventory level. In this case, you can place a trigger on the
part’s table, and when the inventory fell below a set threshold, have it
generate an e-mail alert. You can even automate the reordering process,
all driven by triggers.
Using Triggers
In the previous sections of this chapter, I show you what triggers are, how
they operate, and when to use them. In this section, I welcome you to take
the plunge and make triggers work for you.
sp_helptext trig_check_inventory
It returns the exact statements that make up the trigger, including any
embedded comments:
Feel free to come up with your own queries against the SQL Server 2005
Express system catalogs — a tremendous amount of valuable information is
stored there.
Figure 15-1:
Creating a
new trigger,
using SQL
Server Man-
agement
Studio
Express.
Now that you have this information, you can take action if necessary:
-- If there isn’t enough inventory, then order some
more
IF (@quantity_on_hand + @part_request_count >
@minimum_number)
INSERT INTO reorder VALUES (@part_number,
@minimum_number)
Here’s an example of a DDL trigger that’s designed to block people from cre-
ating new indexes without first checking with you:
Now, if users try to sneak a new index into the database, your new trigger
stops them cold in their tracks:
You can use DDL triggers to safeguard your entire SQL Server 2005 Express
installation.
Chapter 15: Understanding Triggers 237
Invoking triggers
Because the SQL Server 2005 Express database engine monitors and runs
triggers, you do very little to make this process happen. In fact, all that needs
to happen in most cases is for the triggering event to take place. For example,
if you put an insert trigger on a particular table, SQL Server 2005 Express
patiently waits until an insert happens on that table. After that insert hap-
pens, Express invokes the trigger and faithfully executes your instructions.
As I show you in the next section, you can disable a trigger. If you’re con-
cerned that a trigger isn’t executing properly, you can easily check whether
the trigger is in fact active. For example, here’s how to tell if the
trig_check_inventory trigger is disabled:
Disabling triggers
Sometimes, even the best of triggers can get in the way of what you’re trying
to accomplish. For example, suppose that you have a collection of rather
complex triggers for a particular table. You wrote these triggers to perform a
variety of data integrity and validation checks to protect your database from
incorrect information. This strategy is a good one: Your database has very
accurate data.
However, suppose that one day you’re given a text file containing several mil-
lion rows of already-cleaned data that need to be inserted into this table.
These hard-working triggers will likely get in the way and cause the data load
to take a very long time.
If you’re using the bcp utility or the BULK INSERT command, SQL Server
2005 Express automatically disables triggers, which helps speed up these
operations. However, for this example, assume that you’re not using either of
these options.
In this case, you don’t want to drop and re-create the triggers, but you want
this one-time job to finish as quickly as possible. Luckily, you can use the
DISABLE TRIGGER statement to tell SQL Server 2005 Express to set one or
more triggers aside:
In this case, you tell SQL Server 2005 Express to disable two triggers for this
table. If you want to disable all triggers for a table, you can do even less typing:
But why stop there? A simple change disables the DDL triggers for the whole
database:
Finally, if you have sufficient permission you can disable all the DDL triggers
for the entire server:
Here’s how to put your triggers back to work for a specific table:
Modifying triggers
Mistakes happen to the best of us, so someday you’ll probably need to
change one of your existing triggers. If you need to make a modification to
the trigger’s logic, you can use the ALTER TRIGGER statement.
Unfortunately, altering a trigger often means that you must re-type the code
for the entire trigger. But what if you forgot the code? Luckily, you can
retrieve it by simply running the sp_helptext stored procedure:
sp_helptext trig_validate_address
On the other hand, if you want to rename the trigger, use the combination of
DROP TRIGGER and CREATE TRIGGER statements.
Chapter 15: Understanding Triggers 239
Deleting triggers
One day, you and one or more of your triggers might have a falling out.
Maybe it’s just not working for you anymore, or one of you has grown and
changed. In any case, if you can’t patch things up with the trigger, you can
pull the plug. SQL Server 2005 Express makes these awkward moments less
difficult. The DROP TRIGGER statement instantly obliterates the trigger.
For a DML trigger, the DROP TRIGGER statement looks like this:
To prevent global mistakes, SQL Server 2005 Express requires that you list
each DML trigger that you want to delete. Getting rid of a DDL trigger for just
one database looks like this:
You can easily expand the DROP TRIGGER statement to remove a DDL trigger
for all databases on your server:
Another way to get rid of a DML trigger is to drop the entire table, but unless
you truly don’t care about the table, using the DROP TRIGGER statement
instead is a better idea.
240 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
Chapter 16
You can use any of the following programming languages as part of the
SQLCLR environment:
Because the .NET framework handles so many of the tasks that were previ-
ously the responsibility of an individual developer, many applications have
been built on top of this infrastructure. Known as Managed Code, and
whether by design or not, these solutions leverage the following .NET frame-
work services in the process:
⻬ Garbage collection: Before you get your hopes up, no, CLR doesn’t take
the trash out for you or straighten up around your desk (although these
tasks likely will be available by 2010). In this case, garbage collection
refers to how CLR cleans up memory that is no longer needed. It helps
make the most of an always-scarce resource; without it, your applica-
tions would consume more memory, and do so less efficiently.
⻬ Threading: Threads are one way that modern computers and operating
systems stretch performance. They are different strands of logic that
your CPU juggles in near-real time. Threading boosts system throughput
in a way that is completely transparent to your application. CLR
employs sophisticated threading logic to increase your solution’s
responsiveness.
⻬ Security: The power and flexibility of CLR-based applications can be a
double-edged sword: It’s easy to imagine a shady character trying to
sneak some nefarious code into your database. However, the CLR has a
number of built-in security restrictions designed to protect your data-
base from unauthorized logic.
⻬ Assemblies: After compiling your .NET-based application, Microsoft gen-
erates a composite object known as an assembly. In addition to your
application code, these structures contain all sorts of information that
the CLR uses when running this program. By using this intermediate
arrangement, your application can easily interact with other programs
that were built the same way.
Chapter 16: Using the SQL Common Language Runtime (SQLCLR) 243
Why use SQLCLR?
Transact-SQL is fine for many database-oriented tasks, but it has some signifi-
cant shortcomings as a tool for more complex software development jobs.
One of the reasons that SQLCLR exists is to help address these deficiencies.
Here are some of its key advantages when building robust solutions:
⻬ Stored procedures
⻬ Functions
⻬ Aggregates
244 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
⻬ User-defined types
⻬ Triggers
If you’re curious about what these objects do, check out Chapter 14 for
details about the value of stored procedures and functions, and Chapter 15
for how triggers can add value to your applications.
The preceding steps lay out the basic workflow for embedding SQLCLR logic;
with that in mind, check out the two different examples of how to embed
SQLCLR-based logic in your SQL Server 2005 Express database. Before begin-
ning, here are a few assumptions and ground rules about these examples:
Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Figure 16-1 shows how Visual Studio appears for this project. Notice how the
database and project are closely integrated within the development user
interface.
Chapter 16: Using the SQL Common Language Runtime (SQLCLR) 247
Figure 16-1:
Building a
SQLCLR
application
in the Visual
Studio
develop-
ment
environment.
Just a few lines of Visual Basic code complete the stored procedure. Here’s
what the finished product looks like:
Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
End Sub
End Class
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
Here’s what the RiskProfile() function looks like after adding the risk vali-
dation logic:
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString RiskProfile(int numTickets,
int numAccidents, int numLatePayments)
{
// Driver starts out with no faults
int Faults = 0;
if (numTickets > 3)
Faults++;
if (numAccidents > 1)
Faults++;
if (numLatePayments > 3)
Faults++;
switch (Faults)
{
case 0:
Rating = “Positive”;
break;
case 1:
Rating = “Neutral”;
break;
case 2:
Rating = “Negative”;
break;
250 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
case 3:
Rating = “Catastrophe”;
break; default:
Rating = “Neutral”;
break;
}
return Rating;
}
You can now invoke this function from within Transact-SQL, of course making
sure to replace the database name and owner with the proper values for
your site:
W e all strive for perfection. Alas, errors, anomalies, and other unantici-
pated surprises are a fact of life. Nowhere is this fact more apparent
than in computer-driven applications, and solutions built on top of SQL
Server 2005 Express are no exception to this rule.
In this chapter, I show you why planning for, and handling, errors is so impor-
tant. You see how to take advantage of the significant amount of error han-
dling infrastructure offered by SQL Server 2005 Express, as well as the
various application development technologies that work with this database
server. Finally, I point out a number of common error scenarios, along with
techniques that you can use to deal with them.
⻬ Error message: Here’s where you can find the exact wording of the error
message.
⻬ Error number: Each SQL Server 2005 Express error is associated with a
predefined number; this property gives you that number.
⻬ Error procedure: If your error happened in the middle of a stored pro-
cedure or trigger, here is where you can learn the name of the culprit. On
the other hand, if it happened outside the context of either of these
objects, this property is set to NULL.
Chapter 17: Sorry, I’ll Try That Again: Adding Error Handling to Your Code 253
⻬ Error line: This property reports on where SQL Server 2005 Express
found the error in your program or script.
⻬ Error severity: Errors can range in severity, from 0 to 24. All these
errors are not created equal. Some are cause for great concern, while
you can practically laugh off others. Table 17-1 shows a summary of
each major error severity group.
⻬ Error state: Depending on where the error occurred, the same error
number can have different error state values. So a given error number
may indicate different problems.
⻬ ERROR_NUMBER()
⻬ ERROR_MESSAGE()
⻬ ERROR_LINE()
⻬ ERROR_PROCEDURE()
If the error happened outside the context of a stored procedure or trig-
ger, calling this function returns a NULL.
⻬ ERROR_SEVERITY()
⻬ ERROR_STATE()
TRY...CATCH
Unplanned-for problems often caused a total failure of the program in earlier
generations of software applications. These errors frequently made the pro-
gram so unstable that it was unable to continue, an event I’m sure you’ve
seen. In an effort to help stabilize what are increasingly complex programs,
many modern programming languages contain exception handlers that can
catch and handle problems.
⻬ Report the error to the user or invoking application; ask them to correct
the mistake if possible.
⻬ Attempt to programmatically correct the error; the user may not even
know there was a problem.
⻬ Invoke a standardized error handler to manage the problem.
⻬ Rollback any open transactions.
You can nest TRY...CATCH blocks, but note that errors with a severity level
of less than 10 (that is, minor errors, simple informational, and other advi-
sory messages) won’t trigger the CATCH block. Refer to Table 18-1 for a listing
of error severity groups.
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO products VALUES
(‘one oh one’,’Paisley leisure suit’,
‘Everything old is new again! Be the talk of
your town with this cutting edge leisure suit’
);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF (XACT_STATE()) = -1
BEGIN
PRINT N’The transaction contains errors, so
it is being rolled back.’;
ROLLBACK TRANSACTION;
END;
END CATCH;
@@ERROR
Unlike the TRY...CATCH block, which requires a more structured approach
to your Transact-SQL application code, you can simply consult the @@ERROR
operation to check the error number for the most recent statement.
Successful invocations return 0 (a zero); errors return a non-zero value.
Because every SQL statement resets this value, make sure to check it immedi-
ately after an operation. Otherwise, you may not have a true picture of any
error conditions.
After you save the value contained in @@ERROR, you can take action depend-
ing on what you’ve learned. Your Transact-SQL logic, however, is probably
more effective using the TRY...CATCH block rather than the more informal
@@ERROR construct.
Error Examples
By now you’re probably wondering what some real-world errors look like.
Never fear: I’m about to show you a wide variety of what you may encounter
as you build and maintain your SQL Server 2005 Express-based application.
For these examples, I work with two tables from a product rating application,
as defined here:
Syntax error
Sometimes even the simplest problem can drive you nuts. Mistyping SQL
syntax ranks with some of the most common, yet hard-to-debug obstacles.
Unfortunately, unless you embed the TRY...CATCH block within a stored
procedure, even a simple syntax error isn’t caught. For example, look at this
block of code, its simple typo, and its output:
BEGIN TRY
SLEECT * FROM Products;
END TRY
BEGIN CATCH
SELECT
ERROR_LINE() as ‘Error Location’,
ERROR_NUMBER() as ‘SQL Server Error Number’,
ERROR_MESSAGE() as ‘Error Description’
END CATCH
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ‘SLEECT’.
Why didn’t the CATCH block intercept this message and give a formatted
error result? Syntax errors and recompilation mistakes aren’t caught, unless
they happen to be embedded in a stored procedure or other lower-level
TRY...CATCH block.
BEGIN TRY
SELECT rating_id, rating_code FROM ratings;
END TRY
BEGIN CATCH
SELECT
ERROR_LINE() as ‘Error Location’,
ERROR_NUMBER() as ‘SQL Server Error Number’,
ERROR_MESSAGE() as ‘Error Description’
END CATCH
BEGIN TRY
INSERT INTO products VALUES (‘Oh no’,’Widget 6’,
‘High quality widget - available in lime green’);
END TRY
BEGIN CATCH
SELECT
ERROR_LINE() as ‘Error Location’,
ERROR_NUMBER() as ‘SQL Server Error Number’,
ERROR_MESSAGE() as ‘Error Description’
END CATCH
BEGIN TRY
INSERT INTO ratings VALUES (1822,’12/30/2006’,
100, 15,’Product met my needs’);
END TRY
BEGIN CATCH
SELECT
ERROR_LINE() as ‘Error Location’,
ERROR_NUMBER() as ‘SQL Server Error Number’,
ERROR_MESSAGE() as ‘Error Description’
END CATCH
260 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
In this case, the TRY...CATCH block works as advertised, catching the error
message and displaying it in the chosen format.
Trigger interception
In Chapter 15, I show you how to take advantage of triggers to use SQL Server
2005 Express as your agent in enforcing business and other rules. Of course,
all rules are made to be broken, but the database server is rather strict in its
interpretation of these guidelines. So you certainly receive an error if you
attempt to violate a rule encoded in a trigger. Have a look at the following
code snippet to see what I mean. Before beginning, note that a trigger is in
place to prevent users from entering a very high rating if a sufficient number
of reviews aren’t already in place.
BEGIN TRY
INSERT INTO ratings VALUES
(11,’6/10/2007’,1,100,’Best ever!’);
END TRY
BEGIN CATCH
SELECT
ERROR_LINE() as ‘Error Location’,
ERROR_NUMBER() as ‘SQL Server Error Number’,
ERROR_MESSAGE() as ‘Error Description’
END CATCH
The TRY...CATCH block works in tandem with the trigger, protecting the
integrity of the database and allowing the application developer to handle
the exception.
When using the RAISERROR statement, you can choose between building a mes-
sage at runtime or picking a predefined error message from the sys.messages
system catalog. Here’s how to store a user-defined error message in the data-
base server:
You can also use SQL Server Management Studio Express to create these
user-defined error messages.
With the message safely stored in the database, here are some examples of
using it in conjunction with RAISERROR. For the following examples, I show
both runtime-generated messages as well as the message I stored in the
database.
In this first case, here’s an example of the RAISERROR command for a user-
defined error message, using a similar message style to the one I describe in
262 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
the preceding steps. You typically invoke this error via a stored procedure,
function, or trigger:
For entry-level users and developers, SQL Server 2005 Express offers tremen-
dous functionality and power in a free package. However, certain key capabil-
ities are not present in this edition. Thus, after taking feedback from early
users into consideration, Microsoft took the baseline functionality from SQL
Server 2005 Express and added some very helpful new capabilities, and cre-
ated a new edition named SQL Server 2005 Express with Advanced Services.
This product represents a middle way for those organizations that want the
ease of use and low (actually, free) price point of the baseline SQL Server
2005 Express edition as well as higher-end features, such as full-text search
and enhanced reporting capabilities. Prior to this new edition, the only way
to gain access to this type of functionality was to purchase a more expensive
version of SQL Server 2005.
In this chapter, I point out how you can make the most of this edition. To
begin, I help you determine whether this is the right edition of SQL Server
2005 Express for you. Next, I show you how to correctly install the product.
With that vital step out of the way, the next order of business is to see how to
leverage the power of full-text searching. Finally, you see how to quickly
create and deploy reports.
264 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
I show you how to use the first two helpful features throughout the rest of
this chapter.
Installation Considerations
When installing this edition of SQL Server 2005 Express, be mindful to specifi-
cally request important product features. Otherwise, you may be unpleas-
antly surprised to find that they were skipped. For example, look at Figure
18-1 to see how the installation utility looks when selecting features.
Make sure that you enable any capabilities that you think are important in
your environment: It’s usually better to have them installed and simply not
use them than not have them when you need them.
In terms of installing the report server, it’s generally wise to choose the
default configuration rather than skipping this step. Figure 18-2 shows you
how to control the report server’s configuration.
Chapter 18: Full-Text Searching and Reporting Services 265
Figure 18-1:
Installation
feature
selection
dialog box.
Figure 18-2:
Report
server
installation
options.
266 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
To get a better idea of the exact configuration for your report server, just click
the Details button. The window shown in Figure 18-3 appears, which provides
more insight into how SQL Server 2005 Express adjusts your settings.
Figure 18-3:
Report
server
installation
details.
Speaking of reporting, to gain the full benefit of all that SQL Server 2005
Express with Advanced Services offers, make sure to download and install
the SQL Express Toolkit. It includes these key technologies (see Figure 18-4):
Finally, you should bear in mind that if you want to share your reports with
users logging in from other computers, you need to make sure that a web
server such as Microsoft’s Internet Information Services (IIS) is installed and
configured. If it’s not already set up on your computer, you can request it as
follows:
Chapter 18: Full-Text Searching and Reporting Services 267
1. Launch Control Panel from the Start menu.
2. Double-click the Add or Remove Programs icon.
3. Click the Add/Remove Windows Components icon.
The Windows Components Wizard launches.
4. Select the IIS check box and click Next to complete the wizard.
After the wizard finishes, IIS is installed on your computer.
With these details out of the way, it’s now time to see how full-text searching
can add measurable value to your database-driven solutions.
Figure 18-4:
SQL Express
Toolkit
installation.
Full-Text Searching
Many modern database-driven applications need to store and process large
volumes of text-based information. To help address these requirements, data-
base vendors continually improve the capabilities of their product offerings.
Microsoft is no exception. However, advanced text interrogation features
have generally only been found in the pricier versions of its database prod-
ucts. By including these capabilities in this free version, SQL Server 2005
Express with Advanced Services represents a break from this tradition. In
this section, I show you how this technology works and also how you can
take advantage of its power to build richer, more sophisticated applications.
268 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
⻬ Speed: When you need to search for the proverbial needle in a haystack —
where your haystack is made up of reams of text-based data — you’ll
appreciate the dramatic performance gains that full-text searches offer
versus traditional searches that use the LIKE SQL keyword.
⻬ Ease-of-use: As I show you in the “Using full-text searching” section a
little later in this chapter, you don’t need a PhD in computer science
from MIT to be productive with full-text searching. In fact, you can
quickly and simply construct your own queries in minutes.
⻬ Broad document support: Even a modern, sophisticated relational
database management system such as SQL Server is only one source of
information in most enterprises. Tons of additional data reside in all
sorts of locations, from text files to documents such as PDF, Word, and
Excel. Full-text searching lets you include these venues when construct-
ing a query.
⻬ Localization: Modern relational database management systems such as
SQL Server 2005 Express can cope with information in any language,
from Afrikaans to Zulu. When you use full-text searching (rather than the
LIKE keyword), SQL Server 2005 Express applies sophisticated linguistic
rules based on the data’s language rather than a brute force character-
matching exercise.
At its heart, full-text searching relies on special indexes that SQL Server 2005
Express rapidly creates in response to an administrator’s request. Each index
tracks details about words and phrases, including their specific row as well
as location within a column. These indexes are stored on the file system
rather than in the database.
You can create full-text indexes on columns that you define as any of the
following:
⻬ CHAR
⻬ VARCHAR
⻬ NVARCHAR
⻬ VARBINARY
⻬ IMAGE
In case you were wondering, the full-text indexing process skips over com-
monly used words, such as a, the, an, and so on. These are noise words.
270 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
Before you can create a full-text index, you need to make sure that your
table already has a unique index in place on one or more columns that
cannot be null. You should also know that you can create only one full-text
index on a table.
The process by which SQL Server 2005 Express generates a full-text index is
population. Three different mechanisms are available when undertaking this
effort:
⻬ Full population: As you may suspect from its name, this mechanism
evaluates every row in the table and constructs the appropriate index
entries based on what is learned during this process. Unless you specify
otherwise, this is the default behavior when you create a new index.
⻬ Change-tracking population: In this scenario, SQL Server keeps an eye
on changes to the full-text–indexed data over time. Armed with this intel-
ligence, it then updates the full-text index to reflect these alterations. As
an administrator, you have control over how these updates occur.
Although this edition doesn’t include SQL Agent (which means that you
can’t schedule the update), you can have them run automatically or per-
form them manually.
⻬ Incremental-timestamp population: If your table has a column with a
type of TIMESTAMP, SQL Server can automatically update the full-text
index as data changes.
With your tables in place, here are the steps you follow to make full-text
searching a reality. Before setting off down this path, you first need to make
sure your database is configured to allow full-text searching. Here’s how to
make that happen when you create a new database:
Figure 18-5:
Creating a
database
that
supports
full-text
searches.
3. Select the Use Full-Text Indexing check box and continue entering the
properties of this new database. When you’re done, click OK to save
your changes.
That’s all there is to it: Your database is now ready to support full-text search-
ing. For an existing database, all you need to do is open its properties and
switch to the Files property page; you’ll see the same check box there. Check
272 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
it, and you’re ready to go. But before you break out the champagne, you still
have a little more work to do; you now need to create the appropriate full-
text indexes, after all. Here’s how to do just that:
When it’s time to run a query, SQL Server looks at the PackingFileType
column to decide what filter to use to retrieve information. I discuss this
more in the upcoming “Examples” section.
You can create only one full-text index on a given table.
Chapter 18: Full-Text Searching and Reporting Services 273
Full-text predicates versus
full-text functions
When you set out on the full-text road, one important decision you need to
make is whether to use full-text predicates or full-text functions. Actually,
they’re not mutually exclusive, but you’ll probably find that you prefer one or
the other. Here’s a brief overview of these two full-text search capabilities:
When you’re getting started, I recommend working with the simpler full-text
predicates. After you’re up to speed, you can start to leverage the full-text
functions.
Examples
With the full-text catalog and index in place (refer to the earlier section,
“Using full-text searching”), you can finally start deriving some value from
your text-based information. In this section, I show you several different
classes of search, from the fairly commonplace to the more infrequent.
SELECT DeliveryInstructions
FROM ShipRequests
WHERE CONTAINS (DeliveryInstructions, ‘ “no signature required” ‘)
In this example, you’ve asked SQL Server 2005 Express to locate any rows in
the ShipRequests table that exactly match the string in the query.
You’re free to use Boolean logic in your full-text queries. For example, you
could modify the previous query to look for rows that match one of two
phrases as follows:
SELECT DeliveryInstructions
FROM ShipRequests
WHERE CONTAINS (DeliveryInstructions, ‘ “no signature required” OR
“do not sign” ‘)
Of course, you can also combine full-text search conditions with other SQL
conditional query logic in the WHERE clause.
Although these first examples that require exact matches are very helpful,
sometimes you’re likely to want to find all records that mean the same thing,
even if they aren’t worded the same. That brings me to the next type of
search.
SELECT DeliveryInstructions
FROM ShipRequests
WHERE FREETEXT (DeliveryInstructions, ‘damage broke crush’)
Although very helpful, this feature may not always catch all appropriate
matches. For example, searching for crush may not necessarily find an entry
that contains crushable. Likewise, using broke as a search term may not
correctly snag breakable. Keep these types of semantic challenges in mind
as you construct your database applications.
Chapter 18: Full-Text Searching and Reporting Services 275
Proximity search
As you may suspect from its name, a proximity search enables you to look for
phrases or words that are located in the neighborhood of other phrases or
words. For example, suppose that you want to look for the words signature
and required but only when they appear in the same vicinity. You don’t want
to find rows that tell you that special packaging is required or that the cus-
tomer’s signature is on file. You want only those rows that provide some guid-
ance on whether a signature is needed for delivery. You make this search
happen by specifying NEAR in your query:
SELECT DeliveryInstructions
FROM ShipRequests
WHERE CONTAINS (DeliveryInstructions, ‘(signature NEAR required)’)
That’s a lot of SQL, but it’s all necessary. For SQL Server to apply the
right query filter at runtime, you need to tell it what kind of data is being
placed into the table. That’s why you provide instructions in the
PackingFileType column.
3. Run your search.
With your data safely ensconced in its new home and SQL Server given
instructions on what kind of filter to use, locating matching words and
phrases is a cinch. Here’s a search that attempts to locate all shipments
that include packing instructions to use bubble wrap:
276 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
SELECT ShipmentID
FROM PackingInstructions
WHERE CONTAINS (PackingDetails, ‘ “bubble wrap” ‘)
Performance tips
As with most powerful tools, along with great capabilities come great respon-
sibilities. Here are a few suggestions to help you keep your full-text searches
running as quickly and smoothly as possible:
Reporting Services
What good is having a database that’s chock-full of great information if you
can’t easily access your valuable data? Although Transact-SQL lets you build
very powerful queries, expecting the average user to master the intricacies of
this data access method is not realistic.
SQL Server 2005 Express with Advanced Services offers a collection of very
powerful reporting capabilities that are designed to securely distribute
important data to everyone that needs it. In this section, I take you on a tour
of all the components that make up SQL Server’s reporting infrastructure. As
part of the tour, you’ll get the hang of designing, publishing, and maintaining
your own reports.
With your report set up, you have a number of output options:
⻬ HTML
⻬ Excel
⻬ Comma-separated value (CSV)
⻬ Portable Document Format (PDF)
You can assemble and deliver your reports via several useful avenues:
⻬ E-mail
⻬ Portal
⻬ Browser
⻬ Extensible options
278 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
1. Make sure that your computer has the complete reporting support
infrastructure.
This runs the gamut from enough processor horsepower, memory, and
bandwidth to software components. For example, if you grant remote
users access to report content via a browser, you need to ensure that
your computer has a working Web server.
2. Make sure you download and install all the correct database
components.
Simply downloading SQL Server 2005 Express with Advanced Services
isn’t enough; you also should obtain a copy of SQL Express Toolkit,
available for free from Microsoft. Found among its technologies are SQL
Server Management Studio Express as well as SQL Server Business
Intelligence Development Studio, which contains the Report Designer.
You can get the toolkit from the Microsoft Web site.
3. Configure your report server.
You need to perform or verify a number of administrative tasks before
you’re ready to start building reports. You can address all these from
Reporting Services Configuration Manager. For example, to successfully
publish reports, you must set up at least one virtual directory on the
server. As you can see in Figure 18-6, I created a virtual directory to
serve as a destination for my reports.
4. Make sure your database is created and populated.
For the example reports that I show you, the following two tables are all
that’s needed:
CREATE TABLE Clients
(
ClientID INT PRIMARY KEY NOT NULL,
CompanyName VARCHAR(50) NOT NULL,
RegionCode CHAR(1) NOT NULL
)
Figure 18-6:
Creating a
virtual
directory
in the
Reporting
Services
Configura-
tion
Manager.
With these introductory administrative tasks out of the way, now you’re
ready to create some reports. Just follow these steps:
Figure 18-7:
The New
Project
dialog box.
Figure 18-8:
Testing a
database
connection.
Chapter 18: Full-Text Searching and Reporting Services 281
5. With the Query Builder launched, either directly write your query or
use the Generic Query Designer tool for help.
Click the upper leftmost button to launch this tool. You can use this
tool to graphically develop your query, which is what’s happening in
Figure 18-9.
Figure 18-9:
The report’s
query, as
generated
by the
Generic
Query
Designer.
Figure 18-10:
The layout
for the new
report.
Figure 18-11:
Choose
where you
want to
publish your
report.
10. Verify your selections and click Finish to generate your new report.
Figure 18-12 shows where you verify your settings, and 18-13 shows the
final output.
Chapter 18: Full-Text Searching and Reporting Services 283
Figure 18-12:
The settings
for the new
report.
Figure 18-13:
The new
report as
seen from
within SQL
Server
Business
Intelligence
Studio.
284 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
You can customize, preview, and even debug your report from within
SQL Server Business Intelligence Studio. In fact, you can even edit the
XML-based report definition language (RDL) file that’s generated as part
of this process. Here’s a small snippet from the file, which shows por-
tions of both the data connection and formatting logic:
<?xml version=”1.0” encoding=”utf-8”?>
<Report
xmlns=”http://schemas.microsoft.com/sqlserver/reporting/2005/01/
reportdefinition”
xmlns:rd=”http://schemas.microsoft.com/SQLServer/reporting/repor
tdesigner”>
<DataSources>
<DataSource Name=”AdvancedServices”>
<rd:DataSourceID>e2e8470e-a912-4386-9f75-47b5bf26038b</
rd:DataSourceID>
<ConnectionProperties>
<DataProvider>SQL</DataProvider>
<ConnectString>Data Source=VPC01-AAS\SQLEXPRESS;Initial
Catalog=AdvancedServices</ConnectString>
<IntegratedSecurity>true</IntegratedSecurity>
</ConnectionProperties>
</DataSource>
</DataSources>
<rd:ReportID>1e9ca36c-9c3f-4fe1-945d-cc3a9d23490c</rd:ReportID>
<Width>5in</Width>
<Body>
<Height>0.97in</Height>
<ColumnSpacing>0.5in</ColumnSpacing>
<ReportItems>
<Textbox Name=”textbox1”>
<Style>
<FontFamily>Tahoma</FontFamily>
With your report deployed, gaining access to it is quite easy. Assuming that
you’ve set up the correct virtual directories and your Web server is running,
all you need to do is instruct your users to point their browsers at the right
report server. The users then can view the reports from within their Web
browsers. Figures 18-14 and 18-15 show the sample report from the users’
perspective.
You can print your report only on the client; server-side printing is not
supported.
Figure 18-14:
The newly
created
report,
header view.
286 Part V: Putting the Tools to Work: Programming with SQL Server 2005 Express
Figure 18-15:
The newly
created
report, detail
view.
In an effort to expand its influence with these more casual application devel-
opers, Microsoft has created a line of products that have a shallower learning
curve: You’ll find them easier and faster to get productive with. They also
sport much lower price points. Collectively known as the Express Editions,
these include the following software development technologies:
Because this chapter’s focus is Visual Basic 2005 Express, the remainder
delves into how to team this programming language with SQL Server 2005
Express to rapidly build software solutions. Visual Basic 2005 Express offers a
tremendous amount of features and capabilities; this chapter covers a relatively
small percentage of this functionality, primarily as it pertains to database
interaction. To find out more, check out a copy of Visual Basic 2005 Express
Edition For Dummies, by Richard Mansfield (Wiley).
Just as Visual Basic 2005 Express represents a more easily understood imple-
mentation of Visual Basic, SQL Server 2005 Express offers a simpler set of fea-
tures than those found in the more robust editions of the database server.
Anticipating that people building applications with Visual Basic 2005 Express
need an easily understood data repository, Microsoft bundles SQL Server 2005
Express with the software development environment. The Visual Basic 2005
Express download package includes the database server. Many developers
find that this database is right for their applications’ storage requirements.
Creating a project
To begin, you need to set up a project in Visual Basic 2005 Express. Here’s
how to make that happen.
Chapter 19: Building a Simple Desktop Application with Visual Basic Express 291
1. Launch Visual Basic 2005 Express.
2. Choose File➪New➪Project.
The New Project dialog box opens where you can select the type of pro-
ject you want to create, as shown in Figure 19-1.
Figure 19-1:
Choosing
the type of
new project.
3. Choose the Windows Application option from the New Project dialog
box and click OK.
If you want to build another type of application, just choose the appro-
priate template. For this example, though, I stick to a Windows
Application.
4. In the Name box, enter a name for what you want to call your project,
and then click OK.
Visual Basic 2005 Express then performs some initial housekeeping and
setup. Eventually, a blank form appears on-screen. Your next task is to
associate a database with this project, which you can do now or later.
Figure 19-2:
Adding a
database to
the project.
4. Select the SQL Database template, provide a name for your database,
and click OK.
A new database is created, and then the Data Source Configuration
Wizard launches. In the section coming up, I show you how to create
tables, using this wizard.
Figure 19-3:
Setting
advanced
database
connection
properties.
Although I wish I could give you some hard-and-fast rules about what
settings to use in this dialog box, each environment is different. Trial-
and-error may be your best friends for this job. One area for particular
attention is the User instance property. If you already have a running
SQL Server 2005 Express instance, you want to set this property to
False.
294 Part VI: Creating SQL Server 2005 Express Applications
Figure 19-4:
Choosing
objects for
inclusion
into dataset.
You have quite a bit of control here: You can even choose individual
columns within a table for inclusion.
Unless you’re sure that you won’t want a given object in your applica-
tion, include it in your dataset at this time.
After you finish, you see the new connection added to the Data
Connections root node.
Figure 19-5:
Creating a
table within
Visual
Basic 2005
Express.
296 Part VI: Creating SQL Server 2005 Express Applications
You can test your new table very quickly from Visual Basic 2005 Express.
Here’s what to do. You can skip Steps 1 and 2 if you have the development
environment running.
Figure 19-6:
Viewing
table data
within
Visual Basic
2005
Express.
As I mention at the start of this chapter, this sample program is a simple data
entry grid that lets users interact with customer information. The first step
on the road to this application is to build a form that houses the data entry
Chapter 19: Building a Simple Desktop Application with Visual Basic Express 297
grid. You can skip the first two steps if Visual Basic 2005 Express is already
running.
Figure 19-7:
A simple,
yet
powerful,
database-
aware form
in Visual
Basic 2005
Express.
298 Part VI: Creating SQL Server 2005 Express Applications
8. Stop debugging by closing the running form, and then save your new
form by clicking the Save icon.
With your table and form now in place, you have tremendous control over
the look-and-feel and behavior of their information. Much of this power doesn’t
even require you to write any code. Continuing with the grid example I just
created, here’s all you need to do to gain access to these properties:
Visual Basic 2005 Express offers some great programming productivity tools
that you can use to shorten your development cycle. One of the most inter-
esting of these technologies is known as IntelliSense snippets (blocks of pre-
built code, tailored and customized for specific tasks). If you want to take
advantage of pre-built code snippets, do the following:
Figure 19-8:
High-level
IntelliSense
categories.
300 Part VI: Creating SQL Server 2005 Express Applications
Figure 19-9:
IntelliSense
code
snippets.
After you include the IntelliSense code, your application code looks
something like Figure 19-10.
Figure 19-10:
Two
IntelliSense
code
snippets
inserted into
a file.
Figure 19-11:
A sample
debugging
session.
Take the time to learn how to use the debugger. Even if your first few pro-
grams are very simple, you’ll eventually need to fix problems, and the debug-
ger helps shave valuable time off of what is often a very tedious set of tasks.
To help boost its presence with this community, Microsoft has created a line
of products that are simply easier to use. Known as the Express Editions, they
include the following languages and application development products:
Visual Web Developer 2005 Express integrates nicely with SQL Server 2005
Express. That’s a theme of this chapter, where I give you repeated examples
of how closely the two products interoperate. In fact, to encourage this cou-
pling, when you download the development platform, Microsoft thoughtfully
bundles the database server. For most developers, SQL Server 2005 Express
does a fine job of meeting their data storage needs. On the other hand, if
you’re inclined to use another database, you’ll find that Visual Web Developer
2005 Express presents no obstacles.
Figure 20-1:
Providing
details for a
new Web
site.
306 Part VI: Creating SQL Server 2005 Express Applications
Figure 20-2:
The
beginnings
of a new
Web site.
Figure 20-3:
Choosing
a new
database
template.
4. Select the SQL Database template, provide a name for your database,
and click Add.
You may be asked if you want to place the database in the App_Data
folder. Click Yes to this question. The database creation may take some
time to complete.
Step 4 may create an error. If this happens in your environment, just
follow the instructions in the next section.
Figure 20-4:
Creating a
new empty
database.
Chapter 20: Building a Simple Web Application with Visual Developer Express 309
Although I wish I could give you some hard-and-fast rules about what
settings to use in this dialog box, each environment is different. Trial-and-
error may be your best friends for this job. One area for particular atten-
tion is the User instance property. If you already have a running SQL
Server 2005 Express instance, you want to set this property to False.
5. To make sure everything is configured correctly, click the Test
Connection button.
This is one last sanity check. If you’ve designated your connection accu-
rately, the test connection happens almost instantaneously. If not, you
need to continue tuning your settings.
6. Click OK to complete creating the new connection.
Figure 20-5:
Creating a
new table.
Figure 20-6:
Viewing a
new table.
Chapter 20: Building a Simple Web Application with Visual Developer Express 311
Building the User Interface
Generally, designing and creating your database before starting work on the
user interface is a good idea. After the database and its tables are in place,
the process of incorporating these structures into your Web application is
actually quite simple. In this section, I show you how to take the adult educa-
tion sample database that I show you how to create in the previous section of
the chapter, and turn it into a powerful Web application.
To start, the first step is to construct a user interface that lets the administra-
tor pick a class to view. Here’s how to make that happen. If you have the
product running, you can skip Steps 1 and 2.
8. Choose the New Data Source option from the Select a Data Source
drop-down list.
9. Click the Database icon.
10. Provide a meaningful name for the data source, or just choose the
default.
11. Select the data connection you just configured, and click Next.
12. Save the connection string to the application configuration file.
With your connection now defined, the next task is to hook up the drop-
down box you just added to the form with the database.
13. Configure the SELECT statement according to your application’s needs.
In this case, I’m asking Visual Web Developer 2005 Express to retrieve
the ClassName from the Classes table.
14. Save the Web page, and then test it by choosing Debug➪Start Without
Debugging, or pressing Ctrl+F5.
If everything went according to plan, you see a very basic, yet database-
aware form, as shown in Figure 20-7.
Figure 20-7:
A database-
aware drop-
down list.
Chapter 20: Building a Simple Web Application with Visual Developer Express 313
If you did everything correctly, your drop-down list is now filled in with a list
of classes. With that out of the way, you can move to listing the students that
are in each class. The goal is to let the user view details about each student
in the class, as well as make changes to each entry. Just follow these steps:
1. Open (or reopen) the Web site, and its Default.aspx page.
2. Make sure you’re in Design view.
3. Drag a GridView control onto the page.
You find this control under the Data portion of the Toolbox.
4. On the GridView Tasks menu, choose New Data Source from the
Choose Data Source drop-down list.
Using Steps 9 through 12 in the preceding step list as a guide, fill in the
wizard. You’re prompted, as before, to configure the data source.
5. Select the table(s) and column(s) that you want to display.
In this case, I want to display relevant details about each student in the
class that was selected in the drop-down list, so I pick those columns
from the StudentsClasses table.
To allow editing/inserting/deleting of information, make sure that a pri-
mary key is defined on the table and selected during this part of the
workflow.
6. Click the WHERE button to link the selected value from the drop-
down list to your database query (see Figure 20-8).
The Add WHERE Clause dialog box opens. Fill in these fields:
• Column: This is the table’s column that will be filtered by the
WHERE clause that you’re currently creating.
• Operator: This is the operator (=, >=, <>, and so on) that will be
built into the SQL expression that makes up this WHERE clause.
• Source: This is the location where your application will obtain the
filtering criteria necessary to generate the WHERE clause. You can
choose to retrieve a value from a control, cookie, form, profile,
query string, and session.
• Parameter properties: Depending on which source you chose, this
portion of the dialog box contains additional details about how to
construct the WHERE clause.
7. After you finish assembling your WHERE clause parameters, click Add
to see what you’ve built.
You see the exact SQL expression that your application will use.
314 Part VI: Creating SQL Server 2005 Express Applications
Figure 20-8:
Setting the
drop-down
list’s output
to help
locate data.
Chapter 20: Building a Simple Web Application with Visual Developer Express 315
12. Configure the look-and-feel of your application, and then deploy the
Web site.
I’ve saved this step for last, and suggest that you do the same. Don’t
worry about how the application appears until you have all the pieces
working together. Figure 20-9 shows the page with some new fonts and
styles applied. It’s still not done, but it’s closer. Don’t be surprised if you
spend most of your development time working on look-and-feel issues
rather than database and application logic tasks.
Figure 20-9:
Changing
the look and
feel of the
application.
316 Part VI: Creating SQL Server 2005 Express Applications
Chapter 21
Regardless of your familiarity with XML, this chapter can help you grasp how
you can blend it with your SQL Server 2005 Express database. To begin, I take
you on a brief tour of XML, followed by an overview of how you can store this
type of information in your database. Finally, you see how to work with XML
data after placing it into SQL Server 2005 Express.
XML advantages
When compared with alternate means of representing and interchanging
information, XML offers some compelling benefits:
XML has a few relatively minor drawbacks. They chiefly revolve around the
somewhat cumbersome nature of supporting non-text information (such as
video, music, and other binary data) within an XML document. In addition,
some believe that the parsing and manipulation of XML data is too expensive,
and leads to degraded performance. Finally, a real-world XML document with
many levels of nested data can be very hard to understand by a human reader.
XML structure
What does XML look like? Take a peek at the following small example of a pur-
chase order:
Confused? Don’t be: The best way to make sense of an XML document is to
look at it line by line, which is what I do next.
This first line is known as the XML declaration, and includes details about the
XML version as well as any language encoding. This XML was created to sup-
port version 1.0 of the XML standard, and it’s encoded with Unicode.
I just said to look at XML on a line-by-line basis, and yet now I show you the
second and very last lines. The reason I did so is to point out that the entire
document is wrapped by the <PO> and </PO> tags, known as the start tag and
end tag, respectively. Everything between these two tags refers to the pur-
chase order, identified by PO in this case. Tags like this one represent an ele-
ment. You can nest elements as well; in fact, most XML data consists of
elements often deeply nested within higher-level elements. In this case, the
PO element is the highest-level element. Everything that you see between the
start tag and end tag is known as content.
<Customer>
<Name>Soze Imports</Name>
<Identifier>21109332</Identifier>
<reg:Instructions xmlns:reg=”http://www.samplenamespace.com/importexport”>
<reg:Restrictions>Not subject to export control</reg:Restrictions>
320 Part VI: Creating SQL Server 2005 Express Applications
Continuing, you now see a nested element known as Customer, whose start
tag is <Customer> and end tag is </Customer>. This element itself contains
two nested elements, one known as Name, and the other known as
Identifier.
<reg:Instructions xmlns:reg=”http://www.samplenamespace.com/importexport”>
By specifying this namespace server, any applications that use this XML doc-
ument consult the namespace server for details about any elements or attrib-
utes prefixed with reg. A second namespace server comes up a little later in
the XML.
<Creator>Michael McManus</Creator>
Now you can see additional elements, both known as Product. These ele-
ments have their own attributes, quantity and price in this case.
<ship:Shipment xmlns:ship=”http://www.samplenamespace.com/shipping”>
<ship:ShipDate>6/10/2007</ship:ShipDate>
<ship:Instructions>Contact Mr. Hockney in receiving</ship:Instructions>
<ship:Instructions>Fax bill to Mr. Kobayashi</ship:Instructions>
</ship:Shipment>
Chapter 21: Using XML with SQL Server 2005 Express 321
Finally, the document contains an element known as Shipment, which itself
contains nested elements called ShipDate and Instructions. Notice that
to clear up confusion with the earlier reference to Instructions, a link is
included to another namespace server:
<ship:Shipment xmlns:ship=”http://www.samplenamespace.com/shipping”>
That’s it — you now know how to parse an XML document. As you may imag-
ine, however, bigger or deeper XML documents are harder to understand.
Fortunately, many tools on the market help you make sense of this kind of
information. For example, Figure 21-1 shows how this document looks inside
Microsoft’s XML Editor. If this tool looks familiar to you, it should: It’s
Microsoft Internet Explorer, which happens to be the default application for
displaying XML documents in Windows.
Figure 21-1:
An XML
document
within the
XML Editor.
One nice thing about using a specialized XML viewer is that you can expand
or collapse various elements. Figure 21-2 shows how I collapsed some of the
inner elements. Imagine how useful this technique would be for an XML docu-
ment containing thousands of lines of detail.
Figure 21-2:
A more
concise
view of an
XML
document.
these concepts, but several remain. However, you don’t need to worry: I’m as
concise as possible.
<Customer>
<Name>Soze Imports</Name>
<Identifier>21109332</Identifier>
<reg:Instructions xmlns:reg=”http://www.samplenamespace.com/importexport”>
<reg:Restrictions>Not subject to export control</reg:Restrictions>
<reg:Duties>Not subject to duties</reg:Duties>
</reg:Instructions>
</Customer>
XML schema
An XML schema is a data structure that you define to help provide validation
constraints and other details about specific typed XML data (more about that
in the upcoming section). You can specify which attributes are mandatory,
their formats, permissible quantities, and so on. I show you an XML schema
in conjunction with database operations in the “Placing XML into Your SQL
Server 2005 Express Database” section.
Common Language Runtime (CLR) languages. You are faced, however, with a
2GB limitation for any particular XML document. To find out more about inte-
grating CLR with SQL Server 2005 Express, check out Chapter 16.
In this section, I show how to leverage the XML storage capabilities of SQL
Server 2005 Express. Before I begin, remember that I keep the examples as
straightforward and basic as possible. You can perform some extremely
sophisticated data manipulations, using XML, but starting with a solid foun-
dation is a good idea before attempting more advanced operations. These
examples highlight an application that tracks shipment and part information.
1. Launch your favorite SQL editor, and connect to your database server
and database.
I use SQL Server Management Studio Express, provided by Microsoft via
free download.
2. Decide if you want to create or use an XML schema collection.
In this case, I’ve chosen to create a new XML schema collection, which
creates an element known as parts, which itself contains elements
known as code, name, and price. It also cites that a given part can have
an unlimited number of these nested elements:
CREATE XML SCHEMA COLLECTION Parts AS
N’<?xml version=”1.0” encoding=”UTF-16”?>
<xsd:schema
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>
<xsd:element name=”parts”>
<xsd:complexType>
<xsd:choice minOccurs=”0” maxOccurs=”unbounded” >
<xsd:sequence>
<xsd:element name=”code” type=”xsd:string”/>
<xsd:element name=”name” type=”xsd:string”/>
<xsd:element name=”price” type=”xsd:decimal”/>
</xsd:sequence>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
‘
After your XML schema is in place, you can put it to work and associate
it with relevant objects.
3. Design and create your table.
Here’s an example of a table:
Chapter 21: Using XML with SQL Server 2005 Express 325
CREATE TABLE Shipments
(
ShipmentID INTEGER PRIMARY KEY NOT NULL,
ShipmentDate DATETIME NOT NULL,
ShippedParts XML
)
If you’ve created an XML schema, you can simply reference it as part of
the table creation logic. If I wanted to associate this table with the XML
schema collection that I created earlier, all that’s necessary is to slightly
alter the table definition:
CREATE TABLE Shipments
(
ShipmentID INTEGER PRIMARY KEY NOT NULL,
ShipmentDate DATETIME NOT NULL,
ShippedParts XML (Parts)
)
You can create indexes on XML columns. You have two types of indexes
at your disposal: primary and secondary. A primary index shreds, or dis-
assembles, the XML data that is normally stored in binary large object
(BLOB) format, making information quicker to find. With the primary index
in place, you may then create three distinct types of secondary indexes.
• PATH: This contains the Path ID and Value columns from the pri-
mary XML index.
• PROPERTY: This is made up of the primary key from the underly-
ing table, concatenated with the Path ID and Value columns from
the primary XML index.
• VALUE: This index is the mirror image of the PATH index. It con-
tains the Value and Path ID columns.
The SQL Server 2005 Express query optimizer chooses the proper sec-
ondary index based on the query criteria.
4. Insert data into your table.
Here’s an example of creating a single row with two XML entries.
Normally, this kind of relationship would require you to separate the line
item entries into their own table, because it has two entities:
INSERT INTO Shipments VALUES(1,’<Root>
<Parts OrderID=”1” PurchaseOrderNumber=”NSSDJS#1”>
<DeliveryDate>2006-12-30</DeliveryDate>
<Items>
<ShipmentWeight>2.44</ShipmentWeight>
<LineItem>
<Name>DentaKit for Adults</Name>
326 Part VI: Creating SQL Server 2005 Express Applications
<Code>DK-R001</Code>
<Price>29.95</Price>
</LineItem>
<LineItem>
<Name>Retainer Brite 1 Year</Name>
<Code>DK-RB1Y</Code>
<Price>35.00</Price>
</LineItem>
</Items>
</Parts>
</Root>’)
Notice how seamlessly the SQL and XML code integrate; embedding
XML inside SQL just requires some careful quote mark placement.
As with many other SQL Server 2005 Express technologies, you can take vari-
ous paths when working with XML data. To keep these examples as straight-
forward as possible, I explore a limited subset of these options. In particular, I
steer away from the potentially confusing subject of namespaces. I also use
untyped XML to reduce visual clutter.
To help you locate and modify XML-based information, five data functions
are at your disposal. Table 21-1 highlights these methods, along with their
purposes.
For the balance of this chapter, I show you how to use these methods to
achieve your goals. I continually refer to the Shipments table that I lay out in
Chapter 21: Using XML with SQL Server 2005 Express 327
the “Placing XML into Your SQL Server 2005 Express Database” section, ear-
lier in this chapter.
SELECT ShippedParts.query(‘/Root/Parts/DeliveryDate’)
FROM Shipments
WHERE ShipmentID = 1
This query retrieves the DeliveryDate element. To get a list of all the items
in the document, here’s how the query looks:
SELECT ShippedParts.query(‘/Root/Parts/Items’)
FROM Shipments
Using the exist() method, you can easily create a query that inspects the
XML data and looks for matches:
SELECT ShippedParts.query(‘/Root/Parts/Items/LineItem’)
FROM Shipments
WHERE ShippedParts.exist(‘
/Root/Parts/Items/LineItem[Name=”DentaKit for Adults”]
‘) = 1
This query returns all records that have line items with a product name that
corresponds to DentaKit for Adults.
If you want to retrieve XML information and place it in standard SQL format,
just use the value() method:
SELECT ShippedParts.value(‘
(/Root/Parts/Items/ShipmentWeight)[1]’,’decimal(6,2)
‘)
FROM Shipments
In the preceding example, I’m converting the shipment weight element from
the ShippedParts XML column into a decimal(6,2).
If you want to cut to the chase and just issue plain old SELECT statements,
you must know how SQL Server Management Studio Express displays this
information. Just click any column that contains XML, and you see something
like what’s shown in Figure 21-3.
328 Part VI: Creating SQL Server 2005 Express Applications
Figure 21-3:
XML data in
SQL Server
Management
Studio.
UPDATE Shipments
SET ShippedParts.modify(‘
replace value of (/Root/Parts/@PurchaseOrderNumber)[1]
with “TVC-15 PR1DA”
‘)
WHERE ShipmentID = 1
The modify() method expects you to provide a string that conforms to the
XML Data Manipulation Language (XML DML). XML DML extends the stan-
dard XQuery language, making data alterations easier to undertake.
When deleting records, you can use the delete statement from within the
modify() method. Here’s an example of removing the second line item entry
from within the Items node:
UPDATE Shipments
SET ShippedParts.modify(‘delete /Root/Parts/Items/*[2]’)
WHERE ShipmentId = 1
By using the FOR XML directive, you can instruct SQL Server 2005 Express to
convert the output from a given query into XML. In this first example, I use
the RAW directive to create basic XML output:
SELECT Shippers.ShipperName,
ShipperLocations.LocationName
FROM Shippers, ShipperLocations
WHERE Shippers.ShipperID = ShipperLocations.ShipperID
ORDER BY ShipperName
FOR XML RAW
By using RAW, I’ve asked SQL Server 2005 Express to create generic, non-
nested rows that are prefixed with row:
Things get more interesting with the AUTO directive, which returns its results
in a simple tree:
SELECT Shippers.ShipperName,
ShipperLocations.LocationName
FROM Shippers, ShipperLocations
WHERE Shippers.ShipperID = ShipperLocations.ShipperID
ORDER BY ShipperName
FOR XML AUTO
This small sample shows how you can format relational data into an XML struc-
ture. You have many other options at your disposal, from controlling the layout
of the tree to producing an XML schema to handling binary information.
Part VII
The Part of Tens
In this part . . .
S QL Server 2005 Express is a great choice for a data-
base platform. It combines entry-level simplicity and
price with the power and capabilities of an industrial-
strength database engine. And given the broad reach of
Microsoft’s technologies, a wealth of information is out
there about how to make the most of this product.
A s you embark on your SQL Server 2005 Express journey, you can take
comfort in the fact that there are many others on the same path. In this
chapter, I show you how to leverage some of the abundant resources pro-
vided by your fellow SQL Server devotees to help make your trip smoother.
www.microsoft.com/sql/default.mspx
334 Part VII: The Part of Tens
http://msdn.microsoft.com/sql
You can also get some great help at the Microsoft TechNet Web site:
www.microsoft.com/technet/prodtechnol/sql/default.mspx
Wikipedia
No, this isn’t a misprint: You read correctly. Believe it or not, this Internet-
based, open-source encyclopedia (www.wikipedia.org) is a great source of
information about all technology topics, including relational database theory
and practical application. For example, here’s a link to a very comprehensive
article on database normalization in theory and practice:
http://en.wikipedia.org/wiki/Database_normalization
Newsgroups
These collaborative spaces are an immense help when you’re struggling with
a technical problem. Chances are that someone can address your question. In
the past few years, Google has done a great job helping to organize and
rescue Usenet. It’s easier than ever to access these groups via your browser.
Here’s a link to 27 (at last count) newsgroups focused solely on SQL Server:
http://groups.google.com/groups/dir?lnk=gh&hl=en&sel=33606733
You can also find some great links to SQL Server newsgroups at Microsoft
TechNet:
www.microsoft.com/technet/community/newsgroups/server/
sql.mspx
Chapter 22: Ten Sources of Information on SQL Server 2005 Express 335
Magazines
Several well-written magazines are available that provide significant coverage
of database topics. Some are database-agnostic, while others focus specifi-
cally on this product. These periodicals include
User Groups
These gatherings of like-minded individuals are a great place to enhance your
understanding of SQL Server 2005 Express. Some groups meet virtually, while
others have physical events; some groups span both realms. Two of the
better Internet-focused most relevant user groups include the SQL Server
Worldwide Users Group (www.sswug.org), as well as the Professional
Association for SQL Server (www.sqlpass.org).
On the other hand, if you want to meet and greet your counterparts face-to-
face, chances are that an Internet search can point you toward a good candi-
date user group not too far from you.
Books
While this book helps you get started with SQL Server 2005 Express, many
other titles can give you a broader understanding of building high-quality
database applications. Try looking for well-regarded books that cover any of
these topics; they are all pertinent in the context of SQL Server 2005 Express:
www.embarcadero.com/products/products.html
Administrative Tools
As I’ve shown throughout the book, SQL Server Management Studio is a great
tool for administering your SQL Server 2005 Express database. However, you
may also be interested in one of the third-party tools out there. I’ve used
TOAD for SQL Server by Quest Software; all the major database platforms
have versions of this product. You can find it here:
www.toadsoft.com/toadsqlserver/toad_sqlserver.htm
www.sqledit.com/dg/index.html
Blogs
There are some great blogs out there that offer a broad range of information
about SQL Server. You’ll even find postings from the Microsoft product devel-
opment teams. Check out the blogs at technet.com and msdn.com:
http://blogs.technet.com
http://blogs.msdn.com
Chapter 23
⻬ Check out Microsoft’s Web site. You find a handy download link for SQL
Server at www.microsoft.com/sql.
⻬ Use the enclosed CD. To make things even easier, a copy of SQL Server
2005 Express is on the CD that comes with this book. Simply insert the disc
in your CD drive, and follow the on-screen instructions. You’ll be off and
running in no time. (Appendix D contains more information about the CD.)
338 Part VII: The Part of Tens
If you want more ideas about how to have a good installation experience,
have a look at Chapter 2.
⻬ Make sure the database server is running: Unless you request that the
SQL Server 2005 Express service launch when your system boots, you
simply need to start the service. Chapter 2 tells you all about kicking off
the SQL Server 2005 Express service.
⻬ Make sure that you’re using the right protocol: You can use several
communications methods to communicate with SQL Server 2005
Express. In order to successfully converse with the database server, you
need to make sure that both the client and server are speaking on the
Chapter 23: Ten SQL Server 2005 Express Troubleshooting Tips 339
right channel with the right setup. In particular — because SQL Server
2005 Express defaults to local connections only — if you want remote
access, you must run the SQL Server Surface Area Configuration tool to
allow both local and remote connections. You can also choose the proto-
col for these conversations. Chapter 3 reveals all that you need to know
to get the dialogue going.
⻬ Adjust your connection string: When you connect to SQL Server 2005
Express, you need to specify a connection string that helps locate the
database server. Often highly site-specific, even the smallest error in this
connection string dooms your conversation from the start. Chapter 4
has all the details about the various flavors of connection string that
you’re likely to encounter.
⻬ SQLCMD utility: This character-based tool ships with every copy of SQL
Server 2005 Express. You can run just about any administrative task by
using direct Transact-SQL or one of the hundreds of built-in system
stored procedures.
⻬ SQL Server Management Studio Express Edition: If you have more of a
hankering for graphical tools, you want to look at this utility. While a full-
featured version ships with the more extensive SQL Server editions, even
this entry-level version available for SQL Server 2005 Express lets you per-
form many administrative chores. And whatever isn’t possible, you can
always handle with direct Transact-SQL or system stored procedures.
Because it’s built on the enterprise-class SQL Server database platform, SQL
Server 2005 Express offers all the security capabilities of its bigger siblings.
Unfortunately, all this power can sometimes translate into unforeseen security
340 Part VII: The Part of Tens
obstacles. These aren’t hard to overcome, but you do need to know how to
correctly configure your permissions. Check out Chapter 11 to get a handle
on all that you can do with security in SQL Server 2005 Express.
Think of a view as a window into your information, one that can span the
entire database to retrieve results. By pre-building all the joins and stripping
out any extraneous details, you can make this window much simpler than the
underlying data. The end result is that your users and developers can work
with the view, rather than the base database tables. To see how views can
make things better for your enterprise, take a look at Chapter 10.
If you have a different taste in programming languages, don’t worry: You can
develop software that works with SQL Server 2005 Express in just about any
language. In fact, Microsoft offers Express editions of its Visual Studio prod-
uct for other languages, such as Java, C++, and C#.
In this chapter, I show you how to make an informed decision about whether
to upgrade or not. Assuming that you elect to follow the upgrade path, you
find out how to create a workable plan, as well as how to leverage an excel-
lent utility that makes migrations a snap.
Why Migrate?
For many SQL Server 2005 Express installations, this question never arises.
The product will faithfully serve your needs, and there will be no need to look
for an alternative. However, a significant number of database administrators
find themselves bumping up against some of the product’s inherent limita-
tions. Here are a few of these barriers:
⻬ Memory: Even if you fill your server with memory, SQL Server 2005
Express doesn’t take advantage of any more than 1GB of RAM. For small
to mid-sized applications, this limitation isn’t a problem. However, larger
solutions may need more.
⻬ Database size: If you’re building a solution that needs to hold large
amounts of data in a single database, you may not be happy with the
4GB limitation per database in SQL Server 2005 Express.
⻬ Multi-processors: SQL Server 2005 Express takes advantage of only one
physical processor-based CPU, regardless of how many are available
346 Part VIII: Appendixes
However, for the balance of this chapter, I focus on the excellent Import and
Export Wizard, which is part of SQL Server Management Studio. Understanding
this utility is important; you may find it very useful for other types of data
migration, such as importing information from other brands of database
server. The one assumption that I make here is that you can connect to both
your existing SQL Server 2005 Express database server as well as your new
database server.
Your new database is now ready to receive all your data from SQL Server
2005 Express. Just follow these steps to finish the job; you can skip Steps 1
and 2 if you left SQL Server Management Studio running from the previous
set of instructions.
Figure A-1:
Choosing a
data source.
6. Choose your new database server from the Server Name drop-down
list and select either Windows or SQL Server authentication.
7. Select your new database.
Figure A-2 shows how the Choose a Destination screen appears after you
make choices in Steps 5 through 7.
8. Click Next.
Appendix A: Upgrading to SQL Server 2005 349
Figure A-2:
Destination
server
details.
9. On the Specify Table Copy or Query screen, decide whether you want
the wizard to copy all data, or if you want to provide a query to
restrict the result set. Then click Next to continue.
For this example, stick with a full database copy (as I’ve done in
Figure A-3).
Figure A-3:
Choosing
whether to
copy all
data or
provide a
filtering
query.
10. On the next screen of the wizard (shown in Figure A-4), pick one or
more tables and views to copy, and click Next.
350 Part VIII: Appendixes
Because you’re upgrading your entire database, choose all tables and
views. If your new database already has tables in place, you can edit the
field mappings by clicking the Edit button for the tables in question.
Figure A-4:
Selecting
tables and
views for
import.
11. Decide if you want to run the job immediately, or save it for later.
Click Next to continue.
For this example, keep going and run the job right now.
After you click Next, the wizard gives you one last chance to change
your mind before it starts its work, as you can see in Figure A-5.
Figure A-5:
Confirming
your
selections.
Appendix A: Upgrading to SQL Server 2005 351
12. Verify your choices and click Finish.
13. Check for any errors after the job runs.
Figure A-6 shows the report that the wizard creates upon completion. No
rows have been copied; in this case, my SQL Server 2005 Express source
database was empty because my goal was to simply replicate the data-
base structure. In reality, you see accurate row counts for each table.
Figure A-6:
Post-import
report.
With the migration finished, you have one more important task to complete:
Back up your new database so that you preserve your information in a pris-
tine state.
352 Part VIII: Appendixes
Appendix B
T here are many good reasons to choose a functionally rich yet low-priced
database platform like SQL Server 2005 Express. Regardless of your ration-
ale for making this decision, you can use the information found in this appen-
dix to help guide you through the important process of safely and securely
moving your data from its existing locations to your new SQL Server 2005
Express instance. On the other hand, if all you seek is more details on the
process of installing your database server, check out Chapter 2.
not apply to your enterprise, chances are that many of them are worth
considering.
⻬ Are your hardware and software sufficient? SQL Server 2005 Express
doesn’t require a supercomputer, but it does have some basic hardware
and software prerequisites that you want to make sure your environ-
ment meets. Chapter 2 addresses these preconditions.
⻬ Does SQL Server 2005 Express meet your needs? In Chapter 1, I high-
light some features and limitations of this product; it’s worth reviewing
before attempting a migration.
⻬ What applications are affected? Make an inventory of those applica-
tions that are affected by the upgrade, and check that they work with
SQL Server 2005 Express. The odds are that most general-purpose,
ODBC-capable solutions can interact with this product. The same can’t
be said for heavyweight enterprise applications. To be safe, check with
the solution provider.
⻬ When is the right time to upgrade? Ideally, you want to perform your
upgrade during a period of reduced activity, while also factoring in time
to restore your original configuration should things go askew. Juggling a
particularly busy workload and a software upgrade at the same time is
not fun.
⻬ Are there major product differences? Given that its architecture is
based on the powerful SQL Server platform, chances are that SQL Server
2005 Express is more feature-rich and functional than your existing data-
base product. Still, double-checking this assumption is worth your time,
especially if your current database has highly specialized features that
are necessary for your environment.
⻬ Should you work in parallel? In many cases, working in parallel is the
safest way to test a new software configuration. You could assign a
group of users to work with SQL Server 2005 Express, manage any prob-
lems, and then switch everyone to the new platform after you resolve
these issues.
If you go the parallel route, be sure that you keep track of data modifica-
tions in both the new and old systems. Otherwise, you run the risk of
losing information when the upgrade is complete.
⻬ Microsoft Access
⻬ Microsoft Data Engine (MSDE)
⻬ Text files
Microsoft Access
Up until now, many of you have used Microsoft Access as your database envi-
ronment. It’s a good choice for many entry-level, single-user applications, but
a time comes when you need to upgrade to a more powerful and flexible data-
base platform such as SQL Server 2005 Express. Fortunately, making this
transition is quite easy.
You may take several iterations to get the import process working correctly.
Don’t despair: You can keep fine-tuning your import effort until you get it
right. Here’s what you need to do:
Figure B-1:
Choosing
to create
a new
database or
load existing
database.
Figure B-2:
Connecting
to the
database,
and
providing a
database
name.
Figure B-3:
Upgrading
all tables.
358 Part VIII: Appendixes
Figure B-4:
Exporting
table
attributes.
Appendix B: Migrating to SQL Server 2005 Express 359
Figure B-5:
Setting
application
properties.
Figure B-6:
The
Upsizing
Wizard
report.
360 Part VIII: Appendixes
Use the default instance name for your new SQL Server 2005 Express instance
if you directly installed MSDE.
On the other hand, if you installed MSDE as part of a larger packaged soft-
ware installation, just follow these steps to ensure that your database gets
moved to the new server.
1. Install SQL Server 2005 Express using a different instance name than
your MSDE instance.
Use the Named Instance option to request this alteration.
2. When SQL Server 2005 Express is installed, detach the database from
your earlier MSDE instance.
3. Attach the database to SQL Server 2005 Express.
Alternatively, you can run the SQL Server 2005 Express setup program in
custom mode. You can then specify the instance name of your existing MSDE
environment, and you’ll be asked if you want to upgrade this database to SQL
Server 2005 Express.
Text files
If you’ve been storing your information in text files, you’ll find SQL Server
2005 Express to be a much safer and more powerful alternative. However, you
must do some work to get your data migrated. Here’s what you need to do to
make the leap forward:
1. Decide on a database and table structure for SQL Server 2005 Express.
In order to import data, you need a destination. You can elect to create a
one-to-one correlation between your text file–based data and its new
home in SQL Server 2005 Express. On the other hand, you can choose to
create a by-the-book relational database design. In either case, some
planning and thought are required on your part.
To find out more about designing relational databases, have a look at
Chapters 8 and 9.
2. Run the bcp utility, instructing it where to find the data source and
destination.
Appendix B: Migrating to SQL Server 2005 Express 361
This feature-rich, command-line application allows data to move
between SQL Server 2005 Express and external solutions and file for-
mats. You can feed this utility many parameters and settings to help it
gracefully handle your import files; once determined, you can then save
the settings in format files. Figure B-7 shows the available settings for
this application.
I discuss how to use bcp in more detail in Chapter 9.
3. Alternatively, run one of the many third-party utilities available for
data migration.
While the bcp utility is very powerful, you may find it too cumbersome
and arcane to be useful. However, the software market abounds in inde-
pendent tools that do nothing but move information among various for-
mats; one of these tools may make sense for you.
You can even use tools like Microsoft Access and Excel as import utili-
ties, but you have to set up ODBC connections and perform other gym-
nastics that are handled more naturally by bcp or a specialized,
third-party data migration utility.
Figure B-7:
bcp utility
variables.
First, backing up your brand-new SQL Server 2005 Express database is essen-
tial. Doing so gives you a way out in case anything goes wrong after you start
using the database server.
With the backup out of the way, the next order of business is to create an
ODBC data source. You can skip this step if you have no applications or tools
that use ODBC as their primary communication mechanism with your data-
base. However, odds are you need to complete this step. Here’s how to do it:
362 Part VIII: Appendixes
With these last steps out of the way, you can now confidently start using your
SQL Server 2005 Express database.
Figure B-8:
Summary
of ODBC
settings.
Appendix B: Migrating to SQL Server 2005 Express 363
Figure B-9:
A suc-
cessful
connection.
364 Part VIII: Appendixes
Appendix C
Glossary
Advanced Services: A more capable version of SQL Server 2005 Express.
While this edition maintains its sibling’s free price point, it includes some
advanced technologies such as full-text searching and reporting services.
assembly: Application logic that is stored in, and managed by, the SQL Server
2005 Express database server, including objects such as triggers, CLR soft-
ware, and stored procedures. See also Common Language Runtime (CLR).
backup device: A hardware unit that hosts the media for your database back-
ups. You configure your backup to work with this object. These devices are
typically disk or tape drives. See also backup.
composite index: This index is made up of two or more columns. See also
column.
content: All information contained between the start and end tag of an XML
element. See also element; attribute.
element: Surrounded by a start and end tag, this XML-based information may
also include attributes and content. Elements may contain other nested, child
elements. See also attribute; content.
file backup: A type of backup relevant only when there are multiple filegroups.
See also filegroup.
filegroup: Collections of SQL Server 2005 Express data files. For performance
and administrative reasons, you can place user objects into their own, dedi-
cated filegroups. See also master data file (MDF); file backup.
first normal form: One of the three normal forms that make up relational
database guidelines, this rule states that a table should not have any repeating
fields. See also normalization; second normal form; third normal form.
full differential backup: Identical to a full backup, with one major difference:
A full differential backup archives only information that has changed since
the last full backup. This backup can be very handy if only small portions of
your database change on a regular basis; by running differential backups you
don’t need to incur the time and media costs of full backups. See also
backup; full backup.
full text catalog: The file system-based object that holds the contents of all
full-text indexes.
full-text search: The ability, present in SQL Server 2005 Express with
Advanced Services, to quickly and efficiently search large quantities of text-
based information.
These isolation levels interact with your application, allowing or denying visi-
bility to modified data depending on the setting. See also transactions.
368 Part VIII: Appendixes
log file: A file system–based, internal database construct that records data
and table modifications, and restores information to its previous state should
the application rollback a transaction.
logical design: The abstract design and structure of your relational database.
Focusing on the high-level objects, and their interrelationships, this design is
usually generated during the analysis phase of most projects. It then serves
as a guideline for creating the actual implementation of your SQL Server 2005
Express database. See also physical design.
master data file (MDF): SQL Server 2005 Express databases contain two
types of operating system files: MDF and log files. This class of file stores
data, and is dedicated to one-and-only-one database. See also log file;
filegroup.
See also partial differential backup; full backup; full differential backup.
partial differential backup: Archives only those portions of the last partial
backup that have changed since the partial backup was completed. See also
partial backup; full backup; full differential backup.
Appendix C: Glossary 369
permission: A privilege that you grant to a principle. After it’s authorized, the
principle may then interact with one or more securables. See also principal;
securable.
physical design: The actual tables, columns, indexes, and other data struc-
tures used to store information in a SQL Server 2005 Express database.
Development projects typically progress from a logical database design to a
physical database design. See also logical design.
principal: Any user or process that you can authorize to interact with your
SQL Server 2005 Express database. See also securable.
publication: A single unit containing one to many articles, available for repli-
cation to other database servers. See also replication.
recovery model: A preset plan used by SQL Server 2005 Express when
archiving and restoring information. See also backup; restore.
370 Part VIII: Appendixes
row: An individual entry from a given table. For example, a table may contain
details about thousands of customers; a specific customer’s data is in one
row. See also record.
second normal form: Data is said to be in the second normal form if it com-
plies with the first normal form, as well as having one or more columns in a
table that uniquely identify each row. See also first normal form; third
normal form.
securable: This represents any type of object that can be given its own secu-
rity setting. Some examples of securables include tables, views, and users.
See also principal.
table: These contain logical groupings of information about a given topic. For
example, if you’re interested in students and their grades, your application
would have at least two tables: One to track details about students, and one
to monitor their test scores. See also column.
third normal form: Table data that complies with both the first and second
normal forms, and also directly relates to each rows primary key. See also
first normal form; second normal form.
trigger: Stored in and managed by your database server, this software exe-
cutes when a certain event occurs. These events can range from information
creation or modification to structural changes to your database. After the
event occurs, the trigger executes, causing a predetermined set of actions to
take place. These actions can encompass data validation, alerts, warnings,
and other administrative operations. Triggers can invoke other triggers and
stored procedures. See also stored procedure.
372 Part VIII: Appendixes
unique index: Sometimes created explicitly by the user, and sometimes cre-
ated automatically by the database server, by guaranteeing one-and-only-one
value for a given table, this structure speeds access to information as well as
preserves data integrity. See also index.
view: A virtual grouping of one or more tables, often done to reduce complex-
ity while increasing security and reliability. An administrator defines the view,
which is then available for developers and users to access instead of working
with the underlying tables.
System Requirements
Make sure your computer meets the minimum system requirements listed. If
your computer doesn’t match most of these requirements, you may have
problems installing or running the contents of the CD:
If you need more information on the basics, check out PCs For Dummies, by
Dan Gookin; or any of the Windows For Dummies titles by Andy Rathbone (all
published by Wiley Publishing, Inc.).
You can use this database platform alone, or in combination with popular
development tools from Microsoft and other vendors. You can even use it as an
information repository for office productivity software such as Microsoft Excel,
PowerPoint, and other data analysis and business intelligence technologies.
Appendix D: About the CD-ROM 375
If You Have Problems (Of the CD Kind)
SQL Server 2005 Express installed for me with no problems. I’ve tested all the
scripts and application code. Alas, your computer may differ, and some pro-
grams may not install correctly or work properly for some reason.
The three most likely problems are that you don’t have administrative privi-
leges, don’t have enough memory (RAM) for the programs you want to use,
or you have other applications running that are affecting installation or run-
ning of a program. If you get error messages like Not enough memory or
Setup cannot continue, try one or more of these methods and then try
using the software again:
⻬ Turn off any antivirus software that you have on your computer.
Installers sometimes mimic virus activity and may make your computer
incorrectly believe that virus is infecting it.
⻬ Close all running programs. The more programs you’re running, the
less memory is available to other programs. Installers also typically
update files and programs. So if you keep other programs running,
installation may not work properly.
⻬ Add more RAM to your computer. This is, admittedly, a drastic and
somewhat expensive step. However, if you’re running any of the
Windows operating systems I listed earlier in this chapter, adding more
memory can really help the speed of your computer and allow more pro-
grams to run at the same time.
376 Part VIII: Appendixes
Index
assembly, 242, 365
•A• atomicity of transaction, 195
Access (Microsoft) attributes, XML, 96, 319, 365
accessing database using, 128 authentication mode, specifying, 30, 186
migrating from, 355–359 AUTO directive, 329
ACID test, 194–195 autogrowth feature, 61
actions triggered by events. See triggers automated server administration, 346
ad-hoc remote queries, enabling, 38 automatic performance tuning, 12
administration AVG() function, 141
automated, 346
features for, 13, 20–22, 58–60, 339
with SQL Server Management Studio
•B•
Express, 60, 67–68, 339 backup devices, 365
with SQLCMD, 59, 339 backups
third-party tools for, 60 best practices for, 206–207
administrators, 183 definition of, 365
Advanced Services edition, 263–267 exporting data as, 210
ALTER DATABASE command, 206 features for, 15
ALTER TABLE statement, 117–118 full backups, 207, 367
analysis services, 14, 57, 346 full differential backups, 207, 367
antivirus software, 375 limitations of, 346
application developers, 182 partial backups, 207, 368
application development platforms, 130 partial differential backups, 207, 368
application power users, 182 performing, 208–209
application users, 182 recovery models for, 15, 205–206, 369
applications replication for, 84
adding, effect on database size, 56 restoring, 15, 207, 210–212, 370
desktop, creating, 290–298 strategy for, 204–205
desktop, customizing, 298–300 bcp utility, 135–136, 210
desktop, debugging, 301 BEGIN TRANSACTION statement, 198, 202
desktop, packaging and shipping, 301–302 bigint data type, 94
error handling for, 256–257 binary data type, 94
features for, 19–20 bit data type, 94
performance of, 82, 342 blogs, 336
processes used by, controlling, 73 books. See publications (resources)
stability of, 252 Boolean searches, 139
Web, database for, 306–310 buffer cache, 203
Web, user interface for, 311–315 built-in functions, SQL, 140–141
Web, Web site for, 304–306 BULK INSERT statement, 134–136
archives. See backups bulkadmin server role, 180
articles, 86, 365 bulk-logged recovery model, 205–206
378 Microsoft SQL Server 2005 Express Edition For Dummies
stored procedures. See also functions creating, with Visual Basic 2005 Express,
advantages of, 216–217, 340–341 294–296
calling, 226 creating, with Visual Web Developer 2005
compared to functions, 219 Express, 309–310
definition of, 215, 370 definition of, 371
examples of, 217–218 deleting, 118–119
improving performance using, 82 deleting data from, 152–156
listing triggers using, 232–233 designing, 81, 97–98, 340
running from SQLCMD, 22 grouping with views, 161–165, 341, 372
security and, 217 inserting data in, 131–136
system stored procedures, 219–223 joining, in queries, 142–144
viewing in Object Explorer, 109 modifying, 116–118
when not to use, 218–219 modifying data in, 150–152
writing, in SQLCLR, 225–226 rows in, 370
writing, in Transact-SQL, 224–225 viewing in Object Explorer, 109
Structured Query Language (SQL), 2, 126, tags, XML, 319
371. See also SQLCMD utility; TCP/IP (Transmission Control Protocol/
Transact-SQL Internet Protocol), 39, 42, 371
subqueries, 145–146, 371 tempdb database, 33
subscribers, 87, 371 text data type, 94
subscriptions text files, migrating from, 360–361
configuring, 89–90 third normal form, 103–104, 371
definition of, 87, 371 threading, 242
limits on, 85–86 time, data types for, 94, 173–174
SUM() function, 140–141 timestamp data type, 94, 173–174
surface area, configuring, 36–39 tinyint data type, 94
syntax errors, 258 TLA (three-letter acronym), 241
sysadmin server role, 180 TOAD for SQL Server (Quest
sys.sql_modules table, 229 Software), 336
system administrators, 183 TOP extension, SQL, 154–155
system databases, 33, 108 tracing events, 72
system requirements trade-secret algorithms, 244
for CD, 373–374 transactional replication, 85, 87–90
for SQL Server 2005 Express, 24–26 transactions
system stored procedures, 219–223 ACID test for, 194–195
sys.trigger_events table, 229 checkpoints for, 196
sys.triggers table, 229 definition of, 202–203, 371
error handling and, 252
•T• isolation levels for, 196–198, 367
locks for, 196
tables. See also queries (searches) log cache for, 196
columns in, 97–98, 340, 365 reasons for, 201–202, 340
creating, methods for, 113–115 transaction log for, 196
creating, with SQL, 115–116 user configurations for, 73–74
creating, with SQL Server Management using, 198–199, 202
Studio Express, 63–64
Index 389
Transact-SQL. See also SQL (Structured untyped XML, 322
Query Language) UPDATE statement, 151–152
conditional logic in, 126 upgrading CPU, 79
definition of, 125–126, 371 upgrading memory, 345
error handling in, 126, 127 upgrading to SQL Server 2005. See also
features of, 126–127 migrating to SQL Server 2005 Express
variables in, 126 features for, 12
writing stored procedures or functions in, procedure for, 345–351
224–225 reasons for, 56–58
writing triggers in, 228 user groups, 335
XML data, working with, 167 user instances, 69, 72
transitive dependency, 103 user interface, creating, 296–298, 311–315
Transmission Control Protocol/Internet user-defined data types, 95
Protocol (TCP/IP), 39, 42, 371 users. See also logins; principals
triggers authorized, listing, 184–185
advantages of, 341 configuring, 68, 73–74
configuring, 72–73 creating, 187–189
definition of, 227–228, 229, 371 effect on performance, 342
deleting, 239 limiting number of connections by, 72
disabling, 237–238 mapping to Windows users, 68
enabling, 238 number of, database size and, 56
error handling and, 260 permissions for, 189–190, 190–191
improving performance using, 82 roles for, 68, 180–181
invoking, 237 securables for, setting, 68, 188–189
listing, 232–233 types of, 181–183
modifying, 238
scope of, 228
types of, 229–230 •V•
when to use, 231 value() method, 167, 326, 327
writing, 228, 233–236 varbinary data type, 95
troubleshooting varchar data type, 95
CD included with this book, 375–376 vertical partitioning, 105
data access problems, 339–340 views
data integrity problems, 340 creating, 163–165
database connection problems, 338–339 definition of, 161, 372
installation problems, 338 listing, 161–163
performance problems, 342 multiple table views, 164–165
TRUNCATE TABLE statement, 153 reasons to use, 341
truncation, user configurations for, 74 single table views, 163–164
TRY...CATCH block, 254–256 viewing in Object Explorer, 109
typed XML, 322 Virtual Interface Adapter (VIA), 39
virtual memory, adjusting, 80
•U• Visual Basic 2005 Express
connecting to existing database, 292–294
UNIQUE constraint, 120, 160 creating a database, 291–292
unique indexes, 372 creating a project, 290–291
uniqueidentifier data type, 95
390 Microsoft SQL Server 2005 Express Edition For Dummies
Available wherever books are sold. For more information or to order direct: U.S. customers visit www.dummies.com or call 1-877-762-2974.
U.K. customers visit www.wileyeurope.com or call 0800 243407. Canadian customers visit www.wiley.ca or call 1-800-567-4797.
SPORTS, FITNESS, PARENTING, RELIGION & SPIRITUALITY