0

I have created a trigger to audit changes to table rows from my web application. My web application is using a single db user to do updates to the database. However, many different users can log in to the website and do the updates and inserts. Therefore, the db user will always be same but web users will be different

I want to have some way to capture the logged in user to the website who is making the changes to the rows so that I can audit the changes along with the web user that is making the changes.

Can someone please guide me how can I capture the web session in my sql trigger so that I know who is making the changes. Can I configure the web.config file so that the session info is also passed on to the sql server trigger or if there is some other way, please let me know

Regards

Arif

Syed Shah
  • 1
  • 1

1 Answers1

0

The most reliable method is for you to pass this LoggedInUserId through to the table(s) modified, perhaps stored in a ModifiedBy column. This can be a pain to implement and maintain, especially in a legacy system, but its rock solid.

I have had some success using CONTEXT_INFO to relate a small bit of metadata to a session but it's not without its oddities as well.

A simple example:

declare @context varbinary(128);
select @context = cast('user@domain.com' as varbinary(128));
set context_info @context;
go

And, from the trigger you can retrieve the username like:

declare @context varchar(128);
select @context = cast(context_info() as varchar(128));
select @context;

BOL states that this data is not reset when the scope terminates so you will need to consider that to avoid userIds crossing DML operations (connection pooling).

nathan_jr
  • 9,092
  • 3
  • 40
  • 55