SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to use the OUTPUT clause for audit trail?

Execute the following Microsoft SQL Server T-SQL script in SSMS Query Editor to create an audit log table and populate it with an OUTPUT clause when salary hourly rate changes for employees.

-- OUTPUT clause for auditing INSERT, UPDATE, DELETE, or MERGE statement

USE AdventureWorks2008;

-- T-SQL create audit trail table for Human Resources

CREATE TABLE HumanResources.Audit (

  AuditID       INT    IDENTITY ( 1 , 1 )    PRIMARY KEY,

  ChangeDate    DATETIME,

  EmployeeID    INT,

  ChangeItem    VARCHAR(64),

  PreviousValue VARCHAR(64),

  CurrentValue  VARCHAR(64))

GO

 

-- Increase pay rate 10% for employee 173

UPDATE HumanResources.EmployeePayHistory

SET    Rate = Rate * 1.1

OUTPUT      getdate(), convert(VARCHAR,DELETED.BusinessEntityID),

            'Hourly Rate', convert(VARCHAR,DELETED.Rate),

            convert(VARCHAR,INSERTED.Rate)

INTO HumanResources.Audit ( ChangeDate,EmployeeID,ChangeItem,

                                          PreviousValue,CurrentValue )

WHERE  BusinessEntityID = 173;

GO

-- Reverse the change since this is just a demo

UPDATE HumanResources.EmployeePayHistory

SET    Rate = Rate / 1.1

OUTPUT      getdate(), convert(VARCHAR,DELETED.BusinessEntityID),

            'Hourly Rate', convert(VARCHAR,DELETED.Rate),

            convert(VARCHAR,INSERTED.Rate)

INTO HumanResources.Audit ( ChangeDate,EmployeeID,ChangeItem,

                                          PreviousValue,CurrentValue )

WHERE  BusinessEntityID = 173;

GO

 

SELECT *

FROM   HumanResources.Audit

GO

/*

AuditID     ChangeDate              EmployeeID  ChangeItem  PreviousValue     CurrentValue

1           2009-12-21 14:35:02.690 173   Hourly Rate 9.50  10.45

2           2009-12-21 14:35:02.760 173   Hourly Rate 10.45 9.50

*/

DROP TABLE HumanResources.Audit

GO

Related articles:

OUTPUT Clause (Transact-SQL)


Trigger Alternatives in SQL Server - OUTPUT Clause

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.