tags:

views:

30

answers:

2

Hi,

I am trying to set up the trigger in a way that when the administrator (not users) make any changes to the database, all the changed data with the administrator name and time gets saved in the audit table (already created) that has all the possible fields.

I have created triggers on each table for any sort of updates in those tables. The trigger saves the information in audittable. However, i want to restrict this action for administrators only. Like I only want to keep the record of changes made by adminsitrators with their name, time and changes made by them(I have a separate table for adminsitrator names, username, pw and all that).

Can someone please help me with that. Thanks

A: 

To get the user you may use:

  1. server level (login)

    select system_user , suser_sname() , suser_sid()

  2. db level (db user)

    select session_user , current_user , user , user_name() , user_id()

Than and check that this user is admin or not in that additional table.

Vash
A: 

You can try one of these two functions, depending on what you define as "administrator".

SELECT IS_MEMBER('dbo'), IS_SRVROLEMEMBER('sysadmin')

The IS_MEMBER function evaluates the database role and the IS_SRVROLEMEMBER evaluates the server role. So, if you want to know if the user is a database admin, you would use IS_MEMBER. These will work for user-defined roles as well as built-in roles.

UPDATE:

Here's an example of the trigger that would add data to the audit table when a server administrator inserts data to the table.

CREATE TRIGGER trg_InfoUpdates ON tblCustomerInfo 
FOR INSERT AS

    IF IS_SRVROLEMEMBER('sysadmin') = 1
      BEGIN
        INSERT INTO tblAuditLog (CustomerID)
        SELECT CustomerID
        FROM inserted
      END
    ;
bobs
okay but how can i implement that. For example let's say we have this for any kind of updates made by any user:CREATE TRIGGER trg_InfoUpdates ON tblCustomerInfoFOR INSERTASDECLARE @CustomerID intSELECT @CustomerID = (SELECT CustomerID FROM tblCustomerInfo)BEGININSERT INTO tblAuditLog ( CustomerID)Values (@CustomerID)ENDNow how can I implement IS_SRVROLEMEMEBER to achieve the goal of keeping adminitrators' changes?
Michelle
I added an example to my answer. Note that your trigger would have a problem when multiple rows are inserted at one time because the @CustomerID variable would only save one change. Also, the inserted table contains the rows that are inserted during this transaction. So, you don't have to query the tblCustomerInfo table within the trigger. There's also a deleted table that is useful for UDPATES and DELETES.
bobs
Thank you soo much !! I've got it worked!
Michelle