0% found this document useful (0 votes)
8 views36 pages

Ch01

Uploaded by

vuthnarak2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views36 pages

Ch01

Uploaded by

vuthnarak2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

A Tour of SQL Server 2005

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.

Microsoft SQL Server 2005 1-1


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

SQL Server 2005 Editions,


Components, and Tools
SQL Server 2005 is a large and complex product, with many available editions
and many different components, and many separate tools. We begin this course
by reviewing these editions, components, and tools.

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.

• Enterprise Edition is available in both 32-bit and 64-bit versions and


has comprehensive functionality to support the largest organizations
and the most complex requirements. This is the highest priced edition
and it includes “everything.”
• Enterprise Evaluation Edition is exactly the same as the Enterprise
edition, but it is free and it expires 180 days from installation. You can
upgrade to the full version for production use prior to the expiration.
• Developer Edition also has all the features and capabilities of the
Enterprise edition. It is very inexpensive ($50), but it is licensed for
development only, not for production. You can upgrade a Developer
edition for production use.
• Standard Edition is also available in both 32-bit and 64-bit versions.
It is a less expensive alternative for small and medium sized
organizations, where it is often used for e-commerce, data
warehousing, and line-of-business solutions. This edition is limited to
four CPUs per server, and is missing several advanced features related
to business intelligence and high availability.
• Workgroup Edition is the least expensive production edition that you
can buy (there are also free production versions, described next). It
only supports 32-bit processors, and only two CPUs per server. This
edition limits the RAM it can use (3 gigabytes) but not the disk space.
Analysis Services and Integration Services are not included with this
version, and neither is the Profiler or the Database Tuning Advisor.
• Express Edition is the free replacement for MSDE and is integrated
with Visual Studio. Express with Advanced Services is also free and
additionally includes SQL Server Management Studio Express, full-
text catalog support, and the ability to view Reporting Services
reports. Both Express editions are 32-bit only, and are limited to using
one CPU, 1 gigabyte of RAM, and 4 gigabytes of disk space per
database.

1-2 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
SQL Server 2005 Editions, Components, and Tools

• Mobile Edition uses a different database engine from the other


editions, but it supports Transact-SQL queries that are compatible with
the other editions. It can also use merge replication to synchronize wit
other editions. This edition runs in a very small RAM footprint and is
intended for use in mobile devices.
• SQL Server Everywhere uses the same data engine as the Mobile
edition, but is intended for use on desktop and laptop machines rather
than on mobile devices like phones and PDAs.

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:

• Replication: The ability to generate, synchronize, and manage


multiple copies of database objects, including copies containing only a
subset of the full data.
• Full-Text Search: A special indexing engine and query syntax for
finding text data that meets specified criteria.
• Service Broker: A message-based communication platform for
creating distributed applications.
In addition to the core database engine and its tools, SQL Server also supports
three types of Business Intelligence services:

• 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.

Microsoft SQL Server 2005 1-3


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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 Management Studio (SSMS) is an integrated


environment for accessing, configuring, managing, administering, and
developing all components of SQL Server. SSMS combines the
features of Enterprise Manager, Query Analyzer, and Analysis
Manager, included in previous releases of SQL Server, into a single
environment.
• The Business Intelligence Development Studio is an integrated
development environment for Analysis Services, Reporting Services,
and Integration Services solutions that is a based on Visual Studio. It is
actually a stripped down version of Visual Studio with templates that
provide access to rich designers for building business intelligence
projects.
• SQL Server Configuration Manager provides basic configuration
management for the SQL Server’s Windows services, server protocols,
client protocols, and client aliases.
• SQL Server Profiler provides a graphical user interface for
monitoring an instance of the Database Engine or an instance of
Analysis Services.
• Database Engine Tuning Advisor helps create optimal sets of
indexes, indexed views, and partitions to improve database
performance.

Documentation and Samples


SQL Server 2005 contains documentation and samples that demonstrate how
to use SQL Server features and functionality.

• 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.

1-4 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Using SQL Server Management Studio (SSMS)

Using SQL Server Management Studio


(SSMS)
The tool that you will probably use the most is SQL Server Management
Studio (SSMS). This is an integrated development environment for
administering SQL Server 2005 and writing Transact-SQL code. SSMS is
hosted in the Visual Studio shell, although it is not an instance of Visual
Studio, as the Business Intelligence Development Studio is.

Connecting Management Studio


