触发器在插入后更新另一个表

时间:2015-01-14 05:00:24

标签: sql sql-server-2008 triggers

我有2个表EmployeeEmployee_Backup

Employee有3列

  • IDEmployee
  • 名称
  • 状态

Employee_Backup也有3列:

  • IDEmployee
  • 详细
  • 状态

对于在表Employee中插入或更新的每一行,我想使用此条件在表Status中设置Employee_Backup

WHERE employee_backup.IDEmployee = employee.IDEmployee     (inserted / updated)

1 个答案:

答案 0 :(得分:0)

那样的东西?

CREATE TRIGGER tr_Employee_Insert
ON dbo.Employee
FOR INSERT 
AS
    UPDATE b
    SET Status = 'Inserted'
    FROM dbo.Employee_Backup b
    INNER JOIN Inserted i ON b.EmployeeID = i.EmployeeID


CREATE TRIGGER tr_Employee_Update
ON dbo.Employee
FOR UPDATE
AS
    UPDATE b
    SET Status = 'Updated'
    FROM dbo.Employee_Backup b
    INNER JOIN Inserted i ON b.EmployeeID = i.EmployeeID

您基本上需要加入 Inserted伪表,其中包含已从基表(dbo.Employee)和{{插入(或更新)的所有行1}} table - 然后使用JOIN中的结果集作为Employee_Backup语句的基础。

注意:当您向UPDATE添加新行时,会将任何新行插入Employee_Backup - 这是您想要的吗?如果没有,您必须稍微更改dbo.Employee触发器....