Welcome!

.NET Authors: ChandraShekar Dattatreya, Trevor Parsons, Peter Silva, Yeshim Deniz, Pat Romanski

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
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
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.
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
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...
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...

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

Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
"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.
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
The 3rd International @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 it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.