|
Comments
|
Today's Top SOA Links
Features A Summary of T-SQL Enhancements in SQL Server 2005
Taking a closer look at the updated features
By: Mujtaba Syed
Jul. 6, 2004 12:00 AM
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
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 * 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 * 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 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 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 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) Recursive Queries A CTE can be defined by using the WITH clause, as shown in the following code. WITH CustomerSales ([CustomerId, [TotalSales]) 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> 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 The XML query plan output lends itself to various kinds of advanced processing with XQuery, XSLT, DOM, and the CLR. Snapshot Isolation Level Data Types 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 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 DML with Output An example usage is as follows: UPDATE [Jobs] 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 BEGIN TRY 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 Reader Feedback: Page 1 of 1
Your Feedback
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week |
||||||||||||||||||||||||||||||||||||