Welcome!

.NET Authors: David Fletcher, Srinivasan Sundara Rajan, Pat Romanski, Tad Anderson, Adine Deford

Related Topics: .NET

.NET: Article

A Summary of T-SQL Enhancements in SQL Server 2005

Taking a closer look at the updated features

Microsoft is releasing a new version of SQL Server after a gap of five years. This version (SQL Server 2005) introduces a horde of new attention-grabbing features like native XML storage and querying (using XQuery), CLR integration, SQL Web Services, query notifications, and the Service Broker. Apart from these high-profile enhancements, SQL Server 2005 also comes with improved T-SQL support.

Overview of T-SQL Enhancements
Most of SQL Server 2005's T-SQL enhancements focus on offering greater expressiveness to queries. We will look at each of these individual enhancements in detail. The list of enhancements includes:

  • Relational operators
  • TOP
  • Recursive queries
  • XML showplan
  • Snapshot isolation level
  • Data types
  • DDL triggers
  • DML with output
  • Exception handling
Relational Operators
SQL Server 2005 introduces three new relational operators: PIVOT, UNPIVOT, and APPLY.

The PIVOT operator is very similar to the TRANSFORM operator that Microsoft Access provides. It is used to rotate rows into columns. The best way to learn about PIVOT is through an example (see Figure 1).

This table lists the sales of a Toyota dealership. Notice that some models have more than one row for a particular year. Now we apply the following SELECT query (which uses the PIVOT operator) to the SalesSummary table. The result we get is shown in Figure 2.

SELECT *
FROM [SalesSummary]
PIVOT (SUM ([UnitsSold]) FOR [Year] IN ([2003], [2004])) AS [T]

The table was PIVOTed on the year column. Notice how the unique year values have taken the shape of columns and the corresponding number of units sold have been summed up.

The UNPIVOT operator does the opposite of what PIVOT does - it rotates columns into rows. Let's say we want to rotate the table in Figure 2 (let's call it Year WiseSalesSummary), so that the number of units sold is displayed for each year. All we have to do is apply the following SELECT query. The result of the UNPIVOT operation is shown in Figure 3.

SELECT *
FROM [YearWiseSalesSummary]
UNPIVOT (UnitsSold FOR [Year] in ([2003], [2004])) AS T

The APPLY is another new operator available in SQL Server 2005. When used in the FROM clause, it invokes a table-valued UDF for each row of a table. The UDF can optionally use the columns of the table as arguments.

Let's say we have a table called StudentScores that has the Math, Physics, and Chemistry scores of a bunch of students (see Figure 4).

Now, create the Calculate-Grade function, which takes the subject scores of each of the student one at a time and returns the grade of the student.


CREATE FUNCTION [CalculateGrade] 
(@math AS INT, @physics AS INT, @chemistry AS INT)
RETURNS  @GradeTable TABLE ([Grade] CHAR (1))
AS
BEGIN
	DECLARE @average FLOAT
	SET @average = (@math + @physics + @chemistry) / 3
	IF @average >= 90
		INSERT INTO @GradeTable VALUES ('A')
	ELSE IF @average >=80
		INSERT INTO @GradeTable VALUES ('B')
	ELSE IF @average >=70
		INSERT INTO @GradeTable VALUES ('C')
	ELSE
		INSERT INTO @GradeTable VALUES ('F')
	RETURN
END

The following query uses the APPLY relational operator to apply the CalculateGrade function on every row of the StudentScores table. We also pass the Math, Physics, and Chemistry scores to the CalculateGrade function.

SELECT [Name], I.Grade
FROM [StudentScores] AS O
CROSS APPLY CalculateGrade ([Math], [Physics], [Chemistry]) AS I

Figure 5 is an illustrative example of the APPLY operator. There are several ways (many of them better than using the APPLY operator) to achieve the same result.

TOP
In SQL Server, a SELECT query can use the TOP option to specify the number of rows that should be returned. The argument to TOP was a constant value of type BIGINT. The TOP option can also be qualified with the PERCENT keyword to specify that a percentage of the total number of rows should be returned by a SELECT query. The argument in this case was a constant value of type FLOAT.

In SQL Server 2005, an argument can be specified using an expression or a query, the only condition being that both should result in a value that is of the correct type.

For example, the following query returns the latest 10 orders from the Orders table in the Northwind database.

DECLARE @NO_OF_ROWS BIGINT
SET @NO_OF_ROWS = 10

SELECT TOP (@NO_OF_ROWS)
*
FROM [Orders]
ORDER BY [OrderDate] DESC

In SQL Server 2005, the TOP keyword can also be used with INSERT, UPDATE, and DELETE commands. Using TOP to do batch inserts, updates, or delete is more optimal than using the older SET ROWCOUNT method.

An example of using TOP with the DELETE operator would be the following query, which purges the oldest 10,000 rows from TempTable.

DELETE TOP (10000)
FROM [TempTable]
ORDER BY [TimeStamp]

Recursive Queries
SQL Server 2005 introduces Common Table Expressions (CTEs) that allow you to write named table expressions that persist for the duration of a query. The functionality of CTEs is somewhere between derived tables and views.

A CTE can be defined by using the WITH clause, as shown in the following code.