To open SSMS and connect the Object Explorer to a server, click on the Start
menu in Windows, then click All Programs|Microsoft SQL Server
2005|SQL Server Management Studio. This loads the Connect to Server
dialog box, as shown in Figure 1. In most cases, you can use the default
Windows Authentication and click Connect. If you select SQL Server
Authentication, then you need to enter a login name and password.

Figure 1. Logging in to SQL Server.

The Object Explorer


The Object Explorer displays information for all servers to which it is
connected in a hierarchical tree view, which is populated on demand when a
node is expanded. You can double-click a node to expand it or click on the
plus sign next to the node.

Microsoft SQL Server 2005 1-5


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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.

Figure 2. The right-click menu options for a Server node.

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.

Figure 3. Installed databases.

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 4. Server level security options.

1-6 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Using SQL Server Management Studio (SSMS)

Figure 5 shows the security node of the Northwind database, where users,
roles, schemas, asymmetric keys, certificates, and symmetric keys are
managed.

Figure 5. Database level security options.

Server Objects
Figure 6 shows the expanded tree for managing server objects.

Figure 6. Nodes in the Server Objects tree.

Replication
The replication node shown in Figure 7 contains folders for managing local
publications and subscriptions.

Figure 7. Exploring replication objects in SSMS.

Microsoft SQL Server 2005 1-7


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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.

Figure 8. Options for managing SQL Server.

Exploring the Sample Databases


In this course, you will use two Microsoft sample databases: Northwind and
AdventureWorks. You will also work with a data warehouse version of the
AdventureWorks database, named AdventureWorksDW.

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.

1. Double-click the instnwnd.sql file in Windows Explorer. We have


included a copy of the file in the samples directory for this chapter.

1-8 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Using SQL Server Management Studio (SSMS)

2. When the script opens in SSMS, the Connect to Server dialog box
appears. Click Connect.

3. With the instnwnd.sql script open in SQL Server Management Studio,


click the Execute button. This runs the script to create the database.

4. In the Object Explorer, right-click on the Databases node and select


Refresh. The Northwind database is now listed. You can expand its
Tables node to see the tables in the database.

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.

Figure 9. AdventureWorks tables in the Object Explorer.

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.

Microsoft SQL Server 2005 1-9


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

Understanding the AdventureWorks Database


Open SQL Server Books Online and scroll to the Samples and Sample
Databases section at the lower right-hand corner. Click the AdventureWorks
Sample OLTP Database link. The SQL Server Objects in
AdventureWorks link contains the following sections:

• Data Types in AdventureWorks: Lists the system and user-defined


data types that are used in AdventureWorks, and the tables or samples
in which they can be located.
• Schemas in AdventureWorks: Describes the schemas that are used in
AdventureWorks. Provides details about accessing objects that are
contained in the schemas and information about using schema name
alternatives.
• Stored Procedures in AdventureWorks: Describes the stored
procedures that are included in AdventureWorks.
• User-defined Functions in AdventureWorks: Describes the user-
defined functions that are included in AdventureWorks.

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.

1-10 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Using SQL Server Management Studio (SSMS)

Figure 11. Most of the tables in AdventureWorksDW are identified as dimension


tables or fact tables.

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.

Microsoft SQL Server 2005 1-11


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

Figure 12. Exploring database objects.

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.

1-12 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Working with Tables and Queries

Working with Tables and Queries


Although SQL Server supports a wide variety of objects and services, most of
the work you do as a developer is with tables and queries. Tables are where
you store your SQL Server data and queries are how you access and
manipulate the 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.

Figure 13. Editing database objects.

Generating a CREATE TABLE Script


To generate a CREATE TABLE script for an existing table, right-click on the
table in the Object Explorer and choose Script Table as|CREATE To|New
Query Editor Window, as shown in Figure 14. Note that you can also script
to the Clipboard, which is useful when you want to combine multiple scripts
into a single document.

Microsoft SQL Server 2005 1-13


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

Figure 14. Scripting an existing table.

This will generate Transact-SQL code. Experienced database administrators


and developers often write the necessary T-SQL code from scratch directly,
but when you are getting started or if you are performing a task that you don’t
do often, it’s great to be able to use the SSMS tools to help you create scripts.

Using the Template Explorer


Additional script templates are available in a tool named the Template
Explorer. You can access this tool from the View menu. The Template
Explorer presents a tree view that allows you to navigate through a set of
category folders to find the type of script you need. Then you can double-click
the script entry to open a Query Editor window and create a script, as shown in
Figure 15.

