简体   繁体   English

SQL Server 2008 Management Studio中的触发器

[英]Triggers in sql server 2008 management studio

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. 触发器将信息保存在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 谢谢

To get the user you may use: 要获取用户,您可以使用:

  1. server level (login) 服务器级别(登录)

    select system_user , suser_sname() , suser_sid() 选择system_user,suser_sname(),suser_sid()

  2. db level (db user) 数据库级别(数据库用户)

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

Than and check that this user is admin or not in that additional table. 然后在该附加表中检查该用户是否为admin。

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. IS_MEMBER函数评估数据库角色,而IS_SRVROLEMEMBER函数评估服务器角色。 So, if you want to know if the user is a database admin, you would use IS_MEMBER. 因此,如果您想知道用户是否是数据库管理员,则可以使用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
    ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM