Thursday, June 2, 2011

SQL Server: Changed Data 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.

UPDATE:
USE AdventureWorks
GO
-- 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'
OUTPUT DELETED.AddressID, DELETED.AddressLine2,INSERTED.AddressLine2
INTO @UpdatedRecords
WHERE AddressID = 3

SELECT * FROM @UpdatedRecords

DELETE:
USE AdventureWorks
GO
-- 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)
,rowguid UNIQUEIDENTIFIER,ModifiedDate DATETIME)

DELETE FROM Person.Address
OUTPUT DELETED.*
INTO @DeletedRecords
WHERE AddressID = 3

SELECT * FROM @DeletedRecords

INSERT:
INSERT INTO Person.Address
(AddressLine1 , AddressLine2 ,City ,StateProvinceID ,PostalCode
 ,rowguid ModifiedDate)
OUTPUT INSERTED.*
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.

1 comment:

  1. I should add that the INTO clause is optional. You could just display the changed records by only using the OUTPUT clause.

    Regards,

    Syed Muhammad Yasir

    ReplyDelete

All suggestions are welcome