Sign In | Feedback
Katie and Emil Logo
Our full time knowledge sharing hobby :)

Mini Learning Map

View Full Version

Overview: You might often perform deletes, inserts and updates using T-SQL and might have requirements to re-use the affected rows. With SQL Server 2008 and 2008 R2 you can easily do that using TSQL OUTPUT clause. OUTPUT gives you access to deleted, Inserted and Updated rows affected by your standard TSQL Code so you can retrieve old values . Below we created several examples each giving simple example for insert, delete and update.
Example: 1) Let's say you want to archive (move) data which is 90 days old.
2) You want to record field value changes.
3) Or simply want to get IDENTITY field ID eg. Insert row and recover id autogenerated by sql
Typical questions are:
  • How to get affected inserted rows. Tsql output into inserted rows
  • How to get affected deleted rows. T-sql output into delete
  • How to get affected updated rows. Tsql ouput into update
Syntax: Syntax is difficult to read so I'm not going to post it here basically when you use Insert Into, Delete From or Update you can add OUTPUT clause and specify values using Inserted.Column, Deleted.Column. Update is slightly different and you access OLD value using Deleted.Column and NEW value using Inserted.column. After that you just put INTO DestinationTable (columnA, columnB) or @TableVariable. Specifying column names is optional but good practise.

Enough of theory let's learn on examples!
Code Examples: 1) Archive Data. Move all Orders which have been placed over 90 days ago into Archived table.

DELETE FROM OrderTable
     OUTPUT Deleted.*
     INTO OrderTableArchived
WHERE DATEDIFF(D, MyDateField, GETDATE())>30


2) Record field value change. We will record Employee Salary change in this example.

UPDATE Employee
SET Salary = 50000
     OUTPUT Inserted.ID, Deleted.Salary, InsertedSalary, Getdate()
     INTO EmployeeSalaryHistory (ID, OldSalary, NewSalary, DateChanged)
WHERE ID = 7

Note: If the value for a particual field hasn't changed you can access it both using inserted.column and deleted.column


3) Insert row and Get Identity. Some of your may know that @@Identity or Scope_Identity() don't always return identity number we want and OUTPUT is strongly recommended method by Microsoft (See details)

Below I will slightly complicate example by using table variable to store the ID

DECLARE @InsertedRow AS TABLE (ID INT)


INSERT INTO Category (CategoryValue)
     OUTPUT Inserted.ID
     INTO @InsertedRow (ID)
VALUES ('T-SQL')

 


Did you find this page helpful?
Vote Yes! Yes! [+0]  |  Vote no! No? [-0]

Author: by Katie Glownia
Feedback