SQL Server: Data Change Capture without Using Trigger

Most of SQL Server users think that trigger is the only place where we can use DELETED and INSERTED virtual tables to capture data change in result of any INSERT, UPDATE or DELETE statement.

Old and new data values affected by DML operations can be captured by using OUTPUT clause along with virtual DELETED and INSERTED tables. Here are few examples which will be helpful to understand usage of this OUTPUT clause in simple insert, update and delete queries.
USE AdventureWorks
— Create a table variable to hold updated rows
DECLARE @UpdatedRecords TABLE
(AddressID INT, OldAddressLine2 VARCHAR(50), NewAddressLine2 VARCHAR(50))
UPDATE Person.Address
SET AddressLine2 = Silver Street new’
INTO @UpdatedRecords
WHERE AddressID = 3
SELECT * FROM @UpdatedRecords
USE AdventureWorks
— Create a table variable to hold deleted rows
DECLARE @DeletedRecords TABLE
(AddressID INT, AddressLine1 VARCHAR(50), AddressLine2 VARCHAR(50)
 ,City VARCHAR(50),StateProvinceID INT,PostalCode VARCHAR(10)
DELETE FROM Person.Address
INTO @DeletedRecords
WHERE AddressID = 3
SELECT * FROM @DeletedRecords
INSERT INTO Person.Address
(AddressLine1 , AddressLine2 ,City ,StateProvinceID ,PostalCode
 ,rowguid ModifiedDate)
INTO @InsertedRecords
VALUES (‘3rd BlackStone rd’,‘wst.51’,‘Bothell’,78,98010,NEWID(),GETDATE()
Note: This method is applicable for SQL Server 2005 and above versions.

Posted on June 2, 2011, in Sql Server 2005, Sql Server 2008, SQL Server Basics, TSQL Tips n Tricks. Bookmark the permalink. 1 Comment.

  1. Yes! I have recently used the OUTPUT statement in stored procedures to store the new and modified data into temp table before later inserting into audit tables. It’s a very useful feature, introduced in SQL 2005.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: