Home > SQL Server Tips > Microsoft SQL Server > New T-SQL features in SQL Server 2005
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

MICROSOFT SQL SERVER

New T-SQL features in SQL Server 2005


Eric Johnson
08.16.2007
Rating: -4.33- (out of 5)


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


Have you experienced the flexibility of the new T-SQL features in SQL Server 2005? If not, take a look because you'll want to become familiar with four especially noteworthy development features: error handling, ROW_NUMBER Function, DDL triggers and CLR.

Error handling has always been a tricky part of T-SQL development. You once had to manually check for errors after running each statement and handle them on a case-by-case basis. Transaction management was also a chore because you had to figure out the state of your transactions and roll them back or commit them as appropriate. With SQL Server 2005, Microsoft has provided us with newer, more robust error handling capabilities by adding Try...Catch blocks to T-SQL.

Exception handling is simple really; when something unplanned occurs during the execution of your code, i.e., an exception, you need to have a routine to handle that exception. How you handle the exception is really up to you as the developer. In order to add exception handling to your T-SQL code, use Try…Catch blocks.

If you have used Visual Studio recently, you are probably familiar with the concept of Try…Catch blocks. The implementation in T-SQL is similar, but in T-SQL, it actually has fewer options than the full blown implementation you would encounter in Visual Studio. To use Try…Catch, put the T-SQL you want to run inside of a Try block. If an error with a severity of 10 or higher occurs during the execution of the Try code, execution is passed to exception handling code in a Catch block. The basic construct is shown below.

 
BEGIN TRY
   (T-SQL Code Goes Here)
END TRY
BEGIN CATCH
   (Exception Handling Code Goes Here)
END CATCH

ROW_NUMBER function

SQL Server 2005 introduces us to the ROW_NUMBER function. Have you ever had the need to number the rows of a result set in a query? Every now and again, you will find that being able to number the rows is a useful thing. Previously, you had to do something tricky, like create a temp table with an identity column and then insert the results of your SELECT into the temp table. Now, using the ROW_NUMBER function, you can have row numbers added to an additional column of your result set. In order to get row numbers, you simply include the ROW_NUMBER function as one of the columns in your SELECT statement. You must also include the OVER statement in order to tell SQL Server how you want to append the row number.

SELECT ROW_NUMBER() OVER(ORDER BY employee_id) AS 'Row Number', * from
dbo.employee


RESULTS

Row Number employee_id Firstname Lastname soc_sec
1 5623222 Tim Jones 123-65-8745
2 5632111 Rob Kinkad 456-69-8754
3 6365666 Jim Miller 236-56-8989
4 7563333 Joe Roberts 564-89-5555

This query will return all employees and a number that indicates which row each record is in. The OVER statement forces SQL Server to add the row number based on the employee_id column. In other words, the row number is generated as though data were sorted by employee_id. This is an important point, as you can still change the sort order of the SELECT. Take the following query as an example:


SELECT ROW_NUMBER() OVER(ORDER BY employee_id) AS 'Row Number', * from
dbo.employee
ORDER BY soc_sec


RESULTS

Row Number employee_id Firstname Lastname soc_sec
1 5623222 Tim Jones 123-65-8745
3 6365666 Jim Miller 236-56-8989
2 5632111 Rob Kinkad 456-69-8754
4 7563333 Joe Roberts 564-89-5555

Notice in the second result set that the data is sorted by the social security number, but the row number is still built as though the data were sorted by employee_id.

Data Definition Language (DDL) triggers

Triggers have long been a part of T-SQL features and now their usefulness has been expanded. In SQL Server 2005, Microsoft included Data Definition Language (DDL) triggers. DDL triggers, like the name implies, can be configured to fire when DDL actions take place in SQL Server. DDL statements consist of any command you would issue to modify, create or delete objects in a SQL Server database. Generally, most DDL statements begin with CREATE, ALTER or DROP. Using DDL triggers, you could choose to run a script any time a user issues a DROP TABLE statement.

A fairly common practice in older versions of SQL Server was to create schema
More on T-SQL in SQL Server 2005:
  • T-SQL error handling with Try…Catch blocks

  • XML AUTO vs. T-SQL commands

  • Top 10 T-SQL tips
  • binding views on all your tables in production to prevent accidentally dropping a production table. Since the view was schema bound, drops would fail. This required administrators to take an extra step in order to drop a table; they first had to drop a view. Now, you can accomplish the same goal using DDL triggers and the solution is less of a workaround. You can set up a DDL trigger first on ALTER or DROP TABLE statements, which prevents the statement from completing. This, again, adds the extra layer of protection, since the trigger needs to be dropped or disabled before changes are made.

    DDL triggers also have some very obvious auditing uses. Triggers can be used to log the details any time a table, stored procedure or view is added, modified or dropped. No more guesswork around who added a new object. Really, the sky is the limit when it comes to things you can do with DDL triggers.

    Common Language Runtime integration

    SQL Server 2005's new T-SQL features are complete with the capability to write and use Common Language runtime (CLR) modules that can be integrated into your database. CLR integrations allow it to write triggers, stored procedures, functions, aggregate functions and types in a .NET language. Before you go crazy and start rewriting everything in CLR, be warned: Take some time to carefully consider which objects should use CLR. Certain tasks lend themselves well to CLR modules and others don't. If you need to interact with the OS, Common Language Runtime is probably the way to go. Additionally, complex algorithms for string parsing or sorting will likely perform better if done in CLR. However, standard T-SQL statements, such as INSERT, UPDATE and DELETE, are better left in T-SQL. Just use common sense and performance test anything you write.

    The complexities of writing CLR are outside the scope of this tip, but I will give you the ten thousand foot view. You need to use Visual Studio to write stored procedures in the .NET language of your choice. Once you write it, you attach the code as an assembly and then create the stored procedure, function, trigger or type – and then point it at the assembly. Beyond that, it can be called or used just as traditional T-SQL objects would be used. Get an overview of the differences between CLR routines vs. T-SQL stored procedures in our expert answer section.

    There have been a good number of changes made to SQL Server 2005, and not just in the area of T-SQL. We certainly haven't covered everything in this short tip, but these have been some of the most hyped new additions. Take some time and explore these new features -- and you had better hurry. The next version of SQL Server is just around the corner and I am sure it to will be packed with more new toys to play with.


    ABOUT THE AUTHOR:   
    Eric Johnson (MCSE, MCITP: Database Administrator, MCSD) is a co-founder of Consortio Services and the primary Database Technologies Consultant. He has delivered numerous SQL Server training classes and webcasts as well as presentations at national technology conferences. He has presented at TechMentor on SQL Server 2005 Replication, Reporting Services, and Integration Services. Eric is active in the local SQL Server Community, serving as the president of the Colorado Springs SQL Server Users Group.
    Copyright 2007 TechTarget


    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
    Enforcing data integrity in a SQL Server database
    SQL Server and data manipulation in T-SQL
    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

    Microsoft SQL Server
    SQL Server errors, failures and other problems fixed from the trenches
    SQL Server consolidation: Why it's an optimization technique
    Can you shrink your SQL Server database to death?
    Using SQL Server datetime functions GETDATE, DATENAME and DATEPART
    Tuning SQL Server performance via memory and CPU processing
    Get SQL Server log shipping functionality without Enterprise Edition
    SQL Server 2008 backup compression pros and cons
    How to use SQL Server 2008 hierarchyid data type
    Tuning SQL Server performance via disk arrays and disk partitioning
    Should you upgrade to SQL Server 2005 or SQL Server 2008?

    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