1-14 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Working with Tables and Queries

Figure 15. The Template Explorer presents a hierarchy of script templates.

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.

Microsoft SQL Server 2005 1-15


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

Figure 16. Using the Query Designer.

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.

To generate an INSERT script, right-click on the table in the Object Explorer


and choose Script Table as|INSERT To|Clipboard. Paste the text. In order to
execute the query, you’ll need to fill in the actual values in the placeholders
delimited by the angle brackets. Note that the data type required is also
specified.

1-16 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Working with Tables and Queries

INSERT INTO [Northwind].[dbo].[Region]


([RegionID]
,[RegionDescription])
VALUES
(<RegionID, int,>
,<RegionDescription, nchar(50),>)

You can fill the angle-bracketed parameters in manually, or choose


Query|Specify Values for Template Parameters from the menu. There is
also a toolbar button and a keyboard shortcut. This loads a dialog box where
you can fill in the parameters, as shown in Figure 17. Click OK when done.

Figure 17. Filling in template parameters.

This generates the following Transact-SQL:

INSERT INTO [Northwind].[dbo].[Region]


([RegionID]
,[RegionDescription])
VALUES
(5
,Central)

Microsoft SQL Server 2005 1-17


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

New Transact-SQL Features


In this section you’ll get a preview of some of the new relational capabilities
that have been added to the T-SQL language in SQL Server 2005. Later in the
course, you’ll learn more about the details of how these new features work, but
this quick look will serve to whet your appetite for what’s coming and will be
especially interesting to developers who already have some experience
creating queries with previous versions of SQL Server or with other database
engines. These new techniques are all explained in more detail later in the
course.

Common Table Expressions (CTEs)

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.

DECLARE @root int;


SET @root = 2;
WITH ReportsToCTE
AS
(
-- Anchor member returns root node
SELECT EmployeeID, ReportsTo, 0 AS Level
FROM dbo.Employees
WHERE EmployeeID = @root
UNION ALL
-- Recursive member selects from the CTE itself,
-- returning next level of children
-- until no rows are returned
SELECT Child.EmployeeID, Child.ReportsTo,
Parent.Level + 1
FROM ReportsToCTE AS Parent
JOIN dbo.Employees AS Child
ON Child.ReportsTo = Parent.EmployeeID
)
SELECT * FROM ReportsToCTE;

1-18 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
New Transact-SQL Features

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.

-- Ranked by UnitPrice but listed by ProductName


SELECT ProductName, UnitPrice,
ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS
RowNumber,
RANK() OVER (ORDER BY UnitPrice DESC) AS Rank,
DENSE_RANK() OVER (ORDER BY UnitPrice DESC) AS DenseRank
FROM dbo.Products
ORDER BY ProductName;

This example uses the optional PARTITION BY to group the data by


CategoryID and return the dense ranking within each category according to
UnitPrice, as shown in Figure 18.

Microsoft SQL Server 2005 1-19


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

-- Ranked within each category.


SELECT ProductName, CategoryID, UnitPrice,
DENSE_RANK() OVER (PARTITION BY CategoryID
ORDER BY UnitPrice DESC) AS DenseRank
FROM dbo.Products
ORDER BY CategoryID, UnitPrice DESC;

Figure 18. Products partitioned by category and ranked by UnitPrice within that
category.

TOP(n) and APPLY


SQL Server 2005 introduced a new T-SQL syntax for enabling you to feed
each row from the result set of one query to a second query that uses values
from the first query as input, using the new APPLY operator.

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.

1-20 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
New Transact-SQL Features

SELECT CategoryID, CategoryName, ProductName, UnitPrice


FROM dbo.Categories C CROSS APPLY
(SELECT TOP(C.CategoryID) ProductName, UnitPrice
FROM dbo.Products
WHERE CategoryID=C.CategoryID
ORDER BY UnitPrice DESC) P
ORDER BY C.CategoryID, ProductName;

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.

CREATE FUNCTION dbo.fnTopNByCategory


(@TopN int, @CategoryID int)
RETURNS TABLE
AS
RETURN
SELECT TOP(@TopN) ProductName, UnitPrice
FROM dbo.Products
WHERE CategoryID=@CategoryID
ORDER BY UnitPrice DESC;
GO
-- No separate SELECT statement for the function
SELECT CategoryID, CategoryName, ProductName, UnitPrice
FROM dbo.Categories C CROSS APPLY
dbo.fnTopNByCategory(2, C.CategoryID) P
ORDER BY C.CategoryID, ProductName;

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.

Microsoft SQL Server 2005 1-21


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

-- First create a view to work with


CREATE VIEW dbo.CustomerOrdersByYear
AS
SELECT Customers.CompanyName,
SUM(Subtotal) AS Amount,
YEAR(Orders.OrderDate) AS OrderYear
FROM Customers JOIN
Orders
ON Customers.CustomerID = Orders.CustomerID
JOIN [Order Subtotals]
ON Orders.OrderID = [Order Subtotals].OrderID
GROUP BY CompanyName, YEAR(Orders.OrderDate);
GO
SELECT * FROM dbo.CustomerOrdersByYear;

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;

1-22 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
New Transact-SQL Features

Figure 20. Results from a query that uses PIVOT to rotate years into column
headings.

FOR XML PATH


The FOR XML clause was first introduced in SQL Server 2000 to allow you to
return results in the form of XML. SQL Server 2005 added a new PATH mode
that makes it much easier to create complex XML that mixes elements and
attributes. Here’s an example of using this new mode with an embedded
subquery in the SELECT clause that returns a column of the new XML data
type. This XML data gets automatically merged into the final result, a section
of which is shown in Figure 21.

SELECT CustomerID, O.OrderID, Freight,


(SELECT ProductID [@ProductID],
Quantity [@Quantity],
UnitPrice [@UnitPrice]
FROM dbo.[Order Details] D
WHERE D.OrderID = O.OrderID
ORDER BY ProductID
FOR XML PATH('OrderDetail'), TYPE)
FROM dbo.Orders O
WHERE CustomerID = 'ALFKI'
ORDER BY OrderID
FOR XML PATH('Order'), ROOT('Orders')

Microsoft SQL Server 2005 1-23


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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.

-- Combining APPLY with FOR XML PATH


-- to get an in-row list
SELECT CategoryName,
STUFF(TopProducts,1,2,'') --strip the leading ', '
FROM dbo.Categories C OUTER APPLY
(SELECT TOP(3) ', '+ProductName [text()]
FROM dbo.Products
WHERE CategoryID=C.CategoryID
ORDER BY UnitPrice DESC
FOR XML PATH('')) P(TopProducts)
ORDER BY C.CategoryID;

Figure 22. Using APPLY and FOR XML PATH to return a comma-delimited list.

1-24 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
New Transact-SQL Features

Try/Catch Error Handling


TRY/CATCH error handling works much the same way in SQL Server as it
does in a programming language. You place a statement in a BEGIN TRY
block followed by a BEGIN CATCH block. If the statement generates an
error, the statements in the BEGIN CATCH block execute until the END
CATCH is reached. The END TRY is skipped. If no error occurs, the CATCH
block is skipped entirely and processing continues to the END TRY block.

This example demonstrates a transaction that attempts to insert a duplicate


primary key value into the Customers table. The BEGIN TRY wraps the
transaction. If the insert succeeds, the transaction is committed and the PRINT
statement executed. If an error occurs, the transaction is rolled back in the
CATCH block and the message shown in Figure 23 is displayed.

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.

Microsoft SQL Server 2005 1-25


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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:

SELF: The user who created the stored procedure.


OWNER: The owner of the stored procedure.
'user_name': A specified user name.

Rules for permissions on underlying objects also apply to the entity specified
in the EXECUTE AS clause.

Using Snapshot Isolation


SQL Server 2005 introduces a new row versioning mechanism called snapshot
isolation, which is intended to improve performance by avoiding the reader-
writer blocking scenarios in the previous demonstration.

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.

Running CLR Code in SQL Server 2005


SQL Server 2005 overcomes the limitations of T-SQL by hosting the Common
Language Runtime (CLR) that runs .NET Framework 2.0 assemblies. The
.NET Framework is Microsoft’s premier Windows development framework,
supported by Visual Basic, C#, and, at last count, more than 40 other
programming languages. The CLR and Framework, along with full-featured
programming languages, provide a rich environment for building Windows
applications.

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#,

1-26 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
New Transact-SQL Features

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.

Transact-SQL has long been used for stored procedures, user-defined


functions, and triggers. You can use SQLCLR code for these uses as well as a
couple of others. Table 1 shows which kinds of code modules you can use with
each type of object.

Object Type T-SQL SQLCLR

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:

