Вы находитесь на странице: 1из 36

A Te c h n i c a l J o u r n a l f o r t h e S Q L S e r v e r C e n t r a l .

c o m a n d PA S S C o m m u n i t i e s
January/February 2005

Approaching In This Issue:


Best SQL Server 2005 7

Yukon Features for DBA’s


By Brian Knight

What’s New in SQL 11


Integration Services
By Allen Mitchell and Darren Green

Paging Result Sets 14


Using Server 2005’s
ROW_NUMBER
By Joseph Sack

SQL Server 2005 16


Name Resolutions -
Owners & Schemas
By Wendy Sue Williams

The Next Evolution 18


of Management Objects
By Steve Jones

SQL Server Metadata 20


By Anthony Bressi

Yukon Encryption 22
By K. Brian Kelley

PASS
Introducing Database 31
Mirroring
By Rick Heiges, PASS Director of Membership

Strengthening 34
European
Presence in 2005
By Professional Association for SQL Server
“ Ihasneed to know how my database
been accessed and modified.

With Entegra, I have


a complete picture of
who did what when! ”
®
Lumigent Entegra TM
sets a whole
new standard for data integrity. It’s the only
comprehensive data auditing solution focused at
the data level — giving you greater visibility into
your database activity. It monitors data access
modifications, and changes in schema and
permissions — it even tells you who’s viewed
what data. Entegra gives you the insight you
need without the hassle of re-coding application
logic or developing and maintaining triggers.
With end-to-end management, collection, and
reporting capabilities, you’ll have a complete
picture of who did what when to your data.

With Entegra:

• Monitor and audit your database activity


without triggers or application modifications
• Automatically capture, store, and report
changes in permissions, schema, and
data modifications
• Audit SELECT statements to know who’s FREE White Paper
viewed your data
• Store all data in a single, centrally- Learn how you can benefit from monitoring
managed repository and auditing database activity without the
use of triggers and application modifications.
Download your free white paper today at
www.lumigent.com/go/sqlknow.

Copyright © 2004 Lumigent Technologies, Inc. All rights reserved. Lumigent, Entegra and the Lumigent Logo are trademarks or registered trademarks of Lumigent Technologies, Inc.
Editorial

Approaching Yukon
A publication of The Central Publishing Group It’s now known as SQL Server 2005, though I
Managing Editor have to admit that I like Yukon much better. How
Susan Page interesting would it be if the code names were
the actual names of the products? Wishful
Technical Editors:
thinking, but I’d sure like to install SQL Server
Trey Johnson Mark McCorkindale
Randy Lee Anthony Virgil Yukon or SQL Server Shiloh or even SQL Server
Jeff Niblack Sean Lambert Sphinx rather than SQL Server 2000. It makes as
Typesetting, Layout and Printing:
much sense as the current naming. 2000 is v8,
Paramount Printing 2005 is v9?!??!!
Copy Editor This issue marks a change for SQL Server
Susan Page
Standard. Not only is this the start of our second
Advertising: year, but we’ve also made a change in the way
Advertising@sqlserverstandard.com
we build the magazine. When we started this last
Subscription & Address Change:
year, we looked at lots of layout ideas and
http://www.sqlserverstandard.com
designs. Since artistic ability isn’t really one of
Feedback:
editor@sqlserverstandard.com
our talents, we let someone else choose the look,
and then scrambled to get content for the feel. A
Coyright:
year of scrambling has left us looking like most
Unless otherwise noted, all programming code and articles
in this issue are the exclusive copyright of the Central
other magazines. A theme and an article or two
Publishing Group. Permission to photocopy for internal to support it, but mostly we’re filling space with
personal use is granted to the purchaser of this magazine. whatever interesting articles we can find. And
SQL Server Standard is an independant publication and is we’re trying to put something in each magazine
not affiliated with Microsoft Corporation, Microsoft for everyone.
Corporation is not responsible in any way for the editorial
policy or other contents of this publication. SQL Server, No longer. This year our goal, and an ambitious
ADO.NET, Windows, Windows NT, Windows 2000 and Visual one at that, is to dedicate each magazine to a
Studio are registered trademarks of Microsoft Corporation.
Rather than put a trademark symbol in each occurance of
theme and try to fill it with articles that support
other trademarked name, we state that we are using the that theme. As you might have guessed, January
names only in an editorial fashion with no intent of is devoted to Yukon and we have 6 articles, all on
infringement of the trademark. Although all reasonable that very topic to get you ready for the next
attempts are made to ensure accuracy, the publisher does release of SQL Server. And we’ve got similar
not assume any liability for errors or omissions anywhere in
this publication. It is the reader’s responsibility to ensure that
plans for the remainder of the year; each issue
the procedures are acceptable in the reader’s environment devoted to a topic: replication, performance, just
and that proper backup is created before implementing any to name a few.
procedures.
Hopefully you’ll enjoy it and find some value in it.
SQLServerCentral.com Staff:
Brian Knight, President We’re trying something new here at
Steve Jones, Chief Operating Officer SQLServerCentral.com and we’d love to have
Andy Warren, Chief Technology Officer some feedback on whether this meets your
needs, if you like it, any improvements you’d like
to see, or even those topics that interest you.
Design Layout and Printing by: Send a note to articles@sqlservercentral.com
and we’ll take a look and see what we can do.
- Steve Jones

904 448 1700 • 5299 St. Augustine Road, Jacksonville, FL • www.printparamount.com

JANUARY/ FEBRUARY, 2005


3
SQLsuite
THE PROFESSIONAL DBA’S CHOICE

tools for
your SQL Server Enterprise

SQL diagnostic manager


Real-time performance monitoring and diagnostics

SQLsafe
Enterprise-scale backup and recovery

SQLconfig
Change and configuration management

SQLtool
Powerful Web-based administration

SQLschedule
Enterprise-class job management

DTx
Easy-to-use data transformation and migration

For free trials visit www.idera.com


or call toll free 877.GO.IDERA
Table of Contents

A Te c h n i c a l J o u r n a l f o r t h e S Q L S e r v e r C e n t r a l . c o m a n d P A S S C o m m u n i t i e s

Best SQL Server 2005 Features for DBA’s 7


By Brian Knight

What’s New in SQL Integration Services 11


By Allen Mitchell and Darren Green

Paging Result Sets 14


Using Server 2005’s ROW_NUMBER
By Joseph Sack

SQL Server 2005 Name Resolutions - Owners & Schema 16


By Wendy Sue Williams

The Next Evolution of Management Objects 18


By Steve Jones

SQL Server Metadata 20


By Anthony Bressi

Yukon Encryption 22
By K. Brian Kelley

PASS
Introducing Database Mirroring 31
By Rick Heiges, PASS Director of Membership

Strengthening European Presence in 2005 34


By Professional Association for SQL Server

JANUARY/ FEBRUARY, 2005


Best SQL Server 2005 Features
for DBA’s By Brian Knight

“ There are more new features than I can ever


mention in this article, so I’ll touch on the high points.

You’ve probably already read lots about the SQL Your central tool now for management is the
Server 2005’s programmability and business intelligence Microsoft SQL Server Management Studio (seen in
enhancements, but what’s in it for the DBA? In this article, Figure 2). This tool is best compared with Enterprise
I’ll show you a few of my favorite features in SQL Server Manager. Instead of using the MMC console that you
2005. As you can imagine from reading some of the other would see in Enterprise Manager though, Microsoft has
Yukon articles in this issue, the trainers are licking their chosen a new path with a light version of Visual Studio
chops right now with anticipation of training the new crop 2005. The environment is built for enterprise management
of SQL Server users since there will be such a learning of hundreds of databases on a single server. For example,
curve in this release of SQL Server. There are more new when you expand the Databases tree, the tool begins to
features than I can ever mention in this article, so I’ll touch query for the database list and you can move on to the
on the high points. I’ll dive deeper into each feature on next task while it finishes the retrieval. Traditionally in SQL
SQLServerCentral.com over the next few months. Server 2000, you would have to wait while the database
or table list completed retrieving. In large environments,
New Management Environment
this could take 5-10 minutes.
Everything you know about the management tools in
SQL Server 2000 can be thrown out in SQL Server 2005,
with the exception of Profiler (who has also received some
enhancements as well). One of the new minor tool
additions is SQL Computer Manager. This tool replaces
much of what you would previously do in the Services
applet in Control Panel and adds quite a bit more
functionality. For example, you can start and stop the
services and change the password that is used to start
them much like the Services applet. You can also change
the port that SQL Server is listening or create aliases here
much like the Client and Server Network Configuration
programs in SQL Server 2000. Essentially, it combines all
the old service and network management applications
Figure 2: Microsoft SQL Server Management Studio
into one central MMC interface.
Everything Online
One of the most important features for an active
database environment is keeping everything online. While
SQL Server 2000 goes a long way to doing this, you
cannot do a number of things online. SQL Server 2005
fixes that immensely by allowing you to restore databases
while users are still connected to the database, querying.
This option is available in Enterprise, Developer and
Figure 1: SQL Computer Manager Evaluation editions of SQL Server for file and file group

JANUARY/ FEBRUARY, 2005


7
restores. With this feature only the data that is being There are some key differences between database
restored at that point-in-time is unavailable. The rest of mirroring and log shipping. Think of database mirroring as
the database is still accessible. This same type of feature an enhanced version of log shipping. In database
is also available for index rebuild operations and DBCC mirroring, if the principal site fails for whatever reason, the
commands. You will be able to rebuild a clustered index mirror will immediately (within a second or two) take over
while making active modifications to the data. ownership of the data and bring itself out of perpetual
recovery mode. Thanks to a new revision in MDAC,
Data Partitioning
clients will then begin to redirect themselves over to the
A common problem for DBA’s has been handling mirrored site automatically. Traditional log shipping
large tables. A large table can be challenging to insert required that you build this functionality into your
large amounts of data into or delete chunks of data. Let’s application and the failover was manual. Another
take a real-world example that most of us have difference between this and log shipping is that you
encountered in an environment that happens to come in cannot use the mirrored database for reporting as in log
the AdventureWorks database. shipping since it’s in recovery mode. There are some
You are a DBA who has a large transaction table workarounds for this that you can use by using snapshots.
called TransactionHistory and you archive transactions A great benefit to database mirroring is that you can
older than 2 years off to the TransactionHistoryArchive have geographically dispersed sites in a partnership. For
table once a month. Since you have 40 million records in example, my home office in Jacksonville can send the
the TransactionHistory table, it takes hours to copy the data to our disaster recovery site in Chicago and all of my
millions of records from table to table, even with the applications will automatically move over as soon as I take
clustered index on TransactionDate. This would be a the database down for maintenance. One negative about
perfect scenario for data partitioning. database mirror or log shipping is you will double your
You would have partitions on both the space requirements since you are mirroring a database to
TransactionHistory and TransactionHistoryArchive tables a different server.
on the TransactionDate column by month. Before you can
move the data using partitions, you must ensure two core
Snapshots
things: the schema between the two tables must match A database snapshot as its name implies is a
and there must be an empty partition on the target table snapshot of the database as a given point in time. A
to receive the data. Once you’re ready, you would issue a snapshot is read-only and static. Once a snapshot is
series of ALTER TABLE commands to migrate the data created data page changes that have occurred to the
between the two tables. The thing that makes this run so database since the change are tracked. Essentially, a
fast (instantaneously) is that you’re not moving the change log that contains the data page that was changed
physical data pages or rows. Instead, you’re only pointing and what the original data page looked like is kept in the
the meta data of the records for that date range to be snapshot. Because of this, initially, the snapshot is quite
owned by the other table. small, containing very little data. Over time, though, this
can cause a space problem for a server as more and more
Database Mirroring and Snapshots data is updated in the database’s tables.
Database mirroring is one of the most anticipated To create a snapshot in T-SQL, you can use the
high-availability features in SQL Server 2005 and is
CREATE DATABASE syntax as shown below:
covered in much more detail later in this issue of SQL
Server Standard. It is much like log shipping, where the CREATE DATABASE AdventureWorks_DecReport ON
transaction log is restored to a secondary site
( NAME = AdventureWorks_Data, FILENAME =
automatically. In database mirroring, the secondary site
(called a mirror) receives the transaction log backups ‘C:\Program Files\Microsoft SQL
from the primary site (called the principal). There is also a Server\MSSQL.1\MSSQL\Data\AdventureWorks_DecRepo
third server called the witness that monitors the availability rt.ss’ )
of each server in the relationship. Optionally the witness
can be consolidated onto the primary or secondary server AS SNAPSHOT OF AdventureWorks;
but it’s not recommended since it creates a single point of
failure. GO

