473,804 Members | 3,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

typical audit trail ?

I tried to implement triggers for filling audit-trail table on this way.
Everything works fine as long as I don't update the primary key field value.
When I try to update PK value, an error occures.
The code is the following:

CREATE TRIGGER NameOfTheTrigge r
ON dbo.TableName FOR DELETE, INSERT, UPDATE
AS BEGIN
declare
@type varchar(10) ,
@UpdateDate datetime ,
@UserName varchar(128)

if exists (select * from inserted) and exists (select * from deleted)
select @type = 'UPDATE'
else if exists (select * from inserted)
select @type = 'INSERT'
else
select @type = 'DELETE'

select @UpdateDate = getdate() ,
@UserName = system_user
/* this code is repeting for every field in the table*/
if update (TableName) or @type = 'DELETE'
insert dbo.AUDIT_TRAIL (TableName, FieldName, OldValue, NewValue,
UpdateDate, UserName, type)
select 'TableName', convert(varchar (20), 'FieldName'),
convert(varchar (1000),d.FieldN ame), convert(varchar (1000),i.FieldN ame),
@UpdateDate, @UserName, @type
from inserted i
full outer join deleted d
on i.PrimaryKeyFie ldName = d.PrimaryKeyFie ldName
where (i.FieldName<> d.FieldName or (i.FieldName is null and d.FieldName is
not null) or (i.FieldName is not null and d.FieldName is null))

END

How to slve the problem with updated (changed) primary key values?
What is the typical code for audit-trail triggers?

Thanks.

Jul 23 '05 #1
2 2275
Hi

If your Primary Key is likely to change then you may want to create a
manufactured primary key that does not change.

Doing a lot of processing in your triggers may increate your transaction
times. To minimize this you can simply save copies of the inserted and
deleted tables and then do your processing later.

You should check @@ROWCOUNT as the first statement in your trigger to make
sure that some records have changed.

John

"Zlatko Matić" <zl***********@ sb.t-com.hr> wrote in message
news:d1******** **@ls219.htnet. hr...
I tried to implement triggers for filling audit-trail table on this way.
Everything works fine as long as I don't update the primary key field
value. When I try to update PK value, an error occures.
The code is the following:

CREATE TRIGGER NameOfTheTrigge r
ON dbo.TableName FOR DELETE, INSERT, UPDATE
AS BEGIN
declare
@type varchar(10) ,
@UpdateDate datetime ,
@UserName varchar(128)

if exists (select * from inserted) and exists (select * from deleted)
select @type = 'UPDATE'
else if exists (select * from inserted)
select @type = 'INSERT'
else
select @type = 'DELETE'

select @UpdateDate = getdate() ,
@UserName = system_user
/* this code is repeting for every field in the table*/
if update (TableName) or @type = 'DELETE'
insert dbo.AUDIT_TRAIL (TableName, FieldName, OldValue, NewValue,
UpdateDate, UserName, type)
select 'TableName', convert(varchar (20), 'FieldName'),
convert(varchar (1000),d.FieldN ame), convert(varchar (1000),i.FieldN ame),
@UpdateDate, @UserName, @type
from inserted i
full outer join deleted d
on i.PrimaryKeyFie ldName = d.PrimaryKeyFie ldName
where (i.FieldName<> d.FieldName or (i.FieldName is null and d.FieldName
is not null) or (i.FieldName is not null and d.FieldName is null))

END

How to slve the problem with updated (changed) primary key values?
What is the typical code for audit-trail triggers?

Thanks.


Jul 23 '05 #2
Zlatko Matić (zl***********@ sb.t-com.hr) writes:
I tried to implement triggers for filling audit-trail table on this way.
Everything works fine as long as I don't update the primary key field
value. When I try to update PK value, an error occures.
And the error message is?

As you don't disclose the error message, I cannot really say what you
should do to fix it. However, handling changes of primary keys in a
trigger offers some special challenges. In fact, this is only possible
for single-row operations. If you update the PK value for, say, ten
rows, there is no way to relate the rows in the deleted and inserted
tables to each other. (Unless there is alternate key that is immutable.)

So when you have:
from inserted i
full outer join deleted d
on i.PrimaryKeyFie ldName = d.PrimaryKeyFie ldName


and ten rows has changed, this result set gives you 20 rows, effective
as there had been an insert of 10 rows and delete or 10 others.

Another note: my experience is that inserted/deleted are not very
performant, and joining them can be really expensive. For this reason
I routinely insert the tables into table variables that I call
@inserted/@deleted and work with the table variables instead.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
7231
by: Raphael Gluck | last post by:
Hi, Is it possible for one to program one's pages as such that when a database table is updated over the web, via a form, that an e-mail confirmation is sent to a specified address, notifying the update has taken place? If so is there a tutorial out there that is easy to understand and implement? Thanks so much
2
1902
by: Keith | last post by:
Hi I am developing an ASP application which will interact with a SQL database. A requirement of the application is that there is a full audit trail of any modifications to data. I am struggling a bit to get my head round how to do this - just the concept.
3
6296
by: Zlatko Matić | last post by:
Hello. I tried to implement audit trail, by making an audit trail table with the following fileds: TableName,FieldName,OldValue,NewValue,UpdateDate,type,UserName. Triggers on each table were set to do the job and everything was fine except that in the audit trail you couldn't know which row exacltly was updated/inserted/deleted...Therefore I introduced 3 additional columnes (RowMark1, RowMark2, RowMark3) which should identify the...
6
5848
by: Parag | last post by:
Hello, I have been assigned the task to design the audit trail for the ASP.NET web application. I don't know what the best practices for such audit trails are. Our application one dedicated user name and password to perform the database operations. I need to capture all the operations which are performed on the database. Also I need to able to capture the operations which directly performed on the backend directly using the tools like...
0
1390
by: hary08 | last post by:
I have a module copied ftom this site, here it is: Option Compare Database Option Explicit Public Function AuditTrail() On Error GoTo Err_Audit_Trail 'ACC2000: How to Create an Audit Trail of Record Changes in a Form 'http://support.microsoft.com/default.aspx?scid=kb;en-us;197592
3
3785
by: hary08 | last post by:
im doing a database for Hospital Admission, I have a log in form which prompt user for a password. The source of log in is to look for the values in my Table tblEmployees and match user name and password entered.My case now is I have Audit Trail Module which keeps records of modifications and current user, I wanted my audit trail to log the current user based on who has log from based on my Log in Form.please help ty HERES THE CODE FOR ON...
2
3199
by: rockdc1981 | last post by:
I dont it is possible to put this codes together.. I want to prompt the user to save the record and at the same time have a log of audit trail. the codes work out fine separately. Code for Audit Trail Option Compare Database Const cDQ As String = """" Sub AuditTrail(frm As Form, recordid As Control) 'Track changes to data. 'recordid identifies the pk field's corresponding
6
2747
by: babamc4 | last post by:
I have a main form (mainformlung) with 5 subforms (followupacute, followuplate, biochemresults, haemresults and pftresults). I have copied Allen Browne's Audit Trail code (thanks to Allen Browne) and this is working great, edit, insert etc is working bar when I try to delete a record in one of my subforms (I'm in test stage at the mo) I get a run time error 3022 'The changes you requested to the table where not successful because they would...
4
8161
by: Emin | last post by:
Dear Experts, We need to design a database which has an audit trail for updates to a certain set of tables. The two main approaches I've seen for this include shadow tables (an extra table to track changes to the main table) and point-in-time architectures (having an "event date" and an "as known" date for every row). Can someone suggest the pros and cons of each approach or point me to relevant literature discussing the best approach?
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10326
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10075
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9143
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.