Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Audit Trail in C#
Message
From
25/10/2007 23:45:30
 
 
To
25/10/2007 20:52:18
General information
Forum:
ASP.NET
Category:
Other
Miscellaneous
Thread ID:
01263434
Message ID:
01263940
Views:
9
Mike,

I'm familiar with the article you mentioned - it's not what you need.

This should be done in the database, using update triggers. That way, if other applications or other jobs modify the data, those changes can be logged as well.

I covered the basics of audit trail logging in one of my CoDe magazine articles a few years ago. Here's a link:

http://www.code-magazine.com/article.aspx?quickid=0503071&page=4

Here's an example....suppose you have a table called Price, and you want to log any changes on the Price and Descr columns. This example will write out any changes to a table called AuditLog. The Update trigger makes use of the INSERTED and DELETED system tables that store the "before" values and "after" values for rows affected by an UPDATE statement.
CREATE TRIGGER Upd_Price ON dbo.Price
FOR  UPDATE  
AS
   DECLARE @dLastUpdate DATETIME
   SET @dLastUpdate = GETDATE()

      -- Set the last Update for rows updated
   UPDATE Price 
      SET LastUpdate = @dLastUpdate
   FROM Price P
      JOIN Inserted I
       ON I.PrimaryKey = P.PrimaryKey 

      -- Write out to the Audit Log, for rows where Price changed 

   INSERT INTO AuditLog (TableName, PrimaryKey, LastUpdate, 
                          ColName, OldValue, NewValue, UserKey)
          SELECT 'PRICE' AS TableName, I.PrimaryKey, 
                 @dLastUpdate AS LastUpdate, 'Price' AS ColName,
                 CONVERT(CHAR(20),D.Price) AS OldValue, 
                 CONVERT(CHAR(20),I.Price) AS NewValue, 
                 I.UserKey
          FROM Inserted I
          JOIN Deleted D ON D.PrimaryKey = I.PrimaryKey
          WHERE I.Price <> D.Price

   -- Now check for any changes to the description
   INSERT INTO AuditLog (TableName, PrimaryKey, LastUpdate, 
                          ColName, OldValue, NewValue, UserKey)
          SELECT 'PRICE' AS TableName, I.PrimaryKey, 
                 @dLastUpdate AS LastUpdate, 'Descr' AS ColName,
                 D.Descr AS OldValue, 
                 I.Descr AS NewValue, 
                 I.UserKey
          FROM Inserted I
          JOIN Deleted D ON D.PrimaryKey = I.PrimaryKey
          WHERE I.Descr <> D.Descr
Now, that's just 1 example. You might need something more elaborate (there are 3rd party tools that allow you to generate audit trail scripts, or you could generate your own from the system information schema, or from your own custom application data dictionary). But regardless, it belongs in the update trigger.

Hope that helps...
Kevin
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform