Audit Triggers Problem

Sep 23, 2004

Im using triggers to track changes Insert/Update/Deletes on my DB tables and they work for when i am manually adding/editing and deleting a single records.

The problem arises in that I have an asset/inventory management app that dumps lots of details into my DB tables at once each time its run.
Not all of the tables are updated and data cannot be completely inserted.

This is the trigger i have been using - could someone tell me how to modify it to work.



/*
This trigger audit trails all changes made to a table.
It will place in the table Audit all inserted, deleted, changed columns in the table on which it is placed.
It will put out an error message if there is no primary key on the table
You will need to change @TableName to match the table to be audit trailed
*/

ALTER trigger tr_TableName
on dbo.TableName for insert, update, delete
as

declare @bit int ,
@field int ,
@maxfield int ,
@char int ,
@fieldname varchar(128) ,
@TableName varchar(128) ,
@PKCols varchar(1000) ,
@sql varchar(2000),
@UpdateDate varchar(21) ,
@Action nvarchar(50) ,
@HostName nvarchar(50),
@PKFieldName varchar (1000)


IF EXISTS(SELECT * FROM inserted)
IF EXISTS(SELECT * FROM deleted)
--update = inserted and deleted tables both contain data
BEGIN
SET @Action = 'UPDATE'
SELECT @DeviceID = (SELECT inserted.DeviceID FROM inserted INNER JOIN deleted ON inserted.deviceID = deleted.deviceid)
END
ELSE

--insert = inserted contains data, deleted does not
BEGIN
SET @Action = 'INSERT'
select @DeviceID = (SELECT DeviceID from inserted)
END
ELSE
--delete = deleted contains data, inserted does not
BEGIN
SET @Action = 'DELETE'
select @DeviceID = (SELECT DeviceID from deleted)
END

select @TableName = 'TableName'

-- date
select @HostName = host_name(),
@UpdateDate = convert(varchar(8), getdate(), 112) + ' ' + convert(varchar(12), getdate(), 114),
--@DeviceID,
@PKFieldName=(select top 1 c.COLUMN_NAME fromINFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE c where pk.TABLE_NAME = @TableName
andCONSTRAINT_TYPE = 'PRIMARY KEY'andc.TABLE_NAME = pk.TABLE_NAME and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME)

-- get list of columns
select * into #ins from inserted
select * into #del from deleted

-- Get primary key columns for full outer join
select@PKCols = coalesce(@PKCols + ' and', ' on') + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
fromINFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = @TableName
andCONSTRAINT_TYPE = 'PRIMARY KEY'
andc.TABLE_NAME = pk.TABLE_NAME
andc.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

if @PKCols is null
begin
raiserror('no PK on table %s', 16, -1, @TableName)
return
end

