|By Mujtaba Syed||
|July 6, 2004 12:00 AM EDT||
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
- Recursive queries
- XML showplan
- Snapshot isolation level
- Data types
- DDL triggers
- DML with output
- Exception handling
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.
PIVOT (SUM ([UnitsSold]) FOR [Year] IN (, )) 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.
UNPIVOT (UnitsSold FOR [Year] in (, )) 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.
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)
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)
ORDER BY [TimeStamp]
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])
[CustomerId], SUM ([UnitPrice] * [Quantity] * (1 - [Discount]))
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:
<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]
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.
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.
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
RAISERROR ('No drops allowed', 10, 1)
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:
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 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:
-- SQL statements
-- SQL statements
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.
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.
|CuriousTom 10/11/07 03:25:06 PM EDT|
|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.
The emerging Internet of Everything creates tremendous new opportunities for customer engagement and business model innovation. However, enterprises must overcome a number of critical challenges to bring these new solutions to market. In his session at @ThingsExpo, Michael Martin, CTO/CIO at nfrastructure, outlined these key challenges and recommended approaches for overcoming them to achieve speed and agility in the design, development and implementation of Internet of Everything solutions wi...
Aug. 24, 2016 12:30 AM EDT Reads: 1,809
Cloud computing is being adopted in one form or another by 94% of enterprises today. Tens of billions of new devices are being connected to The Internet of Things. And Big Data is driving this bus. An exponential increase is expected in the amount of information being processed, managed, analyzed, and acted upon by enterprise IT. This amazing is not part of some distant future - it is happening today. One report shows a 650% increase in enterprise data by 2020. Other estimates are even higher....
Aug. 24, 2016 12:00 AM EDT Reads: 2,759
I wanted to gather all of my Internet of Things (IOT) blogs into a single blog (that I could later use with my University of San Francisco (USF) Big Data “MBA” course). However as I started to pull these blogs together, I realized that my IOT discussion lacked a vision; it lacked an end point towards which an organization could drive their IOT envisioning, proof of value, app dev, data engineering and data science efforts. And I think that the IOT end point is really quite simple…
Aug. 23, 2016 11:30 PM EDT Reads: 2,202
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. 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 - comp...
Aug. 23, 2016 11:00 PM EDT Reads: 3,477
"My role is working with customers, helping them go through this digital transformation. I spend a lot of time talking to banks, big industries, manufacturers working through how they are integrating and transforming their IT platforms and moving them forward," explained William Morrish, General Manager Product Sales at Interoute, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
Aug. 23, 2016 09:00 PM EDT Reads: 2,959
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 19th International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo Silicon Valley Call for Papers is now open.
Aug. 23, 2016 08:45 PM EDT Reads: 3,730
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
Aug. 23, 2016 08:15 PM EDT Reads: 1,621
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
Aug. 23, 2016 07:00 PM EDT Reads: 3,786
19th Cloud Expo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterpri...
Aug. 23, 2016 05:00 PM EDT Reads: 2,880
SYS-CON Events announced today that Venafi, the Immune System for the Internet™ and the leading provider of Next Generation Trust Protection, will exhibit at @DevOpsSummit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Venafi is the Immune System for the Internet™ that protects the foundation of all cybersecurity – cryptographic keys and digital certificates – so they can’t be misused by bad guys in attacks...
Aug. 23, 2016 02:15 PM EDT Reads: 2,497
Smart Cities are here to stay, but for their promise to be delivered, the data they produce must not be put in new siloes. In his session at @ThingsExpo, Mathias Herberts, Co-founder and CTO of Cityzen Data, will deep dive into best practices that will ensure a successful smart city journey.
Aug. 23, 2016 01:45 PM EDT Reads: 1,400
SYS-CON Events announced today that 910Telecom will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and ...
Aug. 23, 2016 01:15 PM EDT Reads: 1,710
DevOps at Cloud Expo, taking place Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. 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 dev...
Aug. 23, 2016 12:00 PM EDT Reads: 2,008
In today's uber-connected, consumer-centric, cloud-enabled, insights-driven, multi-device, global world, the focus of solutions has shifted from the product that is sold to the person who is buying the product or service. Enterprises have rebranded their business around the consumers of their products. The buyer is the person and the focus is not on the offering. The person is connected through multiple devices, wearables, at home, on the road, and in multiple locations, sometimes simultaneously...
Aug. 23, 2016 09:30 AM EDT Reads: 2,215
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
Aug. 23, 2016 06:45 AM EDT Reads: 2,027
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Aug. 23, 2016 06:45 AM EDT Reads: 1,622
Akana has announced the availability of version 8 of its API Management solution. The Akana Platform provides an end-to-end API Management solution for designing, implementing, securing, managing, monitoring, and publishing APIs. It is available as a SaaS platform, on-premises, and as a hybrid deployment. Version 8 introduces a lot of new functionality, all aimed at offering customers the richest API Management capabilities in a way that is easier than ever for API and app developers to use.
Aug. 23, 2016 03:30 AM EDT Reads: 1,370
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abil...
Aug. 23, 2016 01:30 AM EDT Reads: 1,802
With so much going on in this space you could be forgiven for thinking you were always working with yesterday’s technologies. So much change, so quickly. What do you do if you have to build a solution from the ground up that is expected to live in the field for at least 5-10 years? This is the challenge we faced when we looked to refresh our existing 10-year-old custom hardware stack to measure the fullness of trash cans and compactors.
Aug. 23, 2016 12:45 AM EDT Reads: 1,567
SYS-CON Events announced today that CDS Global Cloud, an Infrastructure as a Service provider, will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. CDS Global Cloud is an IaaS (Infrastructure as a Service) provider specializing in solutions for e-commerce, internet gaming, online education and other internet applications. With a growing number of data centers and network points around the world, ...
Aug. 22, 2016 01:30 PM EDT Reads: 2,142