为Sql DB创建数据库触发器

时间:2014-06-24 07:51:54

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

我是DB的新手,我需要为azure SQL DB创建数据库触发器。

我先用模型创建了MVC5项目,我有这个反映数据库表的模型。

    public class Employee
    {
        public int Id { get; set; }
        public string EmployeeName { get; set; }
        public string EmpAddress { get; set; }
        public string EmpEmail { get; set; }
        public string EmpPhone { get; set; }

    }

    public class EmployeeDbContext : DbContext
    {
        public EmployeeDbContext()
            : base("DefaultConnection")
        {

        }
            public DbSet<Employee> EmployeeCollection { get; set; }
        }

}

现在我想为它创建数据库触发器,我尝试跟随。(我从SO中取这个例子并调整它......)

Create Trigger Dbo.triggerName ON Employee
AFTER INSERT, Update, Delete
AS Begin
  -- Log Deleted Rows and Old Value 
  Insert Into EmployeeCopy(Id ,EmployeeName, EmpAddress,EmpEmail,EmpPhone)
  Select CURRENT_EMPLOYEE, Columns
  From Deleted

  -- Log Inserted Row and New Value 
  Insert Into EmployeeCopy(Id ,EmployeeName, EmpAddress,EmpEmail,EmpPhone)
  Select CURRENT_EMPLOYEE, Columns
  From Inserted
End

我希望它创建新表 EmployeeCopy 并将所有行复制到它。 所以这是我的问题(我是本主题的新手)

1. what is the trigger name?
2.Do I write the Insert into right ?
3. Select CURRENT_EMPLOYEE, Columns ..Here Im not sure if this is the right way to write it?

1 个答案:

答案 0 :(得分:0)

您的insert into声明可能会更改(请参阅下文) - 但您未指定select =&gt;的条件您可能会在每次触发操作中插入已删除和已插入表中的所有行。

查看有关插入的详细信息,例如here

您应该编写并测试您的select语句作为独立查询(只需从New Query窗口运行它),当您获得预期结果时 - 将其置于触发器的逻辑中。

通常,我建议尝试将触发逻辑的每个部分作为独立语句。

Create Trigger dbo.MyTrigger ON Employee
AFTER INSERT, Update, Delete
AS Begin
  -- Log Deleted Rows and Old Value 
  Insert Into EmployeeCopy
   Select (Id ,CURRENT_EMPLOYEE, EmpAddress,EmpEmail,EmpPhone)
   From Deleted
   WHERE Your_conditions_logic_here

  -- Log Inserted Row and New Value 
  Insert Into EmployeeCopy 
   Select  (Id ,CURRENT_EMPLOYEE, EmpAddress,EmpEmail,EmpPhone)
   From Inserted
   WHERE Your_conditions_logic_here
End