• Use T-SQL for data access code.


• Use SQLCLR code for processing-intensive code where you can take
advantage of the rich class libraries in the .NET Framework, or when
T-SQL is not an option, such as for aggregates and types.
• If you need to write both processor-intensive and data access code,
consider splitting up the work and using both T-SQL and SQLCLR for
the parts each is best at.
We recommend this bias: use T-SQL unless there is a clear reason to use
SQLCLR. If you follow just this guideline, you’ll use the right language most
of the time.

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).

Microsoft SQL Server 2005 1-27


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

Business Intelligence Services


SQL Server 2005 contains an impressive suite of Business Intelligence (BI)
tools, including Integration Services, Reporting Services, and Analysis
Services.

SQL Server Integration Services (SSIS)


Anyone who has been responsible for the management and administration of a
database knows that the ability to import and export data is essential. Microsoft
SQL Server 2005 introduced a whole new way of performing data migrations
with SQL Server Integration Services (SSIS).

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.

SQL Server Business Intelligence


Development Studio (BIDS)
Business Intelligence Development Studio is Microsoft Visual Studio 2005
with project templates that are specific to SQL Server 2005 business
intelligence. Business Intelligence Development Studio is the primary

1-28 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Business Intelligence Services

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.

The SQL Server Business Intelligence Development Studio (BIDS) is the


primary development tool for creating your own Integration Services packages
from scratch or editing existing package. It is actually a slightly scaled-down
version of Microsoft Visual Studio 2005, with all of the relevant development
and debugging tools in the full version of Visual Studio. In fact, if you install
Visual Studio 2005 either before or after you install SQL Server 2005, you’ll
actually be using the full version of Visual Studio when you start BIDS.

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.

2. Open the AWDataWarehouseRefresh package by selecting File|Open|


Project/Solution and use the Open File dialog box to navigate to the
location of the AWDataWarehouseRefresh.sln file. Double-click the file.

3. In the Solution Explorer window in Visual Studio, double-click


AWDWRefresh.dtsx.

Microsoft SQL Server 2005 1-29


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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.

1-30 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Business Intelligence Services

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 (SSAS)


SQL Server 2005 Analysis Services (SSAS) provides online analytical
processing (OLAP) and data mining functionality for business intelligence
solutions.

Analysis Services combines the best aspects of traditional OLAP-based


analysis and relational-based reporting by enabling developers to define a
single data model, called a Unified Dimensional Model (UDM) over one or
more physical data sources. All end user queries from OLAP, reporting, and
custom BI applications access the data in the underlying data sources through
the UDM, which provides a single business view of this relational data.

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.

Microsoft SQL Server 2005 1-31


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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.

1. Open the TestSSAS_Complete folder and double-click


TestSSAS_Complete.sln to open the solution in BIDS.

2. From the Build menu, select Deploy TestSSAS_Complete.

3. In the Solution Explorer, double-click the InternetSales_Complete


cube to open it in the Cube Designer.

4. Click the Browser tab, the last tab in the designer.

5. Expand Measures and Internet Sales. Drag Sales Amount to the


section of the browser labeled Drop Totals or Detail Fields Here.

6. Expand Customer, expand the Location folder, and drag the


Customer Location hierarchy to the section of the browser labeled
Drop Row Fields Here.

7. Expand Product and drag Product Line to the section of the browser
labeled Drop Column Fields Here.

8. Expand Order Date and drag Order Date.CalendarYear to the section


of the browser labeled Drop Filter Fields Here.

9. Now experiment with selecting different years to filter by and expand


some of the countries. The cube browser is shown in Figure 25.

1-32 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Business Intelligence Services

Figure 25. Browsing a cube.

Microsoft SQL Server 2005 1-33


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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.

1-34 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
Business Intelligence Services

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?

3. Name three new Transact-SQL features.

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?

6. What does SQL Server Analysis Services (SSAS) provide?

Microsoft SQL Server 2005 1-35


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.
A Tour of SQL Server 2005

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

3. Name three new Transact-SQL features.


CTEs, ranking functions, TOP(n), APPLY, PIVOT, FOR XML PATH,
and Try/Catch error handling

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

6. What does SQL Server Analysis Services (SSAS) provide?


Online analytical processing and data mining functionality for
business intelligence solutions

1-36 Microsoft SQL Server 2005


Copyright © by Application Developers Training Company
All rights reserved. Reproduction is strictly prohibited.

You might also like