8
After the snapshot is created, you can connect to it as then I could customize the DTS package to do just that.
if it were a physical database. After you’re connected, you You can also have the package call another SQL Server
can query it in the same manner that you do a physical job after the maintenance is complete or execute T-SQL.
database with the exception of not being able to do You can reorder the way your maintenance workflow
UPDATE, INSERT or DELETE statements. Any user who occurs also.
has RESTORE permission can also use a snapshot as a
source for the restoration.
RESTORE DATABASE database FROM DATABASE_SNAPSHOT
= AdventureWorks_DecReport
To delete the snapshot, you must only issue a
standard DROP DATABASE command and specify the
snapshot name as shown here:
DROP DATABASE AdventureWorks_DecReport

Maintenance Plans
Maintenance plans in SQL Server 7.0 and 2000 were
a blessing for DBA’s who wanted the basic maintenance
to be performed on a regular basis for your server.
Maintenance plans to me always seem like a great feature
but lacked in some functionality to make it my dream tool. Figure 4: Maintenance plan as a dts package.=
For example, you couldn’t customize a maintenance plan
to meet your own standards. Maintenance plans in SQL Security Enhancements
Server 2005 have gone the extra mile. When you start, it This broad category represents a lot of the work that
asks you what type of tasks you’ll want to accomplish in was done in SQL Server 2005 for the administrator. The
your maintenance plan (shown in Figure 3). world is a lot different place than it was 5 years ago, and
we must dead-bolt the database door locks to make sure
hackers stay out and that we’re compliant with new
regulations like Sarbanes-Oxley. For more information on
the security enhancements in SQL Server 2005, see Brian
Kelley’s article “First Look at Yukon Security” in the
January 2004 issue of SQL Server Standard. Here are the
highlights, though.
An important change that will help SQL Server
comply with new government regulations is the ability for
the DBA to force the user to change his password every
so many days based on a server policy. A user can
potentially get locked out of the SQL Server if he does not
change his password within the set amount of days.
A constant nagging frustration for DBA’s is how SQL
Server 2000 binds users to schemas. In SQL Server 2000,
if your user bknight creates an object called History, the
table may be called bknight.History. In this case though,
Figure 3: Maintenance plan configuration.= you cannot remove the bknight user until you change the
After you answer a series of questions, it will create object owner. By doing this, though, you reset the
the maintenance plan as a DTS package (shown in Figure permissions on the object, which creates a DBA
4). The nice thing about having the maintenance plan headache.
created as a DTS package is it allows for customization. In SQL Server 2005, schemas can be unbound for the
For example, if I’d like to be notified if a backup fails but I user. You can create a schema, for example, called
don’t necessarily care if the update statistics didn’t create,

JANUARY/ FEBRUARY, 2005


9
Accounting and then a table that is owned
by the schema may be called
Accounting.History. The nice thing about
this implementation is that a database role
can own the schema so you’re not tied to a
given user. Finally, you’ll now find that
system objects are a member of the sys
schema.
SQL Profiler
and Database Tuning Advisor
Index Tuning Wizard has a new name
and new functionality. It is now called the
Database Tuning Advisor (DTA) and now
has the ability to give index table partition
recommendations. It’s also highly
configurable to give the DBA a more
control of the recommendations to make Figure 5: The new Profiler event selection process.
sure it doesn’t waste your time.
When you first open Profiler, you may think that Conclusion
nothing has changed. You quickly realize how much If you haven’t done so already, make sure you
better it is. When creating a new trace, you’re given a update your SQL Server Beta 2 install to be the
matrix of events and columns that you can choose latest Community Technology Preview (CTP). As I
between. SQL Server 2000 would let you choose a write this, the latest release was in December of
column for an event that was not a match. For example, 2004. There are significant features that are
the Audit Logout event has no TextData. In SQL Server cleaned up in each preview release. By Beta 3, the
2005, you can’t make that mistake as you can see in features will begin to be locked down and will be
Figure 5. much cleaner. The latest release is much faster
and more bug-free than previous betas of SQL
My favorite feature in Profiler now is the ability to
Server 2005.
tie Profiler to System Monitor results. In other
words, you can select a line in Profiler and
potentially see what that query did to your CPU
and memory of the server visually on the same
Brian Knight is a SQL Server MVP and MCDBA. He is the
screen. You can now trace events in Analysis
co-founder of SQLServerCentral.com and works at Allstate
Services and output the results of a trace to XML (more of a title to co. name and your title?) as the database
for portability. Finally, you can also aggregate your manager. Brian is the author of several books and can be
trace on given keys instead of having to export the reached at bknight@sqlservercentral.com.
data into SQL Server to perform that function.

10
What’s New in SQL Server
Integration Services? By Allan Mitchell/Darren Green

“ It will quickly become apparent that IS is not


just an extension of DTS, but a complete and
total rewrite from the ground upwards.

Introduction empty package within the new package designer. One of
Microsoft SQL Server Data Transformation Services the most important and dramatic changes in the way we
(DTS) made its debut appearance with the release of build packages becomes apparent from the tabs at the top
SQL Server 7.0, and gained even more functionality with of the design sheet, Control Flow and Data Flow, which
the release of SQL Server 2000, but with SQL Server provide two distinct design surfaces. (See Control Flow &
2005 we have SQL Server Integration Services (IS) Data Flow tabs at the top of the central design window in
instead. It will quickly become apparent that IS is not just Figure 1.) Control Flow hosts tasks and related workflow
an extension to DTS, but a complete and total rewrite structures, including precedence constraints and
from the ground upwards, and this no doubt played an containers. The Data Flow Task, also known as the
important part in Microsoft’s decision to select a new pipeline, is where the product really begins to show its
name for the functionality. The depth of the changes will strength. The focus is on true Extract, Transform & Load
become apparent as we try to illustrate some of the new (ETL) through a single high performance pass over the
features and functionality, but also the paradigm change, data, as opposed to the many systems currently
requiring not only changes in our practical implemented more as ELT. If nothing else does, the
implementations but also our mindsets for designing richness of the pipeline will clearly indicate Microsoft’s
solutions in IS compared to DTS. commitment to making IS an enterprise class ETL product.
One of the first changes you will notice across SQL
Server 2005 is the new toolset, and so with the demise of
Enterprise Manager, the Business Intelligence
Development Studio (BIDS) is the new home for the IS
development environment. (Figure 1) The Visual Studio
style environment by its very nature offers several new
features to help develop and manage our packages,
including solution and project-based development,
integration with source control systems such as Microsoft
Visual SourceSafe, and interactive debugging of package
execution. Highlights of debugging include the ability to
set breakpoints at various stages of task execution and
Watch functionality allowing you to view the values of
variables at run-time. Whilst the concept of global
variables is still available, the term “global” is no longer Figure 1: the BIDS Environment
always accurate as variables can now be scoped to a
specific container. Containers, themselves another new Data Flow
concept, provide structure and base functionality for For each Data Flow task in a package there is a
almost all IS objects, from packages through to tasks. separate work surface accessed through the Data Flow
Once you have opened the BIDS and started a new tab. You can perform a simple transfer of data from a
Data Transformation Project, you will be presented with an single source to a single destination, or more advanced

JANUARY/ FEBRUARY, 2005


11
flows, covering multiple sources and destinations, and perform the extra processing when needed to maximize
merge or split the data flow paths between these performance.
multiple connection adapters, transforming the data
Expressions in Workflow
along the way.
The connection objects or connection managers as Workflow very simply is the “how and why” of how we
they are now called are held in the separate Connections get from one task to another in our package. In DTS we
window, but are consumed by tasks and source or have very rudimentary functionality here. For example, if
destination adapters alike. you want to execute a task based on the result of one of
n upstream components that are joined by workflow
The transformations themselves are now easily
constraints to your task this takes a lot of “glue” code,
reusable components that are dropped on to the design
since DTS constraints must all be satisfied. Whilst you can
sheet in a similar manner to tasks, albeit on the Data Flow
improve on basic constraints by using Workflow Scripts,
design surface as opposed to the Control Flow. An
these are not always easy to write and are hidden away
example of a new transformation is the Derived Column
such that they can easily be forgotten and making
component, which will replace much of the custom
maintenance difficult. In IS the level of control you get is
ActiveX script used previously, and instead relies on the
quite extensive and presented in a friendlier and more
new expression syntax implemented throughout IS. Whilst
structured manner. Below is a very short but “thirst
this is initially a learning curve as the language is neither
quenching” list of these new features:
T-SQL nor an existing scripting language, it emphasises
the more structured nature of the product, and perhaps • Constraint
most importantly it was designed for performance. The • Expression
language itself is based on C, and covers most of the • Expression OR Constraint
simple functions you may have used previously. If this • Expression AND Constraint
structured approach is too restrictive there is still the
Where we have multiple constraints going to the
highly flexible Script Component, which brings the power
same task we can choose further from:
of VB.Net into your transformation without going as far as
writing a full custom transformation component. • Logical AND (All constraints must evaluate to true)
There are many other new components available such • Logical OR (Any of the constraints must evaluate to
as the ground breaking Fuzzy Lookup or Term Lookup true)
components which bring true language independent
fuzzy logic and text mining capabilities respectively, right
to the heart of your ETL processing.
One of the most difficult areas of ETL development
and management is around what to do when it goes
wrong. The new logging infrastructure is covered in more
detail below, but from a Data Flow perspective the most
significant advance is the error output. Most components,
source and destination adapters as well as
transformations, implement the error output. These
components allow you to route any rows that fail to
process correctly to that component’s error output path.
This immediately allows you to see which rows caused the
problem, an often asked question today. The simplest Figure 2
thing you can do would be to write the failed rows to a file
A simple article illustrating one of the last points is
for closer examination later, but perhaps more useful
available here Introduction To Expressions On A Workflow.
would be for the data flow to have some additional
components that tried to fix the problem and then merge Property Expressions
the now clean rows back into the main flow. Whilst you Do you remember the good old days, when if we
could code defensively, if the failure rate is only a handful wanted to set the connection string of a text file to a
of rows out of several million, you would only want to dynamic value at execution time in our package, we had

12
to add a lot of glue code? (How can I change the filename
for a text file connection). Well, a lot of those needs are
gone. Now we have a truly amazing piece of functionality
that you can make as expressive as you want or as simple
as you want. Property Expressions can be placed on a
container so this means you can place them on objects
such as packages, tasks, Foreach Loop enumerators, For
Loop enumerators, Sequence containers, event handlers,
connection managers, and log providers to name but a
few. So what do they do? Well, they evaluate an
expression at runtime and substitute the expression for
the value to which it is mapped. The following image
shows how to find property expressions on a Text File
connection manager.