WITH CustomerSales ([CustomerId, [TotalSales])
AS
(
SELECT
[CustomerId], SUM ([UnitPrice] * [Quantity] * (1 - [Discount]))
AS [TotalSales]
FROM [Orders] AS [O] INNER JOIN
[Order Details] AS [OD]
ON [O].[OrderId] = [OD].[OrderId]

GROUP BY [CustomerId]
)
SELECT * FROM [CustomerSales]

This query creates a non-recursive CTE called CustomerSales that has two columns: CustomerId and TotalSales. The CTE gets all unique customer ids and the total sales made to them.

The primary purpose of having CTEs is to support recursion. Recursive CTEs improve readability and manageability of complex SQL statements. Recursive CTEs have the ability to traverse recursive hierarchies in a single query. A typical scenario where one would use a recursive CTE would be when a table has a self-referential constraint.

The recursive form of a CTE is as shown:

<Non-recursive SELECT>
UNION ALL
<SELECT referencing the CTE>

The recursion terminates when the second SELECT block produces an empty result.

The following recursive CTE prints out the name of all employees and their managers found in the Northwind database. The results are shown in Figure 6.


WITH EmployeeManagerCTE ([EmployeeId], [EmployeeName], [ManagerName])
AS
(
	SELECT 
		[EmployeeId], 
		[LastName] + ', ' + [FirstName], 
		[LastName] + ', ' + [FirstName] 
	FROM employees 
	WHERE [ReportsTo] IS NULL

	UNION ALL

	SELECT 
		[E1].[EmployeeId], 
		[E1].[LastName] + ', ' + [E1].[FirstName], 
		[E2].[EmployeeName]
	FROM [Employees] [E1] INNER JOIN 
	[EmployeeManagerCTE] [E2]
	ON [E1].[ReportsTo] = [E2].[EmployeeId]

)
SELECT * FROM [EmployeeManagerCTE]

XML Showplan
SQL Server 2005 has the facility to output a query plan as XML that uses a documented XML schema and carries more information than SQL Server 2000 textual or graphical formats.

The XML query plan output lends itself to various kinds of advanced processing with XQuery, XSLT, DOM, and the CLR.

Snapshot Isolation Level
SQL Server 2000 supports four isolation levels: read uncommitted, read committed, repeatable read, and serializable. SQL Server 2005 introduces a new snapshot isolation level. The snapshot isolation level is based on optimistic concurrency. It holds onto a snapshot of committed data from when the transaction started, allowing non-blocking reads to take place.

Data Types
SQL Server 2005 introduces a few new data types: XML, VARCHAR (MAX), NVARCHAR (MAX), and VARBINARY (MAX).

The XML data type is a first-class data type in SQL Server 2005 and can be used to define columns, variables, and parameters for stored procedures and user-defined functions. The XML data type can be optionally constrained by an XML schema. SQL Server 2005 also provides built-in XQuery support to query XML data.

The VARCHAR (MAX), NVARCHAR (MAX), and VARBINARY (MAX) data types can store up to 2GB of data and provide alternatives to the existing TEXT, NTEXT, and IMAGE data types respectively.

DDL Triggers
SQL Server 2005 has extended traditional triggers and enabled them to be fired for DDL operations like CREATE, ALTER, and DROP. These triggers are created, altered, and dropped using similar Transact-SQL syntax as that for standard triggers.

DDL triggers apply to all commands of a single type across a database or server and they execute only after completion of a DDL statement (although they can roll back the transaction to before the execution of the DDL statement that caused their triggering). DDL triggers cannot be INSTEAD OF triggers.

DDL triggers help to enforce development rules and standards for objects in a database; protect from accidental drops; help in object check-in/checkout, source versioning, and log management activities.

An example of a DDL trigger that prevents the dropping of a table is as shown:

CREATE TRIGGER OnDropTable ON DATABASE FOR DROP_TABLE
AS
    RAISERROR ('No drops allowed', 10, 1)
ROLLBACK

DML with Output
SQL Server 2005 introduces the OUTPUT clause that returns inserted, updated, or deleted rows as part of a DML operation. The OUPUT clause can be used with INSERT, DELETE, and UPDATE statements. The "DELETED" and "INSERTED" pseudo-tables can be used to get the pre- and post-operation values.

An example usage is as follows:

UPDATE [Jobs]
SET [Status] = 'Done'
OUTPUT DELETED.*, INSERTED.*
WHERE [Status] = 'In progress'

The DELETED values are not available for INSERT operations while the INSERTED values are not available for the DELETE operations. Both the INSERTED and the DELETED values are available for UPDATE operations.

Exception Handling
Exception handling can now be done in SQL Server 2005 by using the very well-known TRY/CATCH paradigm. All errors that set the @@error variable will now throw exceptions. The syntax of using exception handling is as follows:

BEGIN TRY
    -- SQL statements
END TRY
BEGIN CATCH
    -- SQL statements
END CATCH

TRY/CATCH blocks can also be nested. Error details are available inside the CATCH block through a set of functions - error_number (), error_message (), error_severity (), and error_state (). RAISERROR can be used to re-throw and exception from within a CATCH block.

Conclusion
SQL Server 2005 enhances T-SQL on a number of fronts - it introduces new and important data types, brings more power and expressiveness to SQL querying, provides more procedural capabilities, and improves parallelism.

More Stories By Mujtaba Syed

Mujtaba Syed works as a software architect with Marlabs Inc. He is an MCSD
(early achiever) and loves to speak about and write on Microsoft .NET. Mujtaba has been programming the Microsoft .NET Framework since its beta 1 release. His current interests are focused on Longhorn.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
CuriousTom 10/11/07 03:25:06 PM EDT

Good One

sudhakar 08/28/04 05:58:42 AM EDT

Sorry, i take back my words.

I could find the images, it would have been better to embed the images in the article instead of providing links to them at the end of it.

sudhakar 08/28/04 05:36:01 AM EDT

I didnt find any figures (which have been refered) in this article which made the examples given for each feature quite difficult to understand. The pictorial representation of query results would have been very helpful.

Pls. send me an alert to my mailid if you update this article with relevent figures.

@ThingsExpo Stories
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...
In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect at GE, and Ibrahim Gokcen, who leads GE's advanced IoT analytics, focused on the Internet of Things / Industrial Internet and how to make it operational for business end-users. Learn about the challenges posed by machine and sensor data and how to marry it with enterprise data. They also discussed the tips and tricks to provide the Industrial Internet as an end-user consumable service using Big Data Analytics and Industrial Cloud.