Home > SQL Server Tips > > What's new with T-SQL in SQL Server 2005
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 


What's new with T-SQL in SQL Server 2005


by Jeremy Kadlec of Edgewood Solutions
10.19.2005
Rating: -3.00- (out of 5)


Expert advice on database development
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


Introduction

In preparation for the SQL Server 2005 launch this November, I recently conducted a survey of Edgewood Solutions' customers, asking them what they consider to be the most valuable features in Microsoft's new database release. One common response across all positions, industries, company sizes and years in business was T-SQL enhancements. These findings serve as a basis for the following tips on Transact-SQL programming extensions.

  • Error handling: TRY and CATCH
  • Transferring rows to columns: PIVOT and UNPIVOT
  • XML enhancements

Tip 1: Error handling with TRY and CATCH

Native error handling is the one area where T-SQL is often at fault compared to other languages. The TRY and CATCH paradigm, introduced in SQL Server 2005, is similar to many .NET languages. This will greatly improve the confidence in SQL Server's error handling with an approach that is familiar to many developers and DBAs.

BEGIN TRY
SELECT 1/0;
END TRY

BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

Transferring rows to columns with PIVOT and UNPIVOT

A developer at a health care company that I work with growls like a dog every time her reporting users want to shift rows to columns. It is not a nice conversation. She has to write some tricky code that requires more than a few CPU cycles to give the users the data they need based on the state reporting requirements. These painful conversations are a thing of the past with the introduction of the PIVOT and UNPIVOT commands in SQL Server 2005. These commands enable the quick shifting of rows to columns and vice versa with few coding changes.

USE AdventureWorks;
GO
SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5
FROM 
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [164], [198], [223], [231], [233] )
) AS pvt
ORDER BY VendorID

Source: Using PIVOT and UNPIVOT, SQL Server 2005 Books Online

XML enhancements

XML has become prevalent in transferring data across many heterogeneous environments and between many Microsoft applications; the SQL Server 2005 XML features improve the inherent capabilities to create, store, transport and query XML data. It is now possible to achieve the following natively in SQL Server:

  • Create an XML schema that can be referenced in a table's column.
CREATE XML SCHEMA COLLECTION [ . ]sql_identifier AS Expression
  • Create a native data type for table creation with pointers out to the XML Schema Collection, which are separate data pages from the base table, similar to a BLOB in SQL Server 2000.
CREATE TABLE Orders
(OrderID int PRIMARY KEY NOT NULL, 
OrderDetailsID int NOT NULL,
OrderDate datetime NOT NULL,
…
XMLOrder xml NOT NULL)
  • Create a variable as the XML data type for stored procedure or ad-hoc transactions.
DECLARE @OrdersSchema xml
…
CREATE XML SCHEMA COLLECTION OrdersSchema AS @OrdersSchema
  • Improve the access to the XML data by creating primary and secondary indexes.
CREATE PRIMARY XML INDEX PXML_Orders_OrderID
ON OrdersSchema.Orders (OrderID);
GO

CREATE XML INDEX SXML_Order_OrderDetailsID
ON OrdersSchema.Orders (OrderDetailsID)
USING XML INDEX PXML_Orders_OrderID FOR PATH ;
GO
  • Query XML data via a simple SELECT statement to return the XML as a portion of the result set with the remainder of the columns in the table.
SELECT * 
FROM Orders
WHERE OrderID = 123

Conclusion

T-SQL takes a big step forward in SQL Server 2005 by expanding the capabilities of the traditional relational database management system. These items are just the tip of the iceberg with additional T-SQL improvements and overhauls to DTS -- now SQL Server Integration Services, Analysis Services, Reporting Services, etc. These are challenging, yet exciting, times to learn about all of the new capabilities SQL Server has to offer.

About the author: Jeremy Kadlec is the principal database engineer at Edgewood Solutions, a technology services company delivering professional services and product solutions for Microsoft SQL Server. He has authored numerous articles and delivers frequent presentations at regional SQL Server users groups and nationally at SQL PASS. Kadlec is the SearchSQLServer.com Performance Tuning expert. Ask him a question here.


More information from SearchSQLServer.com

  • Ask the Experts: Run a T-SQL query to loop through all databases
  • Fast Guide: Stored procedures
  • Topic: Research T-SQL best practices


  • Rate this Tip
    To rate tips, you must be a member of SearchSQLServer.com.
    Register now to start rating these tips. Log in if you are already a member.




    Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


    RELATED CONTENT
    SQL/Transact SQL (T-SQL)
    Physical data storage in SQL Server 2005 and 2008
    SQL Server 2008 data types: Datetime, string, user-defined and more
    SQL Server and data manipulation in T-SQL
    Enforcing data integrity in a SQL Server database
    Supertype and subtype tables in SQL Server
    Using SQL Server datetime functions GETDATE, DATENAME and DATEPART
    Ordering the results of a SQL query
    How to use SQL Server 2008 hierarchyid data type
    SQL Server data conversions from date/time values to character types
    SQL and SQL Server Tutorial and Reference Guide
    SQL/Transact SQL (T-SQL) Research

    SQL Server 2005 (Yukon)
    SQL Server consolidation: Why it's an optimization technique
    Parent-child dimensions in SQL Server 2005 with Analysis Services MDX
    Using SQL Server datetime functions GETDATE, DATENAME and DATEPART
    SSIS error message due to installation problem on SQL Server 2005
    SQL Server data conversions from date/time values to character types
    Basics for working with DATETIME and SMALLDATETIME in SQL Server 2005
    How to configure Database Mail in SQL Server 2005 to send mail
    How to use rank function in SQL Server 2005
    Manage traces in SQL Server 2005 Analysis Services with XMLA commands
    Tutorial: SQL Server 2005 Analysis Services
    SQL Server 2005 (Yukon) Research

    RELATED GLOSSARY TERMS
    Terms from Whatis.com − the technology online dictionary
    ACID  (SearchSQLServer.com)
    commit  (SearchSQLServer.com)
    DAO  (SearchSQLServer.com)
    fetch  (SearchSQLServer.com)
    OLE DB  (SearchSQLServer.com)
    query  (SearchSQLServer.com)
    SQL  (SearchSQLServer.com)
    T-SQL  (SearchSQLServer.com)

    RELATED RESOURCES
    2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
    Search Bitpipe.com for the latest white papers and business webcasts
    Whatis.com, the online computer dictionary

    DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.

    HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
    About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
    SEARCH 
    TechTarget provides enterprise IT professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective IT purchase decisions and managing their organizations' IT projects - with its network of technology-specific Web sites, events and magazines.

    TechTarget Corporate Web Site  |  Media Kits  |  Reprints  |  Site Map




    All Rights Reserved, Copyright 2005 - 2008, TechTarget | Read our Privacy Policy
      TechTarget - The IT Media ROI Experts