Figure 3 Figure 4
Once you have The good thing about the dialog is that we can click
selected the expressions on the ellipses button to the side of the expression text
tab you are offered the box and we are offered the chance to build our
chance to choose the expression using an editor. The language used is pretty
property you wish to set intuitive if you have spent anytime using IS and
and the value to which you expressions in other parts of the product. Let’s have a
wish to set it. look, then, at a couple of examples. The first example
shows us using the expression syntax to derive a value.
The second expressions shows us using a system variable
Control Flow Vs Data Flow value to use in our expression.
The introduction of the distinct Control Flow and Data “c:\\MyLoadFile_” +
Flow design surfaces is a striking and potentially confusing (DT_WSTR,4)DATEPART(“Year”,Getdate()) +
change for existing DTS users. The key point to remember (DT_WSTR,2)DATEPART(“Month”,Getdate()) +
is that the Control Flow hosts tasks. To help illustrate this, (DT_WSTR,2)DATEPART(“Day”,Getdate()) + “.txt”
here is a sample of tasks, some of which will already be
“c:\\MyLoadFile_” + @[System::MachineName] +
familiar to DTS users. “.txt”
• Bulk Insert Task • File System Task
We have tried to give you a very brief overview of
• Data Flow Task • Send Mail Task some of the conceptual changes as well as the practical
• Execute Package Task • WMI Event Task ones that we think will make your ETL processes
• Execute SQL Task • XML Task
considerably easier. If you can relate to some of the
improvements described above, then there are probably
another ten that we didn’t have space for this time round.
The Data Flow task is the replacement for the old Data
This article is based on SQL Server 2005 Beta 2 and Beta
Pump Task. However, that is where the similarity ends.
3 (Yukon).
Inside the Data Flow you can place sources and
destinations, collectively called adapters. You can then
manipulate the flow of the data between adapters by
Allan and Darren are both Microsoft SQL Server MVPs,
using transformations. To try and illustrate what you can specialising in Data Transformation Services and now
do in between here is a small selection of the embracing SQL Server Integration Services.
transformations available.
They run a successful consultancy, Konesans Ltd, providing
• Aggregate • Fuzzy Lookup support and design expertise to a variety of clients in a
• Conditional Split • Merge Join number of countries as well as providing community
• Data Mining Query • Pivot support through the Microsoft newsgroups and the popular
• Derived Column • Union All SQLDTS.com and SQLIS.com websites.

13
JANUARY/ FEBRUARY, 2005
Paging Result Sets Using
SQL Server 2005’s ROW_NUMBER By Joseph Sack

“ After years of creative workarounds and code bloat,


Microsoft has finally given us a ROWNUM equivalent,
the ROW-NUMBER function, introduced in SQL Server2005

Have you ever needed to return a row number END



column in your query result set? Or how about writing a ELSE
BEGIN
stored procedure that pages through a result set,
SELECT @BeginRow = ((@Page-1) * @Size + 1),
returning data in 10 row blocks? @EndRow = ((@Page-1) * @Size) + @Size
If you work with Oracle, then you already have a built- END
in solution, the ROWNUM function. And now, after years DECLARE @Stores TABLE
of creative workarounds and code bloat, Microsoft has (Name nvarchar(50) NOT NULL,
finally given us a ROWNUM equivalent, the ContactType nvarchar(50) NOT NULL,
ROW_NUMBER function, introduced in SQL Server RowNum int IDENTITY(1,1))
2005. INSERT @Stores
(Name, ContactType)
I’ve been waiting for this function for some time now. SELECT Name, ContactType
My job often involves writing stored procedures that FROM Sales.vStore
return data to website search applications. The web ORDER BY Name
pages don’t show the entire query result set on a single SELECT Name,
page, but instead present results in smaller, ordered, ContactType,
paged chunks. One technique for doing this in SQL RowNum
Server 2000 was as follows: FROM @Stores
WHERE RowNum BETWEEN @BeginRow AND @EndRow;
1. Create a temporary table or temporary table GO
variable with an IDENTITY column. The To display the first 10 rows of the first page of your website
IDENTITY column serves as a row number. search results, you would execute the following:
2. Populate the table with an ordered result set.
3. Query the table using the IDENTITY column,
EXEC Sales.uspRetrieveStores_OLDStyle 1, 10
qualifying which rows I wish to see.
To display the second page of rows, rows 11 through
The following procedure demonstrates the SQL Server 2000 20, you would execute:
technique of paging through the Sales.vStore view (available
in the AdventureWorks database in SQL Server 2005, Beta EXEC Sales.uspRetrieveStores_OLDStyle 2, 10
2). It takes two parameters, @Page and @Size, which is Now in SQL Server 2005, ROW_NUMBER (syntax
used to determine which rows from the result set should be
below) allows you to query an ordered result set, as well
retrieved:
as qualify which rows are returned, all without creating an
GO explicitly populated table:
CREATE PROCEDURE Sales.uspRetrieveStores_OLDStyle
@Page int, ROW_NUMBER ( ) OVER ( [ < partition_by_clause > ] <
@Size int order_by_clause> )
AS Before I review the stored procedure equivalent, we’ll
DECLARE @BeginRow int first review the various behaviors of the ROW_NUMBER
DECLARE @EndRow int function. In my first example of using ROW_NUMBER,
IF @Page = 1 the query returns the name, contact type, and row
BEGIN number for stores in the AdventureWorks database.
SELECT @BeginRow = 1, @EndRow = @Size
14
SELECT Name, ContactType, Row_Number() WITH CTE_Stores AS
OVER (ORDER BY Name) ‘RowNum’ (SELECT Name, ContactType, Row_Number()
OVER (ORDER BY Name) ‘RowNum’
FROM Sales.vStore FROM Sales.vStore)
Notice the ORDER BY clause is embedded within the SELECT Name,
ContactType,
syntax of the function, ordering the results by the “name”
RowNum
column. This ORDER BY is a required clause and is used FROM CTE_Stores
to determine the order in which rows appear. The column WHERE RowNum BETWEEN @BeginRow AND @EndRow;
you ORDER BY doesn’t, however, effect the sequential GO
numbering if you have a redundant field.
After compiling the stored procedure, you can view
For example, this next query orders by name, but for example, the second page of results:
qualifies a store that appears twice in the result set. Even
EXEC Sales.uspRetrieveStores 2, 10
though the name ‘Advanced Bike Components’ is
duplicate, you’ll see that the row number still increments I threw in something we haven’t discussed yet: the
from 1 to 2. Common Table Expression (CTE). A CTE is a temporary
SELECT Name, ContactType, Row_Number() named result set which can be used within the execution
OVER (ORDER BY Name) ‘RowNum’ scope of a single SELECT, INSERT, UPDATE, or DELETE
query. We use a CTE because we cannot use the
FROM Sales.vStore
ROW_NUMBER() function directly in the WHERE
WHERE Name = ‘Advanced Bike Components’
clause. Doing so would result in the following error:
ROW_NUMBER also has a partitioning feature that Msg 4108, Level 15, State 1, Line 2
allows you to restart the sequential row numbering based Windowed functions can only appear in the select or
on the grouping of a specific column (either the same order by clauses.
column as your ORDER BY or a different column). This
Instead, if you wish to designate which rows are
next example partitions data by ContactType. Numbering
returned, you must encapsulate your query within a CTE:
begins with “1” for the ContactType of “Order”, and
increments until row 272. It then restarts at “1” for the WITH CTE_Stores AS
(SELECT Name, ContactType, Row_Number()
ContactType of “Purchasing Agent” until row 246, when it
OVER (ORDER BY Name) ‘RowNum’
starts again at “1” for “Purchasing Manager”. FROM Sales.vStore)
SELECT Name, ContactType, Row_Number()
OVER (PARTITION BY ContactType ORDER BY Name) SELECT Name,
‘RowNum’ ContactType,
FROM Sales.vStore RowNum
FROM CTE_Stores
Now to the SQL Server 2005 equivalent of the paging WHERE RowNum BETWEEN 1 AND 10
procedure (we’ll review the elements of this procedure
afterwards): Another special consideration involves the CTE itself.
When using a CTE within a batch of statements, the
CREATE PROCEDURE Sales.uspRetrieveStores
@Page int,
statement proceeding the CTE definition must be followed
@Size int by a semicolon.
AS BEGIN
DECLARE @BeginRow int SELECT @BeginRow = ((@Page-1) * @Size + 1),
DECLARE @EndRow int @EndRow = ((@Page-1) * @Size) + @Size
IF @Page = 1 END;
BEGIN
SELECT @BeginRow = 1, @EndRow = @Size What about performance considerations? Until SQL
END Server 2005 RTM is released, we should avoid making
ELSE any concrete comparisons. However, I did compare
BEGIN (because I couldn’t resist) both versions of the procedure
SELECT @BeginRow = ((@Page-1) * @Size + 1),
using SET STATISTICS IO, and found that the I/O results
@EndRow = ((@Page-1) * @Size) + @Size
END; were almost identical. I’ll be interested to see how
ROW_NUMBER performs with much larger result sets

15
JANUARY/ FEBRUARY, 2005
and more complicated queries in Beta 3 and RTM.
Joseph Sack, MCDBA, is a SQL Server consultant based in
In the meantime, I’ve added ROW_NUMBER at the the Twin Cities. He is the author of SQL Server 200 Fast
top of my favorite improvement lists, and will definitely be Answers for DBA’s and Developers (Apress) and the
converting over my stored procedures to this new co-author of Beginning SQL Server 2000 DBA: Novice to
technique next year. Professional (Apress). He can be contacted via his website,
http://www.JoeSack.com.

SQL Server 2005


Name Resolutions - Owners & Schemas By Wendy Sue Williams

“ A Schema is simply a logical partition


of a database’s namespace.

In SQL Server 2000, all objects technically have a 4- In SQL Server 2005, ownership is separate from
part name (remember server.database.owner.object ?) So schema membership. Objects still have a 4-part name;
– ignoring the server.database components for the however, what was previously the “owner” part now
purposes of this article, and concentrating on reflects the object’s schema as shown in:
owner.object – let us look at the case of a developer server.database.schema.object. Qualifying your object
named Ana, who had the db_ddladmin role in a database. names becomes imperative when you use schemas. Let’s
Ana creates a procedure called uspAddCustomer take a look at what schemas are, and how they work.
with the command: A schema is simply a logical partition of a database’s
CREATE PROCEDURE uspAddCustomer AS... namespace. For example, if I have a Training database, I
may have objects related to the “people” aspect of my
This results in the creation of an object called: business: trainers, employees, students, companies,
Ana.uspAddCustomer contact information. I can logically group these objects
This can create security and/or name resolution together by creating them in the same schema.
problems if any objects referenced in the procedure (eg. Schemas work similarly to file storage on a hard disk. If I
the Customer table) are owned by dbo, or others. The create a file, for example “ServerDocumentation.doc”, I’ll
general recommendation in SQL Server 2000 is to have normally put it in a folder, let’s say “d:\articles”, making the
dbo own everything. Ownership can be changed using fully qualified name of the file includes the path:
the sp_changeobjectowner procedure, or – preferably - “d:\articles\ServerDocumentation.doc.” I am the owner,
Ana can create her procedure using: but ownership is not reflected in the path. I can secure the
folder by using NTFS permissions, which may allow
CREATE PROCEDURE dbo.uspAddCustomer AS....
certain individuals to view the documents in that folder,
As a result of the dbo’s usual ownership of all objects, and I can set permissions on an individual file within that
some developers and DBA’s take shortcuts writing code. folder, for when the folder level permissions are not
(Not you, of course. You’ve always followed the best appropriate.
practice of qualifying objects with owners!) Unless the Back on the SQL Server, your objects are going to be
application requires cross-database or cross-server like the files; your schema will be analogous to the path.
development, you may have some code that looks like: By creating a schema, with, for example:
CREATE TABLE mytable (col1 INT NOT NULL, col2 CREATE SCHEMA Person
INT NULL)
then placing objects in that schema, eg:
instead of:
CREATE TABLE Person.Address (PersonId INT
CREATE TABLE dbo.mytable (col1 INT NOT IDENTITY....
NULL, col2 INT NULL)

16
you’ll be able to grant access to all objects in that SELECT... FROM mytable ...
schema to a set of users. Eg: …without qualifying the table name.
GRANT EXECUTE,INSERT,DELETE,UPDATE,SELECT ON In SQL Server 2005, users can be assigned a default
SCHEMA::person TO [HR] schema, which will result in similar behavior. I assign the
You can also continue to set permissions at the table CustomerService members to the Person schema, and
or view level, as appropriate. ensure the CustomerService role has the SELECT
For example, in the Training database, I have two permission on that schema; as a result, the following
schemas: Person and Course. Within the Person schema, statement will run for that user without error:
I have the tables and views related to all “people”
SELECT first_name, last_name FROM Students
elements of my business, such as the Address table, the
Instructors table, and the Students table. These tables are However, when the CustomerService rep runs:
referred to as Person.Address, Person.Instructors, and
Person.Students. In the Course schema, I have SELECT course_name FROM CourseTitles
Course.Vendors, Course.CourseTitles and …the statement will fail. Why? For objects that are not
Course.Categories. ie: qualified, SQL Server 2005 first looks in the user’s default
schema (Does Person.CourseTitles exist?), then in the
Schema: Person Schema: Course “dbo” schema (Does dbo.CourseTitles exist?). In order
Tables: Address Tables: Vendors for my CustomerService users to access the CourseTitles
Instructors CourseTitles table, I’ll have to ensure that the table name is always
Students Categories qualified with its schema. ie:
A CustomerService user will need to look up course
SELECT course_name FROM Course.CourseTitles
information to give to students, so I can grant
CustomerService the SELECT permission to the Course In addition, as long as they reside in separate
schema. Eg: schemas, objects can have the same name. Just like I can
have two files on my hard drive named “README.TXT,”
GRANT SELECT ON SCHEMA::Course TO
so long as they are stored in different directories, I can
CustomerService
have two views called vMyView, as long as they are
This gives the CustomerService users permission to located in different schemas.
select on all three tables in that schema. The same role SQL Server 2005 does maintain a default “dbo”
will need to enroll new students, so they’ll need the schema. This will make porting existing applications to
INSERT permission on the Person.Students table, but SQL Server 2005 easier. However, as you work with new
only SELECT permission on the Person.Instructors table. applications from this point forward, you’ll see how
I’ll need to assign permissions on the tables directly, much valuable multiple schemas are. When you start using
as is done in SQL Server 2000. Eg: schemas other than the default, you’ll need to ensure the
use of objects’ two-part name (schema.object). Even if
GRANT INSERT ON Person.Students TO
you’re not using SQL Server 2005 yet - and even if you
CustomerService
never intend using schemas other than dbo - you might
GRANT SELECT ON Person.Instructors TO
CustomerService want to ensure your organization continues the best
practice of using those two part names in your code.
From the permissions aspect, schemas provide a
much needed method of simplifying the assignment of
permissions. Often, an application will have several related
Wendy Sue Williams has worked with SQL Server since
tables, to which users need the same level of permission.
1996 as a developer and a DBA. As a Microsoft Certified
However, using multiple schemas introduces object name Trainer, she currently trains for a CPLS in New Jersey, and
resolution issues. Let’s take a look at some code. recently presented a session at the SQL PASS 2004
In SQL Server 2000, if all objects were owned by dbo, conference in Orlando, FL.
my CustomerService users could execute:

JANUARY/ FEBRUARY, 2005


17
The Next Evolution
of Management Objects By Steve Jones

“ In SQL Server 2005, DMO has been


abandoned in favor of SMO.

SQL Server introduced the ability to are COM wrappers around the SMO classes to enable
programmatically manage the database server with the you to work in an unmanaged environment. The
introduction of Distributed Management Objects SQLSMO.dll file is located with the other assemblies and
(DMO) in SQL Server v6.0. The objects were a SQLSMO.tlb file exists that shows SQLSMO and its
substantially enhanced with each version, always lower objects in the object browser. This allows you to
maintaining backward compatibility. That become continue to work with SMO with VBScript or other
slightly confusing for developers when there were both legacy methods of COM programming. An example is
Server and Server2 objects and which methods could be shown in Figure 1.
used with which, but for the most part it worked. set oServer = CreateObject(“SQLSMO.Server”)
Now in SQL Server 2005, DMO has been oServer.Name = “MyServer”
abandoned in favor of SMO. SQL Server Management Wscript.Echo oServer.Name & “ “ &
Objects replace the distributed management objects as oServer.Information.VersionString
well as enhancing the functionality that is available when
programming applications to manipulate the server. Figure 1
While there are many changes to the management Two Classes
framework, the objects are still compatible with SQL
Server 7.0 and SQL Server 2000. There are two main categories of classes in SMO:
instance classes and utility classes. The instance classes
Everything is .NET are for the main objects that you are used to dealing
In keeping with the .NET enabling of all their with: the servers, databases, tables, views, stored
technologies, The SMO framework is implemented as a procedures, triggers, etc. These are in the familiar
.NET assembly. Just as you access the CLR from within hierarchy that you are used to: servers at the top,
SQL Server, you can include all DMO functionality in databases under them, tables under databases, etc. As
your .NET applications as well. The SMO namespace is with DMO, if there are multiple objects below a class
Microsoft/SqlServer.Smo and is located by default they are in a collection Otherwise, there is a single object
in the c:\program files\Microsoft SQL as the child.
Server\90\SDK\Assemblies folder. It is installed with the The utility classes exist to perform specific tasks.
client tools and requires the CLR runtime to be installed There is the Transfer class, the Backup and Restore
as well. classes, and the Scripter class.
One change from DMO is the replication objects are The transfer class contains the functionality that
not a part of the SMO framework. Instead, there are existed in the old DMO Transfer objects as well as a few
Replication Management Objects (RMO) that exist as enhancements. In SMO, however, the Transfer object
well. These enable you to manage all aspects of uses DTS to transfer data. The Backup and Restore class
replication, including the new parallel snapshot handles all the functionality you need to perform any
preparation, initialize a subscription from a backup, type of backup or restore task that you might need. Each
subscribing to data from other databases (like Oracle), Backup or Restore object represents the functionality
etc. A separate namespace exists for these objects that you might need to handle a specific task. An
(Microsoft.SqlServer.Replication) located in the example of this would be Figure 2, which shows how
Microsoft.SqlServer.Rmo.dll, another .NET assembly. you might perform a backup using VB.NET. The Scripter
Never fear, however; not everything is .NET. There class is used to handle scripting of objects. In DMO,

18
there was a method for various objects that allowed you now wrapped inside SMO to allow you to work directly
to script the current object. In 2005, there is a separate with them.
object that discovers the object and its dependencies, Capture Execution is one of the really interesting new
generates a list of objects that need to be scripted based features. Instead of having your application actually
on the discovery, and then the scripts are generated and submit statements to the server for execution, they can be
the resulting script returned. captured using SMO. Suppose you have a section of your
Dim oServer as Server code that creates a database or table, adds an index,
oServer = New Server populates data, for example, in an installation routine.
Dim oBackup as New Backup After testing, you can actually use SMO to capture this as
oBackup.Action = BackupActionType.Database a script for later execution, or on a separate server.
oBackup.BackupSetName = ‘Sample Backup’
oBackup.Database = ‘Northwind 3 Card Monty
Hopefully it doesn’t feel like that, but with the evolution
Figure 2. Backing up a Database using VB.NET
of the management objects, SMO has moved a number of
Optimized Instantiation things around. Books Online has a short list of what’s been
These are a couple of very fancy words that describe moved, though keep in mind that this is a Beta product. It’s
a performance enhancement that was implemented in entirely possible that more changes will be made in the
SMO. This means that as the programmer you can control RTM version. Look for a new article then :).
the level or amount of instantiation that occurs when you Conclusion
create an object. In DMO, all objects in a collection had to
While I normally don’t like wholesale changes
be instantiated, which could eat up lots of resources. Even
between versions, there are times that it’s warranted and
if you never intended to reference some of the objects,
this is one of them. With most everything else being
they would all be created. In SMO, you can partially
rewritten, the CLR added in, and more, SQL Server 2005
instantiate a collection, or even properties. It’s all up to
needed a change from DMO instead of adding Server3
you for each server. It’s not all good, however. Delaying
objects and more. I am glad that backwards functionality
the instantiation when you are planning on referencing
is retained, especially through SQL Server v7 when DMO
more objects or properties isn’t good for performance.
got very popular. It’s also great to see that COM
You’ll create lots of round trips to the server as you
functionality is still available, since I find quick and dirty
instantiate items.
VBScript command files to be an easy way to handle
There are 3 levels of instantiation that you can set. many administrative tasks.
Uninstantiated, nothing loaded, or full instantiated,
If you use DMO, I think you’ll be excited and find the
everything loaded (like DMO) are the most common
changes well worthwhile. It also appears the rewriting
levels that most programmers are familiar with. There’s
scripts from DMO to SMO should be fairly
also partial instantiation, which doesn’t load objects that
straightforward. In many cases, changing from a “2”
are not directly referenced. Once the object is referenced,
object to the single, i.e. Server2 to Server, should allow
then it is fully instantiated.
many of your scripts to work. I’m really looking forward to
New Features Beta 3 and RTM and hopefully much more detailed
The new features in SQL Server 2005 have documentation on the objects. As of now, many of them
corresponding items in SMO as well. HTTP and SOAP are not documented in Books Online. Look for an updated
requests can be handled by EndPoints objects. There are version of this article at SQLServerCentral.com once the
new objects inside the database object to work with Full product releases.
Text Search. The database object can work with snapshot
isolation and the new row level versioning feature. The
ability to spread tables and indexes across file groups has Steve Jones has been working with SQL Server since 1992 in
corresponding SMO objects. The new XML features, a variety of companies from small start-ups to large Fortune
including schema namespaces and indexes, are 500 companies. His primary area of expertise has been in
represented in SMO. Almost everything in the server that the Operations part of IT managing hundreds of databases.
He currently works full-time for SQLServerCentral.com
you can work with has a corresponding SMO
managing all aspects of their publishing business.
counterpart. In addition, the WMI provider objects are

JANUARY/ FEBRUARY, 2005


19
Accessing SQL Server Metadata By Anthony Bressi

“ Microsoft has been encouraging users


to use information_Schema views

In this article we will look at some of the methods FOR
that are available for accessing SQL Server metadata. Select sysobjects.name
The term ‘metadata’ in this article is primarily used to From sysobjects, sysprotects
describe database schema information, but most Where sysprotects.uid = 0
methods described below also allow you to gather AND xtype IN (‘X’,’P’)
AND sysobjects.id = sysprotects.id
statistical information, such as the number of rows in a
and protecttype <> 206 —can be revoked
table. We will primarily concentrate on options to use in
Order by name
persistent code, but will first start at the top. OPEN getRS
System Tables FETCH NEXT FROM getRS INTO @sysName
WHILE (@@FETCH_STATUS <> - 1)
This is probably the most common method that
BEGIN
DBA’s use to access metadata. I am a fan of this method IF (@@FETCH_STATUS <> -2)
because it’s quick, straight forward, and can be BEGIN
accessed using TSQL ‘Select’ statements. This is a good Set @tsql = ‘Revoke Exec On ‘ +
way to access metadata if you need a one-time look at @sysName + ‘ From public’
the data; i.e., your TSQL code will not persist past your Exec dbo.sp_executesql @tsql
current user session in Query Analyzer. But because the END
structure of system tables can change from release to FETCH NEXT FROM getRS INTO @sysName
release, it is <b>not</b> a recommended method to END
use within persistent code. If you are looking for a CLOSE getRS
simple TSQL way to access metadata for a project such DEALLOCATE getRS
as a software application or Internet application you will
INFORMATION_SCHEMA Views
be better off using INFORMATION_SCHEMA Views
instead, which is the next method we will look at. Retrieves database schema information using
familiar TSQL ‘Select’ constructs. The schema
—This example will revoke execute permissions information that is returned is based on the current
for the public group user’s permissions, in other words, <b>the results set
— on all of our stored procedures and extended will only contain data about database objects that you
stored procedures have access to</b>. INFORMATION_SCHEMA
enables you to retrieve metadata about Tables, Stored
— First we’ll use our sys tables to get the Procedures, Views, User Defined Functions, User
procedures that can be revoked, Defined Data Types, Databases, and more. Support for
— then loop through them and revoke them INFORMATION_SCHEMA began with SQL Server 7.0
and carried over to both 2000 and 2005. Because these
— PLEASE EXCUSE THE CURSOR, but in the example
views are system table-independent, Microsoft has been
it helps convey what
encouraging users to use INFORMATION_SCHEMA
— we are trying to do instead of basing code on system tables directly if
DECLARE @sysName varchar(128) possible (Note: some usage statistics that are available
Declare @tsql nvarchar(255) through the system tables are not available through
DECLARE getRS CURSOR INFORMATION_SCHEMA).

