Preview Content - log in or become a member

T-SQL Output Clause

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.

Below are several examples when you could use OUTPUT Clause:

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 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!
 

Are you a member? Log In

Membership plans from just 6.00 USD*

* Currency: USD (US Dollar )

Plans:
Bronze
6.00 USD
Silver
9.00 USD
Gold
12.00 USD
6 Courses
T-SQL (3), SSRS (1), SSIS(1), Excel (1)
Watch Video
75 Mini Courses
T-SQL (34), SSRS (7), SSIS(16), + more
300+ videos and 300+ Articles
38
(part of
Courses)
Progress Tracking
21 Interview Q&As pages
T-SQL (8), SSRS (3), SSIS(4), Other (6)
Forum
11 Webinar Recordings
T-SQL (1), SSRS (9), Career(1)
1 DIY Project (beta)
70-461 Tests
Watch Video
60 days, 100% Money Back Guarantee
Instant Activation
Duration:
Bronze
Silver
Gold
Valid for: 1 month 6.00 USD
sign up
9.00 USD
sign up
12.00 USD
sign up
Valid for: 3 months
10% off
16.00 USD
sign up
24.00 USD
sign up
32.00 USD
sign up
Valid for: 6 months
20% off
28.00 USD
sign up
43.00 USD
sign up
57.00 USD
sign up
Valid for: 1 year
30% off
50.00 USD
sign up
75.00 USD
sign up
100.00 USD
sign up
Valid for: 2 years
40% off
86.00 USD
sign up
129.00 USD
sign up
172.00 USD
sign up
Valid for: lifetime
50% off
108.00 USD
sign up
162.00 USD
sign up
216.00 USD
sign up


Did you find this page useful?
+5  |  -0
(5 Votes)