select @field = 0, @maxfield = max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName
while @field < @maxfield
begin
select @field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION > @field
select @bit = (@field - 1 )% 8 + 1
select @bit = power(2,@bit - 1)
select @char = ((@field - 1) / 8) + 1
--if substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0
begin
select @fieldname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION = @field
select @sql = 'insert LITE_Inventory (TableName, FieldName, OldValue, NewValue, UpdateDate, Action, Host, PkFieldName, DeviceID)'
-- select @sql = 'insert LITE_Inventory (TableName, FieldName, OldValue, NewValue, UpdateDate, Action, Host, PkFieldName)'
select @sql = @sql + ' select ''' + @TableName + ''''
select @sql = @sql + ',''' + @fieldname + ''''
select @sql = @sql + ',convert(varchar(1000),d.' + @fieldname + ')'
select @sql = @sql + ',convert(varchar(1000),i.' + @fieldname + ')'
select @sql = @sql + ',''' + @UpdateDate + ''''
select @sql = @sql + ',''' + @Action + ''''
select @sql = @sql + ',''' + @HostName + ''''
select @sql = @sql + ',''' + @PKFieldName + ''''
select @sql = @sql + ' from #ins i full outer join #del d'
select @sql = @sql + @PKCols
select @sql = @sql + ' where i.' + @fieldname + ' <> d.' + @fieldname
select @sql = @sql + ' or (i.' + @fieldname + ' is null and d.' + @fieldname + ' is not null)'
select @sql = @sql + ' or (i.' + @fieldname + ' is not null and d.' + @fieldname + ' is null)'

exec (@sql)
end
end

View 3 Replies


ADVERTISEMENT

Triggers Audit

Jul 20, 2005

I need audit triggers that change columns value in the same recordthat fire trigger.I need how to do..Thanks..

View 11 Replies View Related

Audit Trail Triggers

Jul 23, 2005

Hello.I tried to implement audit trail, by making an audit trail table with thefollowing fileds:TableName,FieldName,OldValue,NewValue,UpdateDate,t ype,UserName.Triggers on each table were set to do the job and everything was fine exceptthat in the audit trail you couldn't know which row exacltly wasupdated/inserted/deleted...Therefore I introduced 3 additional columnes(RowMark1, RowMark2, RowMark3) which should identify theinserted/updated/deleted row.For example, RowMark1 could be foreign key, RowMark2 could be primary key,and RowMark3 could be autonumber ID.But, when I have several rows updated, RowMark columnes values are identicalin all rows in the audit trail table! What is wrong with my code, and how tosolve it ?Thank you in advance!CREATE TRIGGER Trigger_audit_TableNameON dbo.TableNameFOR DELETE, INSERT, UPDATEAS BEGINdeclare @type nvarchar(20) ,@UpdateDate datetime ,@UserName nvarchar(100),@RowMark1 nvarchar (100),@RowMark2 nvarchar (100),@RowMark3 nvarchar (100)if exists (select * from inserted) and exists (select * fromdeleted)select @type = 'UPDATE',@RowMark1=d.ForeignKeyField,@RowMark2=d.PrimaryKey Field,@RowMark3=d.IDfrom deleted delse if exists (select * from inserted)select @type = 'INSERT',@RowMark1=i.ForeignKeyField,@RowMark2=i.PrimaryKey Field,@RowMark3=i.IDfrom inserted ielseselect @type = 'DELETE',@RowMark1=d.ForeignKeyField,@RowMark2=d.PrimaryKey Field,@RowMark3=d.IDfrom deleted dselect @UpdateDate = getdate() ,@UserName = USER/*The following code is repeated for every field in a table*/if update (FieldName) or @type = 'DELETE'insert dbo.AUDIT_TRAIL (TableName, FieldName, OldValue, NewValue,UpdateDate, UserName, type,RowMark1,RowMark2,RowMark3)select 'Descriptive Table Name', convert(nvarchar(100), 'DescriptiveField Name'),convert(nvarchar(1000),d.FieldName),convert(nvarchar(1000),i.FieldName),@UpdateDate, @UserName, @type, @RowMark1, @RowMark2,@RowMark3from inserted ifull outer join deleted don i.ID = d.IDwhere (i.FieldName <> d.FieldNameor (i.FieldName is null and d.FieldName is not null)or (i.FieldName is not null and d.FieldName is null))END

View 3 Replies View Related

Audit Tables And Triggers

Jul 23, 2005

Dear Group,I would like to create an audit table that is created with a trigger thatreflects all the changes(insert, update and delete) that occur in table.Say I have a table withSubject_ID, visit_number, dob, weight, height, User_name, inputdateThe audit table would have .Subject_ID, visit_number, dob, weight, height, User_name, inputdate,edit_action, edit_reason.Where the edit_action would be insert, update, delete; the edit_reason wouldbe the reason given for the edit.Help with this would be great, since I am new to the world of triggers.Thanks,Jeff

View 1 Replies View Related

Audit/history Without Use Of Triggers?

Jul 20, 2005

HiI am looking to implement an audit/history table/tables but am lookingat doing this without the use of triggers.The reason for doing this is that the application is highlytransactional and speed in critical areas is important.I am worried that triggers would slow things down.I am more used to other database where by there is a utility to "dump"the contents of the transaction logs and use this for auditingpurposes. However SQL Server does not have this functionality (unlessthere is a sql server tool - 3rd party that I do not know about)Has anyone implemented something similar? Or used/using a 3rd partytool that will do this job.Effectively the clients would like to "look" at what happened - say 15minutes ago.thanksjohn

View 3 Replies View Related

DDL Triggers To Audit Permission/ Role Chg

Jan 11, 2008

I have ddl triggers in place to watch what people do to our various database environments. I can see when someone does something to a login, but I can't tell what was done. I have a sneaky someone creating accounts with sysadmin privs and I want to catch the source. I also want to know when someone changes a password on a sql account. Does anyone know of a way to do this?

___________________________
Geek At Large

View 6 Replies View Related

Audit Tables, Delete Triggers, And Asp.net

Jul 20, 2005

i'm in a bit of a bind at work. if anyone could help, i'd greatlyappreciate it.i have a web app connecting to a sql server using sql serverauthentication. let's say, for example, my login/password isdbUser/dbUser. the web app however, is using windows authentication.so if I am logged into the network as 'DOMAINEric', when I access myweb app, my web app knows that I am 'DOMAINEric'. but to the sqlserver db, I am user 'dbUser'.now, i for each table i have, i need to implement an audit table torecord all updates, inserts, deletes that occur against it. i wasgoing to do so with triggers. this is all fine for selects, inserts,and updates. for each table, i have an updatedby and an updatedate.for example, let's say i have a table:create table blah(id int,col1 varchar(10),updatedby varchar(30),updatedate datetime)and corresponding audit table:create audit_blah(id int,blah_id int,blah_col1 varchar(10),blah_updatedby varchar(1),blah_updatedate datetime)for update and insert triggers, i can know what to insert into theupdatedby column of audit_blah because it's in a corresponding row inblah. my web app knows what user is accessing the application, andcan insert that name into blah. blah's trigger will then insert thatname into audit_blah.however, in the case of a delete, i'm not passing in an 'updatedby',because i'm deleting. in this situation, how can the trigger knowwhat user is deleting? the db only knows that sql user 'dbUser' isdeleting, but doesn't know that 'dbUser' is deleting on behalf of'DOMAINEric'. is there any way for my app to inform the trigger toaccess my windows identity without having a corresponding row in thetable from which to pull that info?obviously, i could have each of my app's users log into SQL serverthrough Windows authentication; then i could just use SYSTEM_USER.but let's say, for performance's sake, it'd be better for me to useone sql server login. (i believe one user works better for connectionpooling purposes.) is there a way to get around this?(i'm hoping a built-in function exists that solves all my problems.)suggestions? resources?any help would be great appreciated.happy turkeys.Eric

View 2 Replies View Related

SQL Audit : CLR Trigger Vs TSQL Triggers

Nov 26, 2007

Hi,
I am trying to figure out which of these option is best suited for auditing. Although each one of them has its own pros/cons.
CLR trigger is easy to write and can be made generic so that it fits for any table required to be audited.
I tried both the option in test database and i found the CLR trigger performed poorly.
Results were :
For table A (3 columns) with TSQL trigger took less than a sec for 2500 sequential inserts.
While table B (3 columns) having same structure with CLR trigger took more than 20 sec for 2500 sequential inserts.

Has anybody done performance comparision of this 2 approaches ?
Please share results if any.

I wanted to validate that is my findings correct so that i select best optimized approach.

Thanks,
Jignesh

View 1 Replies View Related

Using Triggers To Track Changes In A Single Audit Table

Feb 6, 2006

Hi,

I am looking to track any changes made to any table within a db into a single audit table which will hold as fields: the table that has been updated/inserted, the field that was changed, its primary key, the old value and the new value specific to that field, and the date it was updated/inserted.

From what I have read, it does not look like this is possible with a trigger on table as it is not row specific and that I might have to control this from the business layer (vb.net). I am correct in this assumption, or is there a way of tracking specific data changes through triggers.

thanks

Welly

View 5 Replies View Related

Using Service Broker With History/Audit Triggers

Jul 13, 2007

Hello. Taking a typical use having a history table, maintained from a base table via triggers... Trying to see how/if that can be done using the SQl 2005 Service Broker method, with messaging? The thought is that if we can do the History table updates ASYNC, the user will not wait more than setting up the Broker message queue. I saw this article about something similar, but it deals with LOGON triggers.



http://www.sqlservercentral.com/columnists/FVandeputte/sqlserver2005logontriggers.asp



I'd think you can't do Hisotyr type triggers, with a message, because wouldn't you need to write all teh INSERTED/UPDATED data somewhere anyways? and there could be multiple rows affected in any given insert/update/delete, so could you even pass that thru to a Broker?



Anyone know of any references to using Broker Services for sending INSERTED/UPDATED data along for Historical versioning?



Also, was curious about error handling, because say you update teh base table, and then a problem occurs, and the Hisotry table is not updated. I want them in sync. Where is the message data stored, and is it accesible even if teh server reboots before the data is RECEIVED from teh QUEUE?



Thanks, Bruce

View 7 Replies View Related

Database Audit Specification To Audit Select On Certain User And Table

Nov 1, 2014

I have made a server security audit and specify from database audit specification to audit "select" on a certain user and on a certain table. I logged in by this user and made the select statement..when i run this query

"select * from sys.fn_get_audit_file('d:Auditaudit1*',null,null)"

It return a value at which time the query has done

after 15 minutes i repeated the same action, i run the audit query and the same result is showed off on the panel.is it suppose to return a list of values by how many times this user has made the select statement on that table ? for example at 5:00 pm then 6:00 pm and so on

View 1 Replies View Related

Audit Logon / Audit Logoff Problem With SQL 2K

Jan 18, 2006

I need help...here is the problem.Last weekend, the servers in our datacenter where moved around. After thismove, and maybe coincidental, 1 server is performing very poor. Afterrunning a trace with SQL Profiler, I saw the problem which was laterconfirmed with another tool for SQL server performance monitoring. It seemsthat all connections to the SQL server (between 200 - 400) are doing a login/ logout for each command that they process. For example, the user'sconnection will login, perform a SELECT, and then logout. This is not a..NET application. The client software was not changed, it is still thesame. The vendor has said that it is not supposed to do that, it issupposed to use 1 connection that log's on in the morning and logs off atthe end of the day or whenever the user exits. 1 user may have severalconnections to the database.At times, the server is processing over 250 login / logouts (avgeraged for30 second period). Has anyone seen this problem? I have the server inAUDIT FAILUREs only. The server has become very unresponsive, things thattook 3 seconds now take over 15 seconds.Any ideas???

View 6 Replies View Related

Multiple Triggers On A Table Or Encapsulated Triggers

May 12, 2008

This isn€™t an problem as such, it€™s more of a debate.

If a table needs a number of update triggers which do differing tasks, should these triggers be separated out or encapsulated into one all encompassing trigger. Speaking in terms of performance, it doesn€™t make much of an improvement doing either depending upon the tasks performed. I was wondering in terms of maintenance and best practice etc. My view is that if the triggers do totally differing tasks they should be a trigger each on their own.

www.handleysonline.com

View 12 Replies View Related

Audit

Nov 9, 2005

I want to register into a table each time a user creates, modifies or deletes any object in a database. It's not possible to add a trigger to the sysobjects table. What can I do?

View 1 Replies View Related

C2 Audit

Jan 30, 2008

Hello,

I enabled the C2 Audit option for my SQL server and it is working allright. i am trying to figure out how can i configure the audit to run for specific databases/tables only. I have several databases on the server but I just want to audit one table in one database for PCI compliance rules.
Any recommendations?

Thanks,
Tony

View 1 Replies View Related

Audit Query

Feb 29, 2008

Good morning,
 Im having a little problem with this report I need to generate, so I thought I would ask for some advice.
I have 2 tables. The 1st is the actual table and the 2nd is the log table (Employee; Employee_log). the '_log' table is an image of the Employee table except it has 4 extra fields (recID,  last_updated_employee_id, operation and operation_date) recid being the PK of the log table.
I need to generate a report that contains some thing like the following:



Table_Name

Column_Name

Old_Value

New_Value

Employee_Modifier

Operation

Operation_Date



Employee

LastName

Reid

Blevins

Jessica Bluff


UPDATE

2/2/2008



Employee

FirstName

Bison

Blison

Jessica Bluff

UPDATE


2/1/2008



Employee

EmployeeID



1234

Jessica Bluff

INSERT

2/1/2008



Employee

EmployeeID



75

Bill Thompson

DELETE


1/28/2008


 To do this, I compare the Employee table to the Employee_log table. If I find changes (the two columns do not equal), I add that columnName and the column value for the regular table(new_value) and the column value for the log table(old value).  If anyone has a solution or some sql to help me out, it would be greatly appreciated.  (A query that will give me each columnName with the value per row would help; Somehow possibly joining my Employee table with 'INFORMATION_SCHEMA.COLUMNS' ??)  Thanks! 

View 1 Replies View Related

Audit Trails

Apr 19, 2002

Hello,

I wish to track changes made to a table, including login who made the change, time of change, etc, without having to change the existing table structure, stored procedures, application.
If anyone has any strategies (with a brief explanation) or articles they could point me to, it would be very much appreciated.

My thinking is to set up a trigger to write both old and new data to a audit table but considering different strategies may be helpful.

Thanks for your time,
Esox

View 1 Replies View Related

Audit Trail For BCP

Mar 19, 2001

Hi,
Is there anyway I can audit the data imported by BCP or DTS into the table ?

Thanks,
Mano.

View 1 Replies View Related

Audit Log Ideas

Nov 28, 2000

I have tried to make my basic audit log do more, but i haven't gotten very far;

In my basic audit log, i record this information:

table
type of change
field modified
old value
new value
db user
date/time

This audit records everything, which is great, but it cannot relate information when i go back to analyze the changes; for example, when a "directory" record is added, a user's information may be entered into several different tables, such as:

name (different table)
addresses (different table)
phone numbers (different table)

If one wanted to look up the changes to addresses of a person in the directory based on the person's name, i could not do it with my existing audit log because the addresses would be in a different table than the name table and there is no relating data in the audit log to relate the address changes to a persons name;

What might be a solution? I have tried a few approaches and am at a loss;

Thank you!

--llyal

View 4 Replies View Related

Audit Logins

Jan 18, 2001

Does anyone have any ideas how I can track when someone logged in and out of SQL Server and compile that information over a 3 month period?

View 1 Replies View Related

Audit Question

Jan 23, 2001

Is there a way to audit a change on a column besides using trigger?

View 3 Replies View Related

USER Audit

Dec 1, 1999

hi,

does anyone know how i can audit a servers login id's and tell the last time it was used. i have just gain about 8 sql servers with a bunch of users that i know are no longer around. so i am trying to trim out dead id's

thanks for any help !!


k ingram
cellstar corp.

View 1 Replies View Related

Audit Trails

May 27, 1999

I am currently developing a system which uses SQL Server 7 as its repositry. One of the systems requirements is the ability to be able to record any changes made to the data, and by whom. In other words I need to store the before and after with a userid.

Has anyone any experience with the matter.

Many thanks

Martin Fisher

View 1 Replies View Related

Audit Delets

Aug 26, 1999

Is there away to track which user had deleted and object(table),
the transaction log has that information but you can't read it and
the error log doesn't log such info. Any advice would be appricated, thanks.

View 1 Replies View Related

Audit Use Of Databases

Jul 10, 2002

Can anyone help me audit connections to databases?

My objective is to tidy a poorly maintained set of servers - especially permissions. (Any suggestion what-so-ever, would be welcome)

Specifically I'm now looking to audit who accesses which databases. As a first step I just want to be able to record database open actions.

I think profiler can help.
My aim is a list of NTuser, Server, Database, When

I've tried profiling Event Object:Opened but NOTHING happens.
Other profile events are OK.

So the simple questions are, what makes this event fire or what is the approriate event (or other method) to acheive this objective.

Note I've looking into auditing - but this doesn't provide me with which database is accessed.

I could, I suppose, use Locks acquired

View 1 Replies View Related

Audit Trail For MS SQL

Nov 9, 2006

Hi folks. Any ideas on the best way to creat an audit trail for ms sql 2000?

I want to capture all tables affected by UPDATE, INSERT and DELETE queries.

Any help would be appreciated!

Many thanks!
Kunal

View 2 Replies View Related

SQL Secuirty Audit

Oct 27, 2004

Hi Folks,

Have a scenario where we have to audit all our databases and servers for changes in security accross the servers.

We have a central montioring server where we pull SQL metadata at regular intervals. In this instance we are looking to have before and after snapshots of the SQL system tables.

For the logins this is fine as there is a last updated field in the syslogins table. We can tell when a new user has been added , remmoved or the login has changed ie the login as been added to sysadmin fixed server role... etc Perfect !!!

What Im trying to work out now is how I can do this for object level permsisions. Have looked at sysprotects but no joy. If a user or a role has been granted select or update on a table... How can I tell based on before and after snap shots of the system tables what permissons have changed and whom have they changed for...

Help ......

View 2 Replies View Related

Audit Data

Jan 18, 2005

Hi all,
I would just like to ask whats the best way to make some audit on some of the tables in a MS SQL server, what i'm planning to have is to have a table which can contain all changes/inserts/deletion of some given tables, my first idea was to have this:

AuditTable that have the following fields:
AuditID, TableName, FieldName, OldValue, NewValue, UpdateBy, UpdateDate

then in all the given tables, i'll have insert, update and delete trigger, the issue comes down to the trigger, what will be the best way to have that trigger written in a way that it can be use for other tables as well? say if a table have more then 20 fields, I don't want to declare 20 var and compare them 1 by1, and if there is a diff, then i insert to the audittable, I want something that it can loop and (if possible) be able to use by other table as well, so the field name etc can get from sysobjects, but then how can you code it in a way that it can do that?

Or is there any better way to get the same result? currently i have an audit table for each table i want to audit on and its just wasting space, any help will be great.
Thanks,

View 6 Replies View Related

Database Audit

May 2, 2006

Does MSSQL 2000 and above have an auditing feature? We have a requirement for tracking activity and history on a particular table. I realize this can be accomplished by a simple trigger but I was wondering if MSSQL had a feature that would accomplish this.

joe

View 2 Replies View Related

SQLServer2000- Audit - ALL

Jun 23, 2006

I turned the Audit ALL option on SQLServer instance "security" tab and restarted the SQLServer but do not see any information logged in SQLServer Logs though I tried to access databases and logged in a couple of times through Query Analyzer. Why is that no logging happened and how can I get this fixed?

Any help is appreciated.

Vinnie

View 1 Replies View Related

Query For SQL Audit

Nov 30, 2007

Hey everyone,

This is my first question here for a long while, so be extra nice ;)

I am doing an audit on some of my sql server 2000s and I would to know if its possible to automate the collection of some of the data.

Firstly I would like to be able to query the domain account that SQLSERVER and SQLAGENT are running on, in my case the agent and service account will alaways be the same, but the account name maybe different depending on what server it is.

Secondly I would like to be able to query whether the account SQL server is running on is local admin of the server...I know some of you will say the SQL account has to be local admin but with the right registry and folder level permissions it is not necessary for the account to be local admin. This was a requirement from a very strict security audit.

View 3 Replies View Related

Which Is Better For An Audit Trail

Apr 27, 2004

A table that stores all [updated | deleted] transactions in a database
i.e.
TableName, TableId, ColumnName, ValueType, NewValue, OldValue, DateChanged

or

A copy of each individual table, which could add up to a lot of tables

View 4 Replies View Related

SQL Audit Tool

May 10, 2007

Hi,

We are looking to purchase SQL Audit tool. Which one do you recommend for SQL Server 2000 Standard Edition and SQL 2005 Enterprise Edition.

Thanks,
Debi.

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved