创建数据库触发器以进行审计操作

时间:2014-06-23 06:21:12

标签: asp.net sql-server asp.net-mvc azure azure-sql-database

我需要为azure db创建数据库触发器,当用户单击更改表中的内容时,触发器会将此事件写入表,写入更改内容,时间等等。

目前我有两个基本问题。

1.这是我的模特

public class UserRoles
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public Boolean Address { get; set; }
    public Boolean Email { get; set; }
    public Boolean Work { get; set; }
    public Boolean Home { get; set; }
}

public class UserRolesDbContext : DbContext
{
    public UserRolesDbContext()
        : base("DefaultConnection")
    {
       this.Database.Connection.ConnectionString = My.GetDBConnectionString();

        if (!String.IsNullOrEmpty(this.Database.Connection.ConnectionString))
        {
            this.Database.SqlQuery("here put the SQL")
        }

    }

        public DbSet<UserRoles> UserRolesCollection { get; set; }
    }

如果我希望在部署我的云服务时创建它,我应该像这样(在sqlQuery中)放置触发器吗?当我正在进行部署时,在天蓝色中创建数据库...

2.假设我想将所有带有DB triger的字段从UserRoles表复制到UserRolesCopy,当它们像 audit 那样更改时,我应该如何编写SQL代码?

my schema name is :UserDB
MyOrginal table is:UserRoles
I want it to copy to UserRoleCopy

我是这个主题的新手,我在MSDN中阅读了以下页面

http://msdn.microsoft.com/en-us/library/ms189799%28v=sql.120%29.aspx

- Windows Azure SQL数据库语法
触发对表或视图的INSERT,UPDATE或DELETE语句(DML触发器)

CREATE TRIGGER [ schema_name . ]trigger_name 
ON { table | view } 
 [ WITH <dml_trigger_option> [ ,...n ] ] 
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
  AS { sql_statement  [ ; ] [ ,...n ] [ ; ] > }

<dml_trigger_option> ::= 
        [ EXECUTE AS Clause ] 

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法审核您的表格更改:

  1. 使用数据库审核规范

    Create a Server Audit and Database Audit Specification

  2. CDC(更改数据捕获)

    About Change Data Capture

  3. DML触发器

  4. &GT;

    Create Trigger yourSchema.TriggerName ON YourTable
    AFTER INSERT, Update, Delete
    AS Begin
      -- Log Deleted Rows and Old Value in Updated Rows
      Insert Into LogTable(UserName, Columns)
      Select CURRENT_USER, Columns
      From Deleted
    
      -- Log Inserted Row and New Value in Updated Rows
      Insert Into LogTable(UserName, Columns)
      Select CURRENT_USER, Columns
      From Inserted
    End