Welcome!

.NET Authors: Sandi Mappic, Ivan Antsipau, JP Morgenthal, Yeshim Deniz, Carmen Gonzalez

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)

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.


@ThingsExpo Stories
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
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 Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...