20
when you need to write persistent code for an application
—Get Information About Tables that interacts with SQL Server 7 or 2000 metadata. A
Select * from INFORMATION_SCHEMA.TABLES where sample SQLDMO example is available in the download.
TABLE_TYPE = ‘BASE TABLE’
— returns information for each table
—Return column info for each table SQL Management Objects (SMO)
Select * from INFORMATION_SCHEMA.TABLES st SMO replaces SQLDMO in SQL Server 2005. As
Inner Join INFORMATION_SCHEMA.COLUMNS sc noted above, SQLDMO is compatible with SQL Server
On st.TABLE_NAME = sc.TABLE_NAME 2005 but no new features have been added. SMO was
where TABLE_TYPE = ‘BASE TABLE’ modeled with SQLDMO in mind and Microsoft has called
it a “logical continuation” to SQLDMO and explicitly
—Get Information About Stored Procedures stated that they have incorporated objects similar to
Select * from INFORMATION_SCHEMA.Routines SQLDMO objects when possible. SMO makes 150 new
—returns stored procedures and functions classes available to users. SMO is backwards compatible
Select * from INFORMATION_SCHEMA.PARAMETERS with SQL Server 2000 and 7.0 and is 100% managed
—returns parameter information for user-defined code. Like SQLDMO, SMO is very easy to work with,
functions and stored procedures especially if you are using Visual Studio 2005.
Unfortunately, if you want the convenience of
—Get Information About Views
intellisense and IDE debugging while writing your SMO,
Select * from INFORMATION_SCHEMA.VIEWS
you will need to use Visual Studio 2005. The Visual Studio
—returns information for each view
2003 IDE will not let you add a reference to the SMO
Select * from
managed library through its GUI (you can still use a
INFORMATION_SCHEMA.VIEW_TABLE_USAGE
‘Using’ statement and include SMO but you lose
—returns each view and the tables it is using
intellisense and debugging from within the IDE). You can
SQL Server Distributed Management still build an SMO application with VS 2003 or even
notepad but you will need to make your references while
Objects (SQLDMO)
using the command line compiler (you will need to use
If you are building a software application that needs the compiler in your Framework 2.0 folder, not your
metadata from a SQL Server 7.0 or 2000 database, this is Framework 1.1 compiler).
the way to go. In fact, SQL Server 2000 Enterprise
Manager uses SQLDMO for most of its actions. Conclusion
Database information is exposed nicely through an easy There are many ways to access SQL Server
to use COM object library that can be used in any COM metadata, and we covered some of the most common
aware language such as Visual Basic, and can also be methods in this article. In addition, we exposed some
used in .Net - although it requires using Interop. While pros and cons of those methods which can hopefully
using SQLDMO you work in a hierarchical manner to help you make the decision of which tool to use for the
access the data that you want. For example, a Server task at hand. There are still yet other alternatives to use
contains a collection of databases, a database contains a to access SQL Server metadata, from ADO.Net to TSQL
collection of tables, and each table contains a collection of functions like DATABASEPROPERTY() (see Books
columns. Microsoft SQLDMO documentation states that Online -> meta data -> functions for more TSQL
applications using SQLDMO can perform all functions metadata functions). Ultimately, you may need to do
performed by SQL Server 2000 Enterprise Manager, some additional research to determine the right tool for
making this a powerful but easy-to-use way to access whatever your needs may be, but I hope that this article
metadata. SQLDMO is supported by SQL Server 7.0 and has helped you get on your way.
2000. It can be used with SQL Server 2005, but was not
updated to support 2005 specific features. SQLDMO is
bundled up in sqldmo.dll so you simply need to add a Anthony Bressi is owner of Agilist Technologies Inc. which
specializes in software for SQL Server Database
reference to this object in your application. If you installed Administrators and SQL Server developers. Mr. Bressi has
your SQL Server files to the default location on your PC, over 8 years of hands-on experience in the Microsoft SQL
the file should be located in: C:\Program Files\Microsoft Server development environment.
SQL Server\80\Tools\Binn. SQLDMO is an ideal choice

JANUARY/ FEBRUARY, 2005


21
Yukon Encryption By K. Brian Kelley

“ If this stays in the final product, It’ll be one more thing


