T-SQL Enhancements
T-SQL Enhancements
Table of Contents
T-SQL Enhancements
In this lab, you will familiarize your self with the new and enhanced
Objectives features of T-SQL.
After completing this lab, you will be able to:
NOTE: This lab focuses on the
concepts in this module and as a Use the new PIVOT and UNPIVOT operators
result may not comply with Use Recursive Query Expressions
Microsoft security
recommendations.
Create triggers that are invoked by Data Definition Language
(DDL) events
NOTE: The SQL Server 2005 labs Handle Exceptions in T-SQL
are based on beta builds of the
product. The intent of these labs is
to provide you with a general feel of
some of the planned features for
the next release of SQL Server. As
with all software development
projects, the final version may differ
from beta builds in both features
and user interface. For the latest
details on SQL Server 2005, please
visit
http://www.microsoft.com/sql/2005/.
Many enhancements have been made to T-SQL and this lab will
Scenario provide exercises to help you understand how these enhancements
work and how you may leverage them in your environment. The lab
exercises will cover usage of new data types, recursive query
expressions, triggers, exception handling and the new
PIVOT/UNPIVOT operators.
Prior basic working experience with SQL Server 7.0 or SQL
Prerequisites Server 2000
Familiarity with T-SQL
Familiarity with SQL Server Management Studio or completion
of the lab on SQL Server Management Studio
60 Minutes
Estimated Time to Complete
This Lab
Page 3 of 18
T-SQL Enhancements
Lab Setup
Tasks Detailed Steps
1. Log in. 1. Log in using the Administrator user account. The password is Pass@word1.
Page 4 of 18
T-SQL Enhancements
Exercise 1
PIVOT and UNPIVOT Operators
Scenario
It is often useful to view relational data in multiple dimensions. For some time now, SQL Server has supported the
CUBE and ROLLUP operators. These operators allow data to be viewed in different dimensions and allow
aggregations to be displayed along those dimensions.
The 2005 release of SQL Server introduces support for the PIVOT and UNPIVOT operators. These operators are
less complex to understand and implement than CUBE and ROLLUP, while still allowing the flexibility to view
data along different dimensions. For example, with the PIVOT operator it is almost effortless to rotate rows into
columns to look at Product data along different dimensions such as supplier, current inventory, and amounts.
In this exercise, you will learn how to use the PIVOT and UNPIVOT operators, apply them in several queries, and
compare their output.
USE AdventureWorks
GO
INSERT SalesOrderTotalsMonthly
Page 5 of 18
T-SQL Enhancements
To see the capabilities of the PIVOT operator, you are creating a worktable
containing the customer ID, the month an order was taken, and the subtotal due on
the order. This table will be used in subsequent queries.
2. Select the statements you just typed.
3. Press F5 to execute the statements.
4. Create a query that 1. In the query editor, type the following query that will pivot the table so that the
uses the PIVOT sales for each month are output by customer.
operator.
SELECT * FROM SalesOrderTotalsMonthly
PIVOT (SUM(SubTotal) FOR OrderMonth IN
([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) AS a
INSERT SalesOrderTotalsYearly
SELECT CustomerID, YEAR(OrderDate), SubTotal
FROM Sales.SalesOrderHeader
WHERE CustomerID IN (1,2,4,6,35)
Page 6 of 18
T-SQL Enhancements
INSERT YearlySalesPivot
SELECT * FROM SalesOrderTotalsYearly
PIVOT (SUM(SubTotal) FOR CustomerID IN ([1], [2], [4], [6])) AS a
Page 7 of 18
T-SQL Enhancements
Page 8 of 18
T-SQL Enhancements
Exercise 2
Common Table Expressions and Recursive Queries
Scenario
A Common Table Expression (CTE) is a temporary result set derived from a simple query. A CTE can be used in
many of the same ways you use a derived table. CTEs can also contain references to themselves. This allows
database developers to write recursive queries. CTEs can also be used in place of views.
Page 9 of 18
T-SQL Enhancements
4. Aggregate the CTEs. 1. In the CTE_REC.sql script, type the following query.
Page 10 of 18
T-SQL Enhancements
INSERT CarParts
VALUES (1, 'Body', 'Door', 4)
INSERT CarParts
VALUES (1, 'Body', 'Trunk Lid', 1)
INSERT CarParts
VALUES (1, 'Body', 'Car Hood', 1)
INSERT CarParts
VALUES (1, 'Door', 'Handle', 1)
INSERT CarParts
VALUES (1, 'Door', 'Lock', 1)
INSERT CarParts
VALUES (1, 'Door', 'Window', 1)
INSERT CarParts
VALUES (1, 'Body', 'Rivets', 1000)
INSERT CarParts
VALUES (1, 'Door', 'Rivets', 100)
INSERT CarParts
VALUES (1, 'Door', 'Mirror', 1)
Page 11 of 18
T-SQL Enhancements
Page 12 of 18
T-SQL Enhancements
Exercise 3
DDL Triggers and EventData()
Scenario
In previous versions of SQL Server, you can define AFTER triggers only for Data Manipulation Language (DML)
statements — INSERT, UPDATE, and DELETE. SQL Server 2005 allows you to define triggers for Data Definition
Language (DDL), and you can optionally define the scope to be an entire database or even an entire server, not just a
single object.
Within a trigger, you can get data regarding the event that initiated it by accessing the EventData() function. This
function returns a variable that uses the new xml data type. Each event’s schema inherits the Server Events base
schema.
In this exercise you will create DDL triggers and use EventData() to capture information about the calling event.
The code above first creates a table, and then creates a DDL trigger that will fire
when a user attempts to drop any database table.
2. Select the statements you just typed.
3. Press F5 to execute the query.
4. In the DDL_EventData.sql script, type the following query.
Page 13 of 18
T-SQL Enhancements
The DDL trigger returns an error message and prevents any table in the database
from being dropped by rolling back the transaction.
3. Alter the DDL 1. In the DDL_EventData.sql script, type the following code.
Trigger to use
EventData().
CREATE TABLE EventLog
(
PostTime datetime,
DBUser nvarchar(100),
Event nvarchar(100),
TSQL nvarchar(2000)
)
GO
The EventData() function returns information about server or database events. This
function returns an XML-typed variable.
2. Select the statements you just typed.
3. Press F5 to execute the query.
First, the code creates a log table to catch the event information. Second, the code
alters the trigger to write event data to the log table. The code stores the time, user,
event, and T-SQL associated with the event in the log table. Finally, the code tests
the altered trigger. Since the altered trigger does not include ROLLBACK, the
“foo” table is successfully deleted.
4. Drop worktables and 1. In the query editor, type the following DDL to drop the worktables you created.
trigger.
DROP TRIGGER safety
ON DATABASE
DROP TABLE DDLTest
Page 14 of 18
T-SQL Enhancements
Page 15 of 18
T-SQL Enhancements
Exercise 4
Event Handling
Scenario
Previous versions of SQL Server require that you include error-handling code after every statement that might
produce an error. SQL Server 2005 introduces two new constructs, TRY and CATCH. These two constructs allow
you to handle transaction abort errors that would otherwise have resulted in the termination of a batch, provided that
those errors do not cause severance of the connection.
In this exercise, you will learn how to use TRY and CATCH blocks in T-SQL.
USE AdventureWorks
GO
Page 16 of 18
T-SQL Enhancements
3. Invoke a run-time When the SET XACT_ABORT option is set to OFF, only the Transact-SQL
error. statement that raised the error is rolled back and the transaction continues
processing.
1. In the TRY_CATCH.sql script, type the following query.
SELECT *
FROM ExceptionT1
GO
SELECT *
FROM ExceptionT2
Page 17 of 18
T-SQL Enhancements
SELECT *
FROM ExceptionT1
GO
SELECT *
FROM ExceptionT2
Page 18 of 18