Feed on
Posts
Comments

If you have created Data Manipulation Language (DML) triggers in SQL Server, you are aware that you can retrieve information from special tables named inserted and deleted to view the new or previous version of rows. SQL Server 2005 introduces the OUTPUT keyword to provide this same functionality in a simple INSERT, UPDATE, and DELETE statement. You can use the OUTPUT keyword to return information about the results of a Transact-SQL statement into a table-valued variable.

You can include an OUTPUT clause in any DML statement with the following exceptions:

  • INSERT statements targeting views
  • DML operations with remote tables or views
  • DML operations on local or distributed partitioned views

This is and example how OUTPUT could be used:

– declare temp table to store the affected by products delete categories 
DECLARE @tmpAffectedCategories TABLE (category_id int)

– delete all products with product_type_id = 2
– and insert the product category_id into the temp table
DELETE FROM Products
    OUTPUT deleted.category_id INTO @tmpAffectedCategories
WHERE product_type_id = 2

– do something with the categories (ex: update the products count into Categories table). I will just list the data.
SELECT * FROM @tmpAffectedCategories

, ,
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • dzone
  • Netscape
  • digg
  • YahooMyWeb
  • Technorati

One Response to “Get the Affected Data with the OUTPUT Keyword”

  1. on 26 Nov 2006 at 4:08 pm Scott Whigham

    I think this is one of my favorite T-SQL additions/mods in SQL 2005. It’s soooo helpful :)

Trackback URI | Comments RSS

Leave a Reply

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a