DBA’s can check off their wish list.
One of the items I have heard asked for in SQL ”
encryption via a pass phrase, you’re on your own to
Server is the ability to do encryption at the database secure the pass phrase used. There are two new
level. In SQL Server 2000 the only option is to use a functions to support this mechanism of encryption:
third party product as there is no built-in capability to
EncryptByPassPhrase( <pass phrase>, <plain text>
take raw data and store it in encrypted form. With SQL )
Server 2005 Beta 2, however, Microsoft introduced
encryption at the database level. If this feature stays in DecryptByPassPhrase( <pass phrase>, <encrypted
text> )
the final product, it’ll be one more item SQL Server
DBAs can check off their wish lists. In this article I’ll look EncryptByPassPhrase() takes the pass phrase and
at why encryption at the database level is a much the text to be encrypted and produces a varbinary
requested feature, how it currently works in beta 2, result. DecryptbyPassPhrase() takes the pass phrase
some thoughts on how to use encryption, and a few and the encrypted text in varbinary format and
issues to consider when implementing encryption produces the original plain text. Here is an example of
within SQL Server. how both are used:
DECLARE @plain nvarchar(4000)
Passwords, Sensitive Data, and Things DECLARE @key nvarchar(4000)
Folks Shouldn’t See DECLARE @cipher varbinary(4000
DECLARE @decrypt nvarchar(4000)
SQL Server databases are used to store all sorts of
SET @plain = ‘This is a standard phrase in
things from library lists to passwords to IDs to credit plaintext’
card numbers. Auditors tend to cast a doubtful eye SET @key = ‘EncryptWithMe’
when bits of sensitive information like passwords, IDs, SET @cipher = EncryptByPassPhrase(@key, @plain)
and credit card numbers are available in plain view, SET @decrypt = DecryptByPassPhrase(@key,
@cipher)
even if it is only to the DBAs. Passwords tend be a big
problem because people have a tendency to re-use SELECT 1, ‘Plain:’, @plain UNION
SELECT 2, ‘Cipher: ‘, @cipher UNIO
passwords. Therefore, the password a user has for an SELECT 3, ‘Decrypt: ‘, @decrypt
application may very well be the same password the ORDER BY 1
user has for their Windows login. This is the type of
situation that causes the auditor’s pencil to start Building the Example
scribbling furiously. Other types of data we would do Going beyond the simple pass phrase encryption,
well to encrypt are things like salary figures in the HR we’ll need to build a few structures to demonstrate how
database. Day-to-day DBA operations wouldn’t need the various other options for encryption work. The build
the unencrypted data therefore there’s no reason to script creates two server principals (logins), TestUser1
display it. If the encryption capabilities in Beta 2 roll and TestUser2, a database, and a table we’ll use to store
forward into the released product, we’ll have a native our encrypted data. It also maps the two server
solution for both of these types of scenarios and many principals to two database principals (users), creates a
role, and makes the database principals members of the
more we’ve faced. Some of our options in the beta are role. Finally, the script gives direct SELECT and INSERT
extensive. Others are extremely quick and simple. access to the table via the role.
Encryption/Decryption By Pass Phrase CREATE LOGIN TestUser1 WITH PASSWORD =
‘MyPassword1!’
SQL Server 2005 Beta 2 provides the option of
CREATE LOGIN TestUser2 WITH PASSWORD =
encrypting using a pass phrase. This is the simplest of ‘MyPassword2!’
the encryption mechanisms and managing the pass
GO
phrase is left to the implementer. If you want to use

22
CREATE DATABASE Sandbox sys.symmetric_keys in the given database and looking for
GO a certificate with the name of
USE Sandbox ##MS_DatabaseMasterKey##. The version stored in
GO the master database allows SQL Server to open the
CREATE USER TestUser1 database master key automatically (part of allowing SQL
CREATE USER TestUser2 Server to completely handle key management). The
CREATE ROLE EncryptionUsers
EXEC sp_addrolemember EncryptionUsers, version stored in the database is then used for
TestUser1 encryption/decryption as necessary.
EXEC sp_addrolemember EncryptionUsers,
TestUser2
GO Creating:
CREATE TABLE dbo.ExampleTable (
To create the master key, the following syntax is used:
ExampleID int IDENTITY, CREATE MASTER KEY ENCRYPTION BY PASSWORD =
EncryptMethod varchar(50),
PlainData nvarchar(1000), ‘<password>’
CipherData varbinary(1000) )
GO For the examples, make sure you are in the Sandbox
database and enter something similar to the following:
GRANT SELECT, INSERT ON dbo.ExampleTable TO
EncryptionUsers CREATE MASTER KEY ENCRYPTION BY PASSWORD =
GO ‘OneRingToRuleThemAll!’
If we try to create a certificate or key without a
The Database Master Key database master key and we haven’t specified some
SQL Server 2005 Beta 2 comes with the ability to other means to encrypt (such as a password), SQL
completely manage the keys and provide for encryption Server will return an error. For example, the following
almost completely behind the scenes. It does so using code to create a certificate will fail:
what is called a database master key. To understand how CREATE CERTIFICATE ExampleCert
this comes into play, let’s take a step back and talk a bit
about the service master key and the encryption WITH SUBJECT = ‘This fails without the db
hierarchy. master key’
When you install SQL Server 2005, a symmetric key The error message received is the this:
(a single stream of bits which can be used to both Msg 15581, Level 16, State 1, Line 2
encrypt and decrypt data) is created for the SQL Server
service. This service master key is used to encrypt a Please create a master key in the database or
whole host of important and sensitive things such as open the master key in the session before
linked server passwords, connection stings, and mapped performing this operation.
account credentials. It is also used to encrypt any and all This goes back to who is handling key management.
database master keys. A query against the If we don’t specify an encryption mechanism, we are
sys.symmetric_keys view in the master database will telling SQL Server we want it to handle the management.
reveal the existence of this key (name of Therefore, the database master key is needed.
##MS_ServiceMasterKey##).
When a database master key is created, it too is a Dropping:
symmetric key. The purpose of a database master key is Eventually you may want to remove the database
to encrypt the certificates and keys within the database if master key. To do so, just execute the following in the
no other encryption mechanism is specified. If we want proper database.
SQL Server to handle key management, the database
DROP MASTER KEY
master key is a requirement.
By default, SQL Server will take the database master However, if any keys or certificates are encrypted
key, encrypt that with the service master key, and store with the database master key, you’ll receive an error like
this result within private structures in the master the following:
database. SQL Server takes the database master key Msg 15580, Level 16, State 1, Line 1
encrypted with the password you’ve specified (more on Cannot drop Master Key since Certificate
this shortly) and stores this in the given database the key ‘’NorthwindCert’’ is encrypted by that.
applies to. You can verify its existence by querying

JANUARY/ FEBRUARY, 2005


23
These must be removed before the master key can In the example I’ve given (after the key was
be dropped. regenerated), I’d open the database master key with the
following command:
Changing the Password:
OPEN MASTER KEY USING PASSWORD =
There may come a time where you’ll need to
‘MyPrecious...’
regenerate, or reset, the master key. The following
regenerates the master key with a new password: With the database master key opened, I can now
encrypt using the service master key. This doesn’t affect
ALTER MASTER KEY REGENERATE WITH PASSWORD =
the encrypted version by the password, but it does
‘<new password>’
create the encrypted version stored in the master
Continuing with the example, you can reset the database. Now SQL Server is back in control of key
Sanbox database master key by executing the following management, at least as far as any keys encrypted using
command in the database. the database master key.
ALTER MASTER KEY REGENERATE WITH PASSWORD = ALTER MASTER KEY ADD ENCRYPTION BY SERVICE
‘MyPrecious...’ MASTER KEY
You should only do this, however, when you have a
lot of spare cycles on your server or you have no other Is the Database Master Key Necessary?
choice. SQL Server will decrypt any keys encrypted with Strictly speaking, the database master key is not
the master key and then encrypts them again with the necessary. If you choose to encrypt using passwords (at
new master key. As a result, the whole process can be least initially), the database master key doesn’t have to
exist at all. This is actually an option if the level of trust
very resource intensive. Of course, if the master key has
been compromised, you may not wait until you have low doesn’t allow for the DBAs to control the keys. So long
CPU-usage on your SQL Server. as the keys within the database are encrypted using the
database master key, the DBA has potential access to all
Preparing to Detach the Database: of them. If, however, keys are encrypted using
If you need to detach the database, you’ll want to passwords, the DBA will have to know the password to
remove the encryption from the service master key. Keep unlock the key. An example I’ll use later has an
in mind that when the database master key was created asymmetric key encrypted with a password being used
you also specified a password. By removing the service to encrypt a symmetric key. Therefore, not every level has
master key encryption you can then detach the database to have a password, but the initial one does. However, if
without losing the database master key and any keys you you go down this road, then you’ll have to build your own
encrypted with it. Here’s how: mechanisms for key management. If you are concerned
about someone being able to see the password using
ALTER MASTER KEY DROP ENCRYPTION BY SERVICE Profiler or a server-side trace, the contents are masked.
MASTER KEY
Certificates
Steps After Attaching the Database: SQL Server 2005 Beta 2 has the ability to generate
Once you’ve re-attached the database, you’ll self-signed certificates. Certificates contain the public
probably want to re-encrypt with the service master key key of a person, device, or service. Data can be
for the new SQL Server. This will allow SQL Server to encrypted using the public key and only someone
open the database master key automatically and keeps possessing the private key can decrypt the data again.
key management totally within the control of SQL Server. Certificates also have a range for which each one is valid.
Normally SQL Server is able to open the database master Should a certificate be used before or after the validity
key. However, we removed the service master key period, most applications will throw an error. Should a
encryption before detaching the database, thereby certificate be used to represent something other than
breaking SQL Server’s ability to open the database what it was created for, most applications will again
master key automatically. Until SQL Server is able to throw an error. A good example is (at the time of this
encrypt the database master key using the service writing) if you try to navigate to the website
master key, you must first open the database master key https://www.dshield.org. You should get a message
manually. You can do so by specifying the password. revealing the certificate is actually for
OPEN MASTER KEY USING PASSWORD = ‘<password>’ https://secure.dshield.org. Here we see an example of
where the identity on the certificate doesn’t match the
24
name of the web site. WITH SUBJECT = ‘Example Certificate 2’,
The certificates created by SQL Server comply with ENCRYPTION_PASSWORD = ‘GandalfTheGrey’,
the X.509v3 certificate standard. In addition to using EXPIRY_DATE = ‘12/31/2010’
certificates for encryption within the database, SQL
Server can also use certificates for SSL connections as Changing the Properties:
well as for use with Service Broker. However, I’ll only There are only a limited number of things you can
concentrate on their use for encryption within the change with a certificate. Two things you can’t change
database. are the valid range of the certificate the certificate
subject. You can, however, change the private key as well
Creating: as the password the private key is encrypted with. I’ll only
Creating a certificate follows this syntax (without focus on the changing password option:
syntax for Service Broker use):
ALTER CERTIFICATE <certificate name>
CREATE CERTIFICATE <certificate name>
[AUTHORIZATION <user>] WITH PRIVATE_KEY (
{ ENCRYPTION_PASSWORD = ‘<new password>’
FROM <certificate source> [, DECRYPTION_PASSWORD = ‘<old password>’]
| If the certificate was encrypted with the database
WITH <certificate options> master key, the decryption_password is not needed. In
}
the example I used above, however, I did specify a
The certificate source is a file, an executable, or an password for ExampleCert2, so I’ll need to specify the old
assembly. I’ll focus strictly on the WITH clause option. password in order to set a new one:
The certificate options are defined as:
SUBJECT = ‘<certificate subject name>’ ALTER CERTIFICATE ExampleCert2
[, START_DATE = ‘<mm/dd/yyyy>’] WITH PRIVATE_KEY (
[, EXPIRY_DATE=’<mm/dd/yyyy>’] ENCRYPTION_PASSWORD = ‘GandalfTheWhite’,
[, ENCRYPTION_PASSWORD = ‘<password>’] DECRYPTION_PASSWORD = ‘GandalfTheGrey’ )
The only required field is SUBJECT. Therefore we can
Dropping:
create a certificate simply by doing the following:
When a certificate is no longer useful, whether it’s
CREATE CERTIFICATE ExampleCert1 due to the fact that it’s expired, it has been compromised,
WITH SUBJECT = ‘Example Certificate 1’ or the data is no longer being encrypted, dropping the
Since no encryption password was specified, the certificate is simple:
database master key will be used to encrypt the private DROP CERTIFICATE <certificate name>
key. This allows SQL Server to manage access to the
private key. I’ve also not specified authorization. Granting Access to a Certificate:
Authorization determines who will own the certificate. I
I mentioned earlier you could give access to a
do not have to specify a user as the owner of a certificate.
certificate without making a user an owner of the
There is another means if I want to give that user access
certificate. SQL Server 2005 completely restructures the
to the certificate and its private key. I’ll demonstrate this
permissions hierarchy from SQL Server 2000 and also
shortly.
introduces new options such as CONTROL. CONTROL
Here is a second certificate, but this one is created basically gives all permissions and is everything short of
with the expiry date and the password set. Since a actual ownership. CONTROL is what is needed to use a
password is used here, SQL Server cannot perform key certificate. The permissions hierarchy changes are
management with this certificate. Instead, if you want to beyond the scope of this article so I’ll just provide two
decrypt data encrypted with the certificate’s private key, examples on how to grant access to the certificates
you’ll also have to provide the password used to secure created earlier, one for each created principal. If you want
the private key. I’ll show this when I show how to encrypt to understand more about changes to permissions, refer
and decrypt data using certificates. to that topic in the SQL Server 2005 Beta 2 Books Online.
CREATE CERTIFICATE ExampleCert2

JANUARY/ FEBRUARY, 2005


25
GRANT CONTROL ON CERTIFICATE::ExampleCert1 TO ExampleID, EncryptMethod, PlainData,
TestUser1 CipherData,
GRANT CONTROL ON CERTIFICATE::ExampleCert2 TO CASE
TestUser2 WHEN EncryptMethod = ‘ExampleCert1’ THEN
CONVERT(nvarchar(max),
Encrypting/Decrypting Data with Certificates: DecryptByCert(Cert_ID(‘ExampleCert1’),
Here’s where the rubber meets the road. Having CipherData))
certificates doesn’t do us any good if we can’t use them WHEN EncryptMethod = ‘ExampleCert2’ THEN
to encrypt and decrypt data. In SQL Server 2005 there CONVERT(nvarchar(max),
are two functions in order to do just that: DecryptByCert(Cert_ID(‘ExampleCert2’),
CipherData,
EncryptByCert( <certificate ID>, <plain text> ) N’GandalfTheWhite’))
END DecryptedData
DecryptByCert( <certificate ID>, <encrypted
text> FROM dbo.ExampleTable
[, <password>] )
Asymmetric Keys
The password is only necessary if the certificate’s
Asymmetric keys are similar to certificates in that
private key was encrypted using a password If the
there is a public and private key pair. However,
certificate’s private key was encrypted using the
asymmetric keys don’t have a validity period and with
database master key, only the certificate ID and the
respect to SQL Server aren’t specifically used to identify
encrypted text is necessary with DecryptByCert(). The
a person, device, or service. Asymmetric keys tend to be
certificate ID can be determined from the certificate
used more to encrypt symmetric keys than data. I’ll
name using another function:
explain this in more detail when I talk about where and
Cert_ID(‘<certificate name>’) how to encrypt.
One thing to understand about DecryptByCert() is
the result from the function is of the varbinary type.
Therefore, the return value has to be changed to a Creating:
useable form with the Convert() function. This is true of Creating an asymmetric key is similar to a certificate,
all of the Decrypt functions. but there are different options, such as the encryption
Putting all of it together, here’s an example of algorithm. There is also the possibility of specifying an
inserting encrypted data into the table and then asymmetric key source outside of SQL Server (path,
retrieving it back out in decrypted form. If you attempt to executable, or assembly, as with the certificate),
use a certificate you don’t have access to when inserting however, I will look at the case where the asymmetric key
the data, a null value will be inserted instead (providing is generated entirely in SQL Server:
the column allows for nulls). You will likewise receive a
CREATE ASYMMETRIC KEY <key name> [AUTHORIZATION
null value should you try to decrypt with a certificate you <user>]
don’t have access to. To see how access to the WITH ALGORITHM = <encryption algorithm>
certificates work, execute the statements both as [ ENCRYPTION BY PASSWORD = ‘<password>’]
TestUser1 and TestUser2 and note the differences.
The available encryption algorithms are RSA_512,
DECLARE @Plain nvarchar(1000)
RSA_1024, and RSA_2048. If the ENCRYPTION BY
SET @Plain = ‘Example Plaintext’
PASSWORD clause is not specified, the database master
INSERT INTO dbo.ExampleTable key is used to encrypt the private key. Here are two
(EncryptMethod, PlainData, CipherData) VALUES examples, the first encrypting with the database master
(‘ExampleCert1’, @Plain, key and the second with a password I’ve specified.
EncryptByCert(Cert_ID(‘ExampleCert1’), @Plain))
CREATE ASYMMETRIC KEY AsymmKey1 AUTHORIZATION
INSERT INTO dbo.ExampleTable TestUser1
(EncryptMethod, PlainData, CipherData) VALUES WITH ALGORITHM = RSA_1024
(‘ExampleCert2’, @Plain,
EncryptByCert(Cert_ID(‘ExampleCert2’), @Plain)) CREATE ASYMMETRIC KEY AsymmKey2 AUTHORIZATION
TestUser2
SELECT WITH ALGORITHM = RSA_1024

26
ENCRYPTION BY PASSWORD = ‘TheShire’ CASE
WHEN EncryptMethod = ‘AsymmKey1’ THEN
Altering: CONVERT(nvarchar(max),
As with certificates, the password encrypting the DecryptByAsymKey(AsymKey_ID(‘AsymmKey1’),
private key can be changed. The only difference in syntax CipherData))
is ASYMMETRIC KEY instead of CERTIFICATE as in the
WHEN EncryptMethod = ‘AsymmKey2’ THEN
following example:
CONVERT(nvarchar(max),
ALTER ASYMMETRIC KEY AsymmKey2
WITH PRIVATE_KEY ( DecryptByAsymKey(AsymKey_ID(‘AsymmKey2’),
ENCRYPTION_PASSWORD = ‘MasterFrodo’, CipherData,
DECRYPTION_PASSWORD = ‘TheShire’ ) N’MasterFrodo’))

Dropping: END DecryptedData


Dropping an asymmetric key is also similar to the FROM dbo.ExampleTable
syntax for a certificate. Another example:
DROP ASYMMETRIC KEY ASymmKey2 Symmetric Keys
A symmetric key is one which is used both for
Encrypting/Decrypting Data with Asymmetric Keys: encryption and decryption. Symmetric key algorithms
Like with certificates, there are functions to encrypt also tend to be fast relative to asymmetric key algorithms
and decrypt data using asymmetric keys. There is also a and are often chosen when large amounts of data have
function to find the asymmetric key ID, much like there is to be encrypted and decrypted quickly. SQL Server 2005
one to determine the certificate ID. Here is the syntax for provides support for symmetric keys using a variety of
those functions: encryption algorithms.

EncryptByAsymKey( <key id>, <plain text> ) Creating:


Creating a symmetric key is similar to creating a
DecryptByAsymKey( <key id>, <encrypted text> [,
certificate or asymmetric key. The big difference is a
‘<password>’] ) symmetric key can have a certificate, an asymmetric key,
AsymKey_ID(‘<key name>’) another symmetric key, or a password to encrypt the
symmetric key. The syntax for creating a symmetric key
As with the decryption by certificate, the resulting
is:
value is of varbinary type and will need to be converted.
Here is the example using asymmetric keys for
CREATE SYMMETRIC KEY < key name> [AUTHORIZATION
encryption and decryption. Again, the first asymmetric <user>]
key used the database master key and the second
WITH <key options>
asymmetric key used a specified password:
DECLARE @Plain nvarchar(1000) ENCRYPTION BY <encryption mechanism>
SET @Plain = ‘Example Plaintext’ The only key option I’ll look at is the algorithm. The
INSERT INTO dbo.ExampleTable following symmetric key encryption algorithms are
(EncryptMethod, PlainData, CipherData) VALUES available: DES, TRIPLE_DES, RC2, RC4, DESX,
(‘AsymmKey1’, @Plain, AES_128, AES_192, and AES_256. The encryption
EncryptByAsymKey(AsymKey_ID(‘ASymmKey1’), mechanisms are more varied:
@Plain))
CERTIFICATE <certificate name>
INSERT INTO dbo.ExampleTable |
(EncryptMethod, PlainData, CipherData) VALUES PASSWORD = ‘<password>’
(‘AsymmKey2’, @Plain, |
EncryptByAsymKey(AsymKey_ID(‘ASymmKey2’), SYMMETRIC KEY <key name>
@Plain)) |
ASYMMETRIC KEY <key name>
SELECT
ExampleID, EncryptMethod, PlainData, Unlike certificates and asymmetric keys, an
CipherData, encryption mechanism must be specified. I’ve providede
JANUARY/ FEBRUARY, 2005
27
two examples. The first uses an asymmetric key (created EncryptByKey( <key GUID>, <plain text> [, <col
earlier) and the second uses a password: name> | <col value>] )
CREATE SYMMETRIC KEY SymmKey1 AUTHORIZATION DecryptByKey( <encrypted text> [, <col name> |
TestUser1
<col value>] )
WITH ALGORITHM = AES_256
ENCRYPTION BY ASYMMETRIC KEY AsymmKey1 Key_GUID(‘<key name>’)
CREATE SYMMETRIC KEY SymmKey2 AUTHORIZATION
TestUser2 The <col name> or <col value> is an optional
WITH ALGORITHM = TRIPLE_DES parameter. It’ll be hashed and concatenated with the
ENCRYPTION BY PASSWORD = ‘GatesOfMordor’ plain text before encryption or used to validate the data
during decryption. Its sole purpose is data integrity. I did
Altering: not use this optional parameter in the examples. I’ve
included a second opening of SymmKey2 demonstrating
Altering a symmetric key is different from both
how to open a symmetric key encrypted with an
certificates and asymmetric keys. Like with a database
asymmetric key having a password.
master key (which is a symmetric key), mechanisms of
encryption can be added and removed. The syntax is: OPEN SYMMETRIC KEY SymmKey1
USING ASYMMETRIC KEY AsymmKey1
ALTER SYMMETRIC KEY <key name>
{ ADD ENCRYPTION BY <encryption mechanism> | OPEN SYMMETRIC KEY SymmKey2
USING PASSWORD = ‘GatesOfMordor’
DROP ENCRYPTION BY <encryption mechanism> } OPEN SYMMETRIC KEY SymmKey2
The encryption mechanisms are the same for USING ASYMMETRIC KEY AsymmKey2
CREATE SYMMETRIC KEY. Multiple encryption WITH PASSWORD = ‘MasterFrodo’
mechanisms can be present at the same time. However,
before any changes can be made to a symmetric key DECLARE @Plain nvarchar(1000)
(and before a symmetric key can be used, period), the SET @Plain = ‘Example Plaintext’
symmetric key must be opened. The syntax to open a
symmetric key is: INSERT INTO dbo.ExampleTable
(EncryptMethod, PlainData, CipherData)
OPEN SYMMETRIC KEY <key name> VALUES
USING <encryption mechanism> (‘SymmKey1’, @Plain,
EncryptByKey(Key_GUID(‘SymmKey1’), @Plain))
Here is an example where the second symmetric key
is opened and an asymmetric key is added as an INSERT INTO dbo.ExampleTable
encryption mechanism. (EncryptMethod, PlainData, CipherData)
VALUES
OPEN SYMMETRIC KEY SymmKey2 (‘SymmKey2’, @Plain,
USING PASSWORD = ‘GatesOfMordor’ EncryptByKey(Key_GUID(‘SymmKey2’), @Plain))

ALTER SYMMETRIC KEY SymmKey2 SELECT


ADD ENCRYPTION BY ASYMMETRIC KEY AsymmKey2 ExampleID, EncryptMethod, PlainData,
CipherData,
Dropping: CASE
Dropping a symmetric key is similar to dropping a WHEN EncryptMethod = ‘SymmKey1’ THEN
certificate or an asymmetric key: CONVERT(nvarchar(max),
DecryptByKey(CipherData))
DROP SYMMETRIC KEY SymmKey2 WHEN EncryptMethod = ‘SymmKey2’ THEN
CONVERT(nvarchar(max),
Encrypting/Decrypting Data with Symmetric Keys: DecryptByKey(CipherData))
To encrypt or decrypt data with a symmetric key, it END DecryptedData
must be opened. Once that is accomplished, you can use FROM dbo.ExampleTable
the specified symmetric key algorithms. They are similar
to the other two encryption/decryption methods: Where and How to Encrypt?
The decision of trust is an important one when

28
deciding where to apply the encryption and whether or encrypted with the symmetric key.
not to use the database master key. SQL Server provides The holder of the private key can decrypt the
data encryption at two different “trust levels.” If DBAs are symmetric key and then use that symmetric key to
trusted, SQL Server can handle all of the key decrypt the data. It also makes a good practice for SQL
management using the database master key. This is by Server. Create an asymmetric key and then create a
far the simplest method of implementing encryption in symmetric key using the asymmetric key as the
the database. Asymmetric keys and certificates can be encryption mechanism. Encrypt the data with the
accessed automatically and symmetric keys should be symmetric key and you have a good balance of both key
opened fairly easily as well. security and performance.
If, however, due to business or other reasons even
the DBAs shouldn’t be able to decrypt the data, then the Issues to Consider
use of keys with passwords effectively keeps them out When implementing encryption, several issues must
from within SQL Server itself. Even profiler won’t reveal be addressed. The first is the one of key management. If
important contents of key commands. An administrator, SQL Server is not handling key management, you must
however, can hook up a debugger, and setting the come up with a secure mechanism to store passwords
proper breakpoints, see a query come through and see and allow an application to access keys. If a critical key is
the password. Of course, that’s true of any server. Using compromised, so is the data. Therefore, protecting the
SQL Server’s native encryption, these are the two options keys is almost as important as protecting the data itself.
provided. The second main issue is performance. This
The only other option is to build in encryption into the consideration has two prongs: performance loss due to
application and send encrypted data to SQL Server. This cycles spent encrypting and decrypting the data and
is considered a third “trust level” because it should be performance loss due to an inability to use indexes
completely independent of the DBAs and the SQL Server effectively since the data is encrypted. Using a hybrid
platform itself. cryptosystem like I mentioned above is probably the best
solution for the first prong. However, an expectation of
Use of a Hybrid Encryption Scheme slightly slower performance should be expected. With
In comparison of performance, symmetric key the second prong, it’s a matter of if the encrypted data is
algorithms tend to be substantially faster and if you’re used to filter or sort a result set. If not, there shouldn’t be
dealing with a lot of conversions (as with a database), a big performance problem. If, however, the encrypted
symmetric keys offer the best performance. However, data is used to do either of those two functions, indexes
symmetric keys are also weaker than asymmetric keys for are effectively out. Expect a slightly to significantly worse
the simple fact that once I have the key, I can encrypt and performance as a result.
decrypt the data at will. With an asymmetric key pair, I Conclusion
can expose the public key, which you can use to encrypt
Native encryption built into SQL Server 2005 looks
data intended for me. You can then send the encrypted
very promising. This addresses an item on the wish list of
data over a non-secure channel without worrying about
a number of DBAs and Microsoft looks to have
compromise. Once I receive it, I can decrypt using my
implemented a reasonable solution. Certificates,
private key. No one else can unless they’ve managed to
asymmetric keys, and symmetric keys are all supported
get my private key
within SQL Server and each encryption mechanism has
However, if we have a lot of data to send back and its own set of encryption/decryption functions. There are
forth, it’s better to use a symmetric session key and then trust and performance issues that must be addressed
encrypt it using my public key. I decrypt the session key before implementing a solution, but overall SQL Server
and then we encrypt all data using that session key. 2005 gives us a lot of flexibility to come up with workable
We’ve been able to exchange a symmetric key and we’ve solutions for our environments. I hope encryption
not had to send it in the clear over a non-secure channel. remains and makes it into the final product.
Therefore both of us possess the symmetric key securely
and are able to leverage the faster speed of the Brian Kelley is an Enterprise Systems Architect with AgFirst
symmetric encryption algorithms. These hybrid Farm Credit Bank and the regular security columnist for
cryptosystems are actually fairly popular. This is the SQLServerCentral.com. He is also the author of “Start to
Finish Guide to SQL Server Performance Monitoring” from
principle behind Secure Sockets Layer (SSL) as well as NetImpress and a member of the GSEC Advisory Board. You
Encrypting File System (EFS): A symmetric key is can contact him at SQLServerCentral.com.
encrypted with an asymmetric key pair and the data is
29
JANUARY/ FEBRUARY, 2005
PASS_0111204_SummitAd 12/7/04 2:35 PM Page 1

Register Now for the


2005 PASS Events

2005 PASS European Conference 2005 PASS Community Summit


11–13 May 2005 September 27– 30, 2005
Hilton Munich Park Gaylord Texan Resort & Convention Center
Munich, Germany Grapevine (Dallas), Texas USA
Register by 28 February 2005 for only 995€! Register by June 30, 2005 for $1295!
• Benefit from two days filled with highly technical sessions • Be a part of the LARGEST event exclusively dedicated to
presented by Microsoft, MVP’s and highly regarded industry Microsoft SQL Server education and training.
professionals, focusing on three tracks: Data Warehousing • Get the most comprehensive coverage of SQL Server 2005
and Business Intelligence, Database and Application anywhere while you develop and expand your knowledge
Development, and DBA/Enterprise Database Administration of SQL Server 2000.
and Deployment. • Meet and network with members of the Microsoft SQL
• Hear from members of the SQL Server development team at Server development team, SQL Server MVP’s and other SQL
Microsoft on the hottest topics to date including: Server professionals.
• What’s New for Developers in SQL Server 2005 – • Check out the world's premier SQL Server vendors at the
Gert Drapers, Microsoft largest, most comprehensive tradeshow dedicated to
SQL Server.
• Upgrading to SQL Server 2005 Management Tools –
Euan Garden, Microsoft Visit www.sqlpass.org for more information
• Reporting Services Enhancements for SQL Server 2005 – or to register for the 2005 PASS Events.
Jason Carlson, Microsoft
One-year complimentary PASS membership is also
• View the latest products and solutions at the Vendor Fair
included. Register today!
designed specifically for users in the Europe, Middle East and
Africa (EMEA) region.

Present a Technical Session and Receive a Looking for a way to freshen up on your
Complimentary Registration and Worldwide SQL Server skills before attending one of the
Industry Recognition. PASS Conferences?
If you would like to share your expertise at the 2005 The 2004 PASS Community Summit technical sessions have all
European Conference, please submit your proposal at been compiled on a CD-ROM with full desktop capture, MP3
www.sqlpass.org. This is a great opportunity to solidify audio, live demos, speaker PowerPoint presentations and
your reputation as a SQL Server expert. much more! Order your copy today at www.sqlpass.org.

ORKING TOG
R S W ET
HE
S E
U R

d
E

u
ca it
tio un
m
n u Networking u Com

www.sqlpass.org
PASS The Definitive Global Community
for SQL Server Professionals

About the Author:


Rick Heiges is a Database
Introducing Database
Consultant with Scalability Experts.
Prior to joining Scalability Experts,
Mirroring
he was on the full-time faculty at Database Mirroring is one of the
High Point University specializing coolest new features in SQL
in Database Coursework. He also Server 2005. What does
serves as Director of Membership Database Mirroring do for you?
of PASS and founded the local SQL Database Mirroring provides an
Server User Group in High Point, up-to-date copy of your data on
North Carolina. He is currently another server. But it provides
under contract with McGraw-
more than just a warm and
Hill/Irwin to write a textbook on
fuzzy feeling that your data is in
SQL Server for college-level classes.
more than one place for safety. database will be called ServerB
It also provides another High and will initially fill the “mirror”
Availability or Disaster Recovery role. There is also a third server
option for SQL Server as well as which we will call ServerW and
an ability to do some reporting serve in the role of “witness” in
from the mirror server. the High Availability scenarios.
Microsoft offers Clustering as its • When a transaction from a
current “native” solution for client hits the principal (step
High Availability in SQL Server #1), it is recorded in the
2000. Clustering is not going transaction log as it
away in SQL Server 2005 and it normally would (step #2).
is receiving some enhancements • While it is making the
which will not be discussed change in the data file (step
here. Database Mirroring has #3), it sends the transaction
been described as the evolution (step #3) to the mirror
of Log Shipping and has also server (ServerB).
been referred to as Transaction • The mirror will then record
Shipping. Log Shipping is NOT the transaction in its log file
going away in SQL Server 2005, (step #4) and then start to
but it is not getting any new write the change in its data
major features other than bug file (step #5) while sending
fixes. an acknowledgement (step
#5) back to the principal.
How it works…. • Once the principal receives
The server that contains the the acknowledgement, the
“real” database will be called transaction is committed
ServerA and will initially fill the (step #6) and the data is
“principal” role. The server mirrored successfully.
containing the “mirror” of the • There is no data that gets

JANUARY/ FEBRUARY, 2005


31
transmitted to or through assuming the principal role. The more likely to be physically far
the witness during this witness server is simply another apart from one another. The
process. instance of SQL Server and can safety level is set to “off”.
act as the witness for more Failover to the mirror server can
Server Roles… than one mirroring session. The only occur if the DBA initiates it.
The principal server handles role of the witness takes up very Because the safety is off, there
your client connections and little in the way of resources is a chance for some data loss
allows access to the database. It and is not a single point of on a very small scale. This is
is essentially this same server failure. If the Witness crashes, because the principal server
setup used today in your it would simply mean that does not wait for an
applications. The mirror server is automatic failover is not acknowledgement from the
constantly restoring / redoing possible although manual mirror that the transaction has
the transaction log from the failover is possible. The witness been received before
principal server. This way it has may live on the same server as acknowledging to the client
an up-to-date copy of the the principal or the mirror, but that the transaction has
database at all times. The that is not recommended and successfully been committed.
clients cannot access the mirror would be considered a “worst” This scenario fits in well for
server directly unless a failover practice. disaster recovery. There is also
occurs. When a failover occurs, no need for a witness in the
the mirror server becomes the Benefits asynchronous scenario.
principal server. In reality, clients Database mirroring provides for
never access the server when it two basic benefits. It provides Setting it Up…
is in the mirror role. The witness for high availability or disaster Database mirroring is initially set
server is there for one reason recovery. The high availability up by backing up the data to be
and one reason only. The scenario means that you have mirrored on the principal server
reason is to provide automatic automatic failover and you can and restoring it to the mirror
failover. The witness monitors lose the Principal server and still server. Once the full backup,
the other servers and confirms be available to your clients. This differential backup (if any), and
connectivity and roles being means that the safety level is set transaction log backups have
played by each server. By having to “full”. Although database been applied to the mirror
the witness, there can be a mirroring may be set up with server, the commands to
quorum. It takes at least two the servers not physically close establish the partnership
servers to decide which server to one another, having the between the principal and the
will play the principal role; this servers physically close helps to mirror may be issued. Once the
prevents the possibility of two eliminate network latency. If commands are issued, the
servers assuming the same role the purpose of your Database principal starts sending the
at the same time. If the witness Mirroring session is to provide latest updates since the last
did not exist, there might be a High Availability and the servers transaction log back up to the
possibility that both ServerA experience network latency, the mirror server. For a small- to
and ServerB assume the performance of your system medium-size database, this
principal role if one of them had will be affected. The Disaster works quite well. However, a
a brief network connection Recovery scenario (also referred large database may take an
outage. The witness is there to to as asynchronous scenario) is extraordinary amount of time to
vote in this process. This means used where the mirror server is initially set up due to the volume
that the server must talk to at used as a warm standby server. of data. In the case of the VLDB,
least one other server before In this scenario, the servers are clustering may be a much better

32
solution. During this period of Reporting for Duty…. Failover can occur over and
initial setup, the database will over again, but what about the
Another really cool feature in
have a session state of client applications? Clients can
SQL Server 2005 is the
synchronizing. This means that connect to the principal
Database Snapshot. Basically,
the database is working its way database either by using the
this feature allows a complete
to the synchronized state. latest MDAC or by a slight
copy of a database to exist at
Synchronized state occurs when modification of code (about 10
the time it commands to create
all updates from the principal lines) concerning the
the snapshot. It results in a very
have been sent and connection. Essentially, the
space-efficient, read-only copy
acknowledged that was sent by client tries to connect to the
of the database. We will not
the principal server. There is also principal. If it fails, it attempts
fully explore this feature here,
a suspended session state which connection to the secondary
but it can be very useful in
means that the database is server which will be the new
gaining another benefit. A
behind because it was principal if failover has
database snapshot maybe
suspended by the DBA, but occurred. At no time can a
created on the mirror server.
communication with the client connect to a database on
This allows read-only access to
partners is still possible. The last a server in the mirror role. The
the data stored on the mirror
state is called a disconnected servers that participate in
server at the point in time when
state. This means that the mirroring have their own IP
the commands were issued to
partner cannot communicate address and do not share a
create the database snapshot.
with the other partner. Only in third IP address, as is the case in
Once a transaction is processed
the SYNCHRONIZED state, you clustering.
after the command has been
are safe from data loss. The
issued, the database snapshot is
three other states indicate that
no longer up-to-date. But, this Summary
you are exposed to possible The Database Mirroring feature
does allow for the mirror server
data loss. on SQL Server 2005 provides a
to also be used as a reporting
This is the basic syntax for server. However, putting more much simpler method of
establishing a mirroring session stress on the mirror server can obtaining High Availability or
once the database is restored cause a slowdown of Disaster Recovery than before.
with NO RECOVER on the processing which may affect Although there are still many
mirror server. More information the mirroring session. This is good reasons to consider a
may be obtained in BOL. because it may affect the speed clustering solution, mirroring
ALTER DATABASE <database> in which the transaction is does not require any special
SET PARTNER = recorded which would in turn hardware or shared storage to
<server_network_address> affect the speed of the complete the setup. In
acknowledgement back to the addition to these reasons, a
This command is run on both principal server. Remember, the mirroring session may also
the principal and mirror servers. principal does not acknowledge provide access to data for
This syntax promotes simplicity. the transaction until the Mirror reporting purposes on the
If mirroring is for high responds that the transaction mirrored server. At the time of
availability, another T-SQL has been successfully recorded this article, there was no
command is issued to the when the safety is set to “full”. decision of which version of SQL
“ALTER DATABASE” syntax to Server this would appear in.
specify the Mirror server. Client Concerns
The discussions so far have
been focused on the database.

JANUARY/ FEBRUARY, 2005


33
PASS Reflects on Extending from across the Sanjay Shetty, the PASS
Significant Global United States to Western and Chapter network in India now
Expansion in 2004: Eastern Europe, PASS Official extends across multiple cities in
Looking Forward to Chapters have recently sprung India, including Bangalore,
Further Strengthening its up in Germany, Norway, the Hyderbad, Mumbai,
European Presence in 2005 United Kingdom, Denmark and Trivandrum and Pune, and
by: Professional Association Bosnia & Herzegovina. This Chapter meetings are held on a
for SQL Server growth in Europe has helped to monthly basis in each city.
fuel PASS’ educational “PASS is a savior for all of those
The 2004 PASS Board of offerings in the region, from in the SQL Server community,
Directors is proud to announce hosting a SQL Server Academy especially DBAs, OLAPs and
the success of a continued in Dubrovnik, Croatia in June of SQL Developers who previously
push to serve the needs of 2004, to recently announced had nowhere to turn. PASS has
global users of SQL Server plans to build upon that effort played a crucial role in
technology. Since it’s inception with the 2005 PASS European providing an opportunity for
in 1999, PASS has ensured Conference, 11-13 May in this segment of the [SQL
that SQL Server users’ Munich, Germany, at the Hilton Server] community to interact
educational needs have been Munich Park. and grow,” comments Shetty.
met both through a global Europe is not the only success Some of the proposed plans for
community structure as well as story in terms of PASS’ global the future include growth into
a network of local chapters. expansion. With affiliated additional cities throughout
Overall growth in Chapters has groups located in Australia and India where there is a
grown to over 80 worldwide, Japan, growth in Asia has significant SQL Server
with our total number of experienced a tremendous development community,
Chapters at the end of 2002 surge of energy in India. hopes to expand into other
more than doubling in 2003 Realizing that India’s rapidly APAC countries and plans for a
and 2004 alone. “ In addition growing marketplace of SQL regional 3-5 day joint event
to significant growth in the Server developers and users did with both the INETA and PASS
United States, PASS has not yet have a user group communities.
successfully extended its dedicated to SQL Server
community and benefits to For additional information on
education and networking, PASS and the benefits of
SQL Server users throughout PASS member Rushabh Mehta
the world” explains PASS becoming a member, please
worked with Kurt Allebach, the visit the PASS Web site at
President, Kevin Kline, “in part chapter liaison on the PASS
due to our extremely www.sqlpass.org, or contact
Board of Directors, and Joe PASS Headquarters at
dedicated members who help Homnick, a Microsoft Regional
drive the process as well as 312.527.6742.
Director, to find a way to serve
through our close cooperation this need. With help from
with Microsoft.” Microsoft Regional Director,

401 North Michigan Avenue Phone: 312.527.6742


Chicago, Illinois 60611- 4267 Fax: 312.245.1081
E-mail: passhq@sqlpass.org
Web: www.sqlpass.org

34
SQL Server Standard May/June, 2004

36

Вам также может понравиться