|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.
You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ...
Apr. 29, 2016 09:15 PM EDT Reads: 245
The IoT has the potential to create a renaissance of manufacturing in the US and elsewhere. In his session at 18th Cloud Expo, Florent Solt, CTO and chief architect of Netvibes, will discuss how the expected exponential increase in the amount of data that will be processed, transported, stored, and accessed means there will be a huge demand for smart technologies to deliver it. Florent Solt is the CTO and chief architect of Netvibes. Prior to joining Netvibes in 2007, he co-founded Rift Technol...
Apr. 29, 2016 09:00 PM EDT Reads: 1,514
Join IBM June 8 at 18th Cloud Expo at the Javits Center in New York City, NY, and learn how to innovate like a startup and scale for the enterprise. You need to deliver quality applications faster and cheaper, attract and retain customers with an engaging experience across devices, and seamlessly integrate your enterprise systems. And you can't take 12 months to do it.
Apr. 29, 2016 04:30 PM EDT Reads: 1,763
Machine Learning helps make complex systems more efficient. By applying advanced Machine Learning techniques such as Cognitive Fingerprinting, wind project operators can utilize these tools to learn from collected data, detect regular patterns, and optimize their own operations. In his session at 18th Cloud Expo, Stuart Gillen, Director of Business Development at SparkCognition, will discuss how research has demonstrated the value of Machine Learning in delivering next generation analytics to im...
Apr. 29, 2016 03:45 PM EDT Reads: 1,595
This is not a small hotel event. It is also not a big vendor party where politicians and entertainers are more important than real content. This is Cloud Expo, the world's longest-running conference and exhibition focused on Cloud Computing and all that it entails. If you want serious presentations and valuable insight about Cloud Computing for three straight days, then register now for Cloud Expo.
Apr. 29, 2016 03:30 PM EDT Reads: 1,656
So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, will provide tips on how to be successful in large scale machine lear...
Apr. 29, 2016 02:45 PM EDT Reads: 842
IoT device adoption is growing at staggering rates, and with it comes opportunity for developers to meet consumer demand for an ever more connected world. Wireless communication is the key part of the encompassing components of any IoT device. Wireless connectivity enhances the device utility at the expense of ease of use and deployment challenges. Since connectivity is fundamental for IoT device development, engineers must understand how to overcome the hurdles inherent in incorporating multipl...
Apr. 29, 2016 02:30 PM EDT Reads: 1,404
The paradigm has shifted. A Gartner survey shows that 43% of organizations are using or plan to implement the Internet of Things in 2016. However, not just a handful of companies are still using the old-style ad-hoc trial-and-error ways, unaware of the critical barriers, paint points, traps, and hidden roadblocks. How can you become a winner? In his session at @ThingsExpo, Tony Shan will present a methodical approach to guide the holistic adoption and enablement of IoT implementations. This ov...
Apr. 29, 2016 02:00 PM EDT Reads: 1,540
We’ve worked with dozens of early adopters across numerous industries and will debunk common misperceptions, which starts with understanding that many of the connected products we’ll use over the next 5 years are already products, they’re just not yet connected. With an IoT product, time-in-market provides much more essential feedback than ever before. Innovation comes from what you do with the data that the connected product provides in order to enhance the customer experience and optimize busi...
Apr. 29, 2016 02:00 PM EDT Reads: 831
The IETF draft standard for M2M certificates is a security solution specifically designed for the demanding needs of IoT/M2M applications. In his session at @ThingsExpo, Brian Romansky, VP of Strategic Technology at TrustPoint Innovation, will explain how M2M certificates can efficiently enable confidentiality, integrity, and authenticity on highly constrained devices.
Apr. 29, 2016 02:00 PM EDT Reads: 975
Artificial Intelligence has the potential to massively disrupt IoT. In his session at 18th Cloud Expo, AJ Abdallat, CEO of Beyond AI, will discuss what the five main drivers are in Artificial Intelligence that could shape the future of the Internet of Things. AJ Abdallat is CEO of Beyond AI. He has over 20 years of management experience in the fields of artificial intelligence, sensors, instruments, devices and software for telecommunications, life sciences, environmental monitoring, process...
Apr. 29, 2016 01:30 PM EDT Reads: 782
SYS-CON Events announced today that Ericsson has been named “Gold Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. Ericsson is a world leader in the rapidly changing environment of communications technology – providing equipment, software and services to enable transformation through mobility. Some 40 percent of global mobile traffic runs through networks we have supplied. More than 1 billion subscribers around the world re...
Apr. 29, 2016 01:00 PM EDT Reads: 755
SYS-CON Events announced today that Stratoscale, the software company developing the next generation data center operating system, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Stratoscale is revolutionizing the data center with a zero-to-cloud-in-minutes solution. With Stratoscale’s hardware-agnostic, Software Defined Data Center (SDDC) solution to store everything, run anything and scale everywhere...
Apr. 29, 2016 01:00 PM EDT Reads: 1,482
Angular 2 is a complete re-write of the popular framework AngularJS. Programming in Angular 2 is greatly simplified – now it's a component-based well-performing framework. This immersive one-day workshop at 18th Cloud Expo, led by Yakov Fain, a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay, will provide you with everything you wanted to know about Angular 2.
Apr. 29, 2016 12:30 PM EDT Reads: 1,637
SYS-CON Events announced today that Men & Mice, the leading global provider of DNS, DHCP and IP address management overlay solutions, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. The Men & Mice Suite overlay solution is already known for its powerful application in heterogeneous operating environments, enabling enterprises to scale without fuss. Building on a solid range of diverse platform support,...
Apr. 29, 2016 11:45 AM EDT Reads: 2,224
In his session at @ThingsExpo, Chris Klein, CEO and Co-founder of Rachio, will discuss next generation communities that are using IoT to create more sustainable, intelligent communities. One example is Sterling Ranch, a 10,000 home development that – with the help of Siemens – will integrate IoT technology into the community to provide residents with energy and water savings as well as intelligent security. Everything from stop lights to sprinkler systems to building infrastructures will run ef...
Apr. 29, 2016 11:30 AM EDT Reads: 488
You deployed your app with the Bluemix PaaS and it's gaining some serious traction, so it's time to make some tweaks. Did you design your application in a way that it can scale in the cloud? Were you even thinking about the cloud when you built the app? If not, chances are your app is going to break. Check out this webcast to learn various techniques for designing applications that will scale successfully in Bluemix, for the confidence you need to take your apps to the next level and beyond.
Apr. 29, 2016 11:15 AM EDT Reads: 1,418
Manufacturers are embracing the Industrial Internet the same way consumers are leveraging Fitbits – to improve overall health and wellness. Both can provide consistent measurement, visibility, and suggest performance improvements customized to help reach goals. Fitbit users can view real-time data and make adjustments to increase their activity. In his session at @ThingsExpo, Mark Bernardo Professional Services Leader, Americas, at GE Digital, will discuss how leveraging the Industrial Interne...
Apr. 29, 2016 10:00 AM EDT Reads: 1,114
Whether your IoT service is connecting cars, homes, appliances, wearable, cameras or other devices, one question hangs in the balance – how do you actually make money from this service? The ability to turn your IoT service into profit requires the ability to create a monetization strategy that is flexible, scalable and working for you in real-time. It must be a transparent, smoothly implemented strategy that all stakeholders – from customers to the board – will be able to understand and comprehe...
Apr. 29, 2016 09:30 AM EDT Reads: 996
Increasing IoT connectivity is forcing enterprises to find elegant solutions to organize and visualize all incoming data from these connected devices with re-configurable dashboard widgets to effectively allow rapid decision-making for everything from immediate actions in tactical situations to strategic analysis and reporting. In his session at 18th Cloud Expo, Shikhir Singh, Senior Developer Relations Manager at Sencha, will discuss how to create HTML5 dashboards that interact with IoT devic...
Apr. 29, 2016 09:00 AM EDT Reads: 840