Ch01
Ch01
A Tour of SQL
Server 2005
Objectives
• Understand the differences between the available editions of SQL
Server 2005.
• Get an overview of the components and tools that SQL Server 2005
includes.
• See the sample databases that will be used in this course.
• Preview some of the new features in SQL Server 2005.
The files associated with this chapter are located in the following folder:
{Install Folder}\Tour
This chapter does not contain a lab.
Editions
SQL Server 2005 is available in a number of distinct editions that differ in
their features and their price. Here is a brief summary of these editions.
TIP: For more detailed information on the features supported by the different
versions of SQL Server 2005, consult this Web page:
http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx
For more information on pricing and licensing, consult this Web page:
http://www.microsoft.com/sql/howtobuy/default.mspx
Server Components
SQL Server 2005 is composed of a number of distinct components. The most
commonly used one is the Database Engine, which provides the core service
for storing, processing, and securing data. The database engine, which is
accompanied by tools for creating and managing relational database objects,
also supports the following SQL Server features:
• Analysis Services includes the tools for creating and managing online
analytical processing (OLAP) and data mining applications.
• Reporting Services includes server and client components for
creating, managing, and deploying tabular, matrix, graphical, and free-
form reports. Reporting Services is also an extensible platform that
you can use to develop report applications.
• Integration Services is a set of graphical tools and programmable
objects for moving, copying, and transforming data.
There is also a set of services called Notification Services for developing and
deploying applications that send messages to subscriber applications running
on a variety of devices when specified data changes occur.
Management Tools
SQL Server 2005 includes a rich set of graphical tools, and most of these are
completely new in this version. These tools are accessible from the Start|All
Programs|Microsoft SQL Server 2005 menu.
• SQL Server Books Online contains the core documentation for SQL
Server 2005, and is also available on the Web as part of the Microsoft
Developer Network (MSDN).
• SQL Server Samples provide sample code and sample applications
for the Database Engine, Analysis Services, Reporting Services, and
Integration Services.
The Object Explorer is right-click enabled, which means that any node you
click on displays its own context-sensitive menu, as shown in Figure 2.
Databases
When you expand the tree, each node displays its child objects. Figure 3 shows
the installed databases. In the next section, you’ll learn how to install the
Northwind sample database if it isn’t already installed on your server.
Security
Security is managed at two levels, at the server level and at the database level.
Figure 4 shows the nodes for creating logins, assigning server roles, and
managing credentials at the server level.
Figure 5 shows the security node of the Northwind database, where users,
roles, schemas, asymmetric keys, certificates, and symmetric keys are
managed.
Server Objects
Figure 6 shows the expanded tree for managing server objects.
Replication
The replication node shown in Figure 7 contains folders for managing local
publications and subscriptions.
Management
The management node, shown expanded in Figure 8, is where you’ll find your
maintenance plans for backing up SQL Server databases, as well as the logs
and Activity Monitor. You will find upgraded SQL Server 2000 Database
Maintenance Plans, DTS packages, and SQL Mail in the Legacy folder.
Northwind
Northwind is an older database that originally shipped with Microsoft Access
and with SQL Server 2000, and it has a simpler design than AdventureWorks.
This simpler design makes Northwind useful for examples where the
complexity of the AdventureWorks design might distract from the main point
of the example.
Try It Out!
See instnwnd.sql Follow these steps to install the Northwind database, if it doesn’t already
appear in the Databases list in SSMS.
2. When the script opens in SSMS, the Connect to Server dialog box
appears. Click Connect.
AdventureWorks
AdventureWorks was developed for SQL Server 2005 and it includes
examples of features that were introduced in SQL Server 2005, such as the
XML data type. Figure 9 shows a partial view of some of the AdventureWorks
tables in the Object Explorer. Note that the objects are named using the
schema_name.object_name syntax.
Northwind uses dbo as the schema for all objects, so in Northwind you see
them listed as shown in Figure 10. The dbo schema is present in all databases,
and in previous versions of SQL Server it was commonly used for all objects,
because the alternative was to use schemas based on object ownership and tied
to individual user accounts. In SQL Server 2005, this tie between schemas and
users was broken and you can now create and use schemas that are not named
for or necessarily associated with individual users.
Figure 10. Northwind uses the dbo schema for all objects.
AdventureWorksDW
The AdventureWorkDW sample database is an example of a database that is
used primarily for reporting and analysis rather than for entering new
transactions. The database tables are mostly categorized into fact tables and
dimensions tables, which are named in this example with prefixes that show
the type of table, as shown in Figure 11. Fact tables contain quantitative
measures to be analyzed and the dimension tables contain qualitative data used
for grouping and filtering the measures.
Database Objects
By expanding the nodes for each database in the Object Explorer, you can see
the variety of database objects that SQL Server supports, shown in Figure 12.
Here’s a summary of a few of the database objects that you will use most:
• Tables: All data is stored in rows in tables that each have a defined set
of columns, indexes, and constraints.
• Database Diagrams: Diagrams provide a graphical view of a set of
tables and how they are related to each other with foreign key
constraints. You can also use database diagrams to make design
changes to tables.
• Views: Views are saved queries that select data from one or more
tables.
• Stored Procedures: These are saved queries that can select data, like
views, but that can also make changes to the design or contents of
tables. Stored procedures can have parameters and procedural code
written either with Transact-SQL (T-SQL) or with a .NET language.
• Functions: SQL Server has built-in functions that you can call from
your T-SQL code, and you can create user-define functions that take
parameters and return data.
Creating Tables
You can use the table designer to create and edit a table. Expand a table node
and right-click on a column in the table. Select Modify from the menu. This
displays all of the columns in the table and the properties for the selected
column, as shown in Figure 13 for the Person.Contact table in
AdventureWorks.
Creating a View
You can use SSMS to create and save a new view, or to generate the Transact-
SQL for a select query without saving a new view. Right-click on the Views
node in the Object Explorer and select New View from the menu. Select the
tables you want to use, and the join statements will be generated for you. You
can use this technique not only to create views, but to copy/paste the SQL into
the definitions of other objects as well. You can execute the SQL to see the
result set, as shown in Figure 16.
Generating Scripts
You can easily script existing objects in SSMS, generating scripts for creating
objects, scripting the definition of existing objects or generating DML
statements.
See Tour.sql Hierarchical data is often difficult to work with in relational queries, because it
is difficult to write queries that can handle multiple levels of nested data when
you don’t know ahead of time how many levels there will be.
Here’s an example of a query that uses a common table expression to find all
the employees in the Northwind database who report either directly or
indirectly to a particular employee.
Ranking Functions
SQL Server 2005 introduces new ranking functions that make it much easier
than in the past to create queries that rank results, especially if the results are
not sorted in the same order that you want to use for the ranking. There are
four ranking functions:
• RANK: Returns the rank of each row based on the number of ranked
rows ahead of it. For example, if two rows are tied for first place, then
the third row gets a rank of 3, not 2.
• DENSE_RANK: Returns the rank of each row without any gaps in
the ranking numbers. For example, if two rows are tied for first, then
the third row gets a rank of 2.
• NTILE: Distributes the rows into a specified number of groups and
returns the number of the group each row is in. Percentiles, where the
rows are divided into 100 groups, are an example of this type of
ranking.
• ROW_NUMBER: Returns the sequential number of each row in
ranked order, starting at 1 for the first row.
One interesting feature is the ability to define a different sort order for the
ranking from the one used to list the results. The following query ranks
products by unit price in descending order (highest price first) but it lists the
products alphabetically.
Figure 18. Products partitioned by category and ranked by UnitPrice within that
category.
This is a very handy new feature that allows you to perform efficient set-based
operations to solve problems that otherwise might have tempted you to use
less-efficient procedural operations, such as cursors.
The following example uses the APPLY operator and also shows how you can
now use a variable or a parameter with TOP. This example uses the
CategoryID value to determine how many of the top products by price are
listed for each category.
APPLY is often used with functions that return sets of data, called table-valued
functions. This example first creates a function and then calls it using the
APPLY operator.
PIVOT
Users and developers who have worked with pivot tables in Excel or crosstab
queries in Access have for years requested a pivot extension to the T-SQL
language. The following example first creates a view that returns sales totals
by year and by customer. The next query uses PIVOT to rotate the years up
into column headings.
The partial results of selecting from the view are shown in Figure 19.
Figure 19. Partial results from a view to be used as the basis for a PIVOT query.
Here’s a query that uses PIVOT to move the years into column headings. The
results are shown in Figure 20.
SELECT *
FROM dbo.CustomerOrdersByYear
PIVOT(
SUM(Amount)
FOR OrderYear
IN([1996], [1997], [1998])
) AS P;
Figure 20. Results from a query that uses PIVOT to rotate years into column
headings.
Figure 21. Using FOR XML PATH to mix elements and attributes.
FOR XML PATH also supports options that can return results without any
XML markup. This example combines that with the use of APPLY to generate
a comma-delimited list of the three top products by price in each category. The
results are shown in Figure 22.
Figure 22. Using APPLY and FOR XML PATH to return a comma-delimited list.
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO dbo.Customers (CustomerID, CompanyName)
VALUES ('ALFKI', 'New ALFKI');
COMMIT
PRINT 'Transaction committed.';
END TRY
BEGIN CATCH
ROLLBACK
SELECT
ERROR_NUMBER() AS Number,
ERROR_SEVERITY() AS Severity,
ERROR_STATE() AS State,
ERROR_PROCEDURE() AS procedureName,
ERROR_LINE() AS Line,
ERROR_MESSAGE() AS messageText;
PRINT 'Transaction rolled back.';
END CATCH
Figure 23. Using the new error handling functions with TRY/CATCH to display
information.
Using EXECUTE AS
Stored procedures can be used to provide enhanced security by granting users
execute permissions on the stored procedure, while revoking or denying
permissions on the underlying objects. However, if the schema (or owner) of
the stored procedure and underlying objects is different or the stored procedure
contains dynamic SQL (sp_executesql, EXEC) then the caller will be required
to have permissions on the underlying objects. In SQL Server 2000 it was not
possible to change this behavior.
SQL Server 2005 introduces the EXECUTE AS clause which allows you to
specify the security context under which the stored procedure executes to
another user. The default security context is that of CALLER (whoever is
calling the stored procedure). The other security context options are:
Rules for permissions on underlying objects also apply to the entity specified
in the EXECUTE AS clause.
Read operations do not request shared locks on the data, so transactions that
modify data do not block transactions that read data, and transactions that read
data do not block transactions that write data, as they normally would under
the default READ COMMITTED isolation level.
As a host for the CLR, commonly referred to as the SQLCLR, SQL Server
2005 lets you run in-process .NET code that is deeply integrated with SQL
Server. This means that you can write code, typically in Visual Basic or C#,
and run it in the same process as SQL Server, with full access to all database
objects. You can augment the power of T-SQL by calling functions written in
.NET code.
Stored Procedures √ √
User-defined Functions √ √
Triggers √ √
User-defined Types √
Aggregates √
Table 1. T-SQL vs. SQLCLR for various code modules.
In general, we’ve found that these guidelines provide a good basis for deciding
whether to use T-SQL or SQLCLR code:
SQL Server 2005 also introduced new managed interfaces for using .NET code
to access and control SQL Server objects, including SQL Management Objects
(SMO) and Replication Management Objects (RMO).
You can use SSIS to import, export, and transform data between data sources.
In early versions of SQL Server, the only data migration tool that shipped with
SQL Server was BCP (Bulk Copy Program). This tool was efficient for
moving large amounts of data in and out of SQL Server. However, its DOS
interface was limiting. Microsoft re-engineered BCP and integrated it into Data
Transformation Services (DTS) with the release of SQL Server 7.0 and
updated it in 2000 to provide users with a much more robust data
transformation tool that included a Windows interface.
Even with the improved version of DTS in SQL Server 2000, there were a
number of problems. One of the biggest was mobility—the ability to move
DTS packages to other servers and work successfully there. The tasks built
into DTS had some unacceptable limitations, such as an FTP task that could
only download files, not upload them. The Send Mail task used MAPI,
requiring that Outlook be installed on the server. Development tools were
crude and hard to use, to say the least. And there were many other limitations.
Nonetheless, DTS provided a robust way to move data around and transform
it, making it a widely used feature of SQL Server.
For SSIS, Microsoft built on those earlier attempts and provided a robust SQL
Server tool you can use to perform many tasks associated with migrating data.
SSIS is a complex feature, but it can dramatically simplify data migration and
is a worthy tool in the ETL (Extraction, Transformation, and Loading)
business space.
environment that you will use to develop business solutions that include
Analysis Services, Integration Services, and Reporting Services projects. Each
project type supplies templates for creating the objects required for business
intelligence solutions, and provides a variety of designers, tools, and wizards
to work with the objects.
Try It Out!
See the The Microsoft samples for SQL Server 2005 include an SSIS package that
AWDataWare- moves data from the AdventureWorks database into the AdventureWorksDW
houseRefresh database. A copy of this sample is included with the sample files for this
folder chapter. To load the SSIS package, follow these steps.
1. Start either BIDS or, if you prefer and have it installed, Visual Studio
2005. To start BIDS, select Start|All Programs|Microsoft SQL Server
2005|SQL Server Business Intelligence Development Studio.
These steps open Visual Studio’s Package Designer and load the package,
shown in Figure 24.
Figure 24. The BIDS development environment with a package loaded and ready
to edit or execute.
TIP: Installation of the SQL Server samples does not happen automatically when
you install SQL Server. To install the samples, select Start|All
Programs|Microsoft SQL Server 2005|Documentation and
Tutorials|Samples|Microsoft SQL Server 2005 Samples.
You can browse through the package and take a look at the available tools in
the Toolbox to get an idea of what’s available in SSIS. Close BIDS when you
are done inspecting the package.
Reporting Services
SQL Server 2005 Reporting Services is a server-based reporting platform that
you can use to create and manage tabular, matrix, graphical, and free-form
reports that contain data from relational and multidimensional data sources.
The reports that you create can be viewed and managed over a World Wide
Web-based connection. Reporting Services includes the following core
components:
• A complete set of tools that you can use to create, manage, and view
reports.
• A Report Server component that hosts and processes reports in a
variety of formats. Output formats include HTML, PDF, TIFF, Excel,
CSV, and more.
• An API that allows developers to integrate or extend data and report
processing in custom applications, or create custom tools to build and
manage reports.
The reports that you build can be based on relational or multidimensional data
from SQL Server, Analysis Services, Oracle, or any Microsoft .NET data
provider such as ODBC or OLE DB. You can create tabular, matrix, and free-
form reports. You can also create ad hoc reports that use predefined models
and data sources.
Analysis Services also provides a rich set of data mining algorithms to enable
business users to mine their data looking for specific patterns and trends. These
data mining algorithms can be used to analyze data through a UDM or directly
from a physical data store.
Try It Out!
See the TestSSAS Follow these steps to take a look at a UDM that you will build later in this
_Complete folder course.
7. Expand Product and drag Product Line to the section of the browser
labeled Drop Column Fields Here.
Summary
• SQL Server Management Studio (SSMS) is an integrated environment
for accessing, configuring, managing, administering, and developing
all components of SQL Server.
• SQL Server Profiler provides a graphical user interface for monitoring
an instance of the Database Engine or an instance of Analysis
Services.
• The Database Engine Tuning Advisor helps create optimal sets of
indexes, indexed views, and partitions to improve database
performance.
• The Object Explorer displays information for all servers to which it is
connected in a hierarchical tree view.
• SQL Server 2005 ships with new sample databases, AdventureWorks
and AdventureWorksDW.
• You can create SQL Server objects using the designers or by writing
Transact-SQL scripts.
• New Transact-SQL features include CTEs, ranking functions, TOP(n),
APPLY, PIVOT, FOR XML PATH, and Try/Catch error handling.
• EXECUTE AS allows you to specify the security context under which
a stored procedure executes to another user.
• Snapshot isolation helps avoid blocking scenarios by using a new row
versioning mechanism.
• SQL Server 2005 overcomes the limitations of T-SQL by hosting the
Common Language Runtime (CLR).
• The Business Intelligence Development Studio (BIDS) is an integrated
development environment for Analysis Services, Reporting Services,
and Integration Services solutions that is based on Visual Studio.
• SQL Server Integration Services (SSIS) includes tools and wizards for
managing data from different data sources.
• SQL Server 2005 Reporting Services is a server-based reporting
platform that you can use to create and manage tabular, matrix,
graphical, and free-form reports that contain data from relational and
multidimensional data sources.
• SQL Server 2005 Analysis Services (SSAS) provides online analytical
processing (OLAP) and data mining functionality for business
intelligence solutions.
Questions
1. Which tool can you use to create database objects and administer security?
2. What are the names of the two new sample databases that ship with SQL
Server 2005?
4. Which Transact-SQL clause can you use to change the security context
that a stored procedure runs under?
5. Which new feature in SQL Server 2005 can help you avoid blocking
scenarios?
Answers
1. Which tool can you use to create database objects and administer security?
SQL Server Management Studio (SSMS)
2. What are the names of the two new sample databases that ship with SQL
Server 2005?
AdventureWorks and AdventureWorksDW
4. Which Transact-SQL clause can you use to change the security context
that a stored procedure runs under?
EXECUTE AS
5. Which new feature in SQL Server 2005 can help you avoid blocking
scenarios?
Snapshot Isolation