更新部门表上的触发器,如果​​已停用特定部门,则会将员工设置为活动状态

时间:2018-05-29 05:26:58

标签: sql sql-server triggers

我有两张桌子:

tblEmployees tblDepartment

我知道update中的代码 但我不知道如何将其插入trigger

这是我的代码update

UPDATE tblEmployees
SET Employee_Type = 'Active'
FROM tblEmployees AS t1
LEFT JOIN tblDepartment AS t2
ON t1.EmployeeID = t2.EmployeeID
WHERE
t2.Department_Type = 'Inactive' AND t2.DepartmentID = '1101'

2 个答案:

答案 0 :(得分:1)

触发器看起来像这样:

CREATE TRIGGER [UpdateEmployeeTrigger] ON tblDepartment AFTER Update
AS 
BEGIN
    UPDATE e
        SET Employee_Type = 'Active'
        FROM inserted i JOIN
             tblEmployees e
             ON i.EmployeeID = e.EmployeeID
        WHERE i.Department_Type = 'Inactive'
END;

表格布局没有意义。为什么名为Department的表格中有一个名为EmployeeId的列?

答案 1 :(得分:-1)

我希望这可以帮助你创建一个触发器。

CREATE TRIGGER [UpdateEmployeeTrigger]
   ON  tblDepartment
  AFTER Update
AS 
BEGIN

    UPDATE tblEmployees
    SET Employee_Type = 'Active'
    FROM tblEmployees AS t1
    LEFT JOIN tblDepartment AS t2
    ON t1.EmployeeID = t2.EmployeeID
    WHERE t2.Department_Type = 'Inactive'
    AND t2.DepartmentID in (select DepartmentID from inserted)

END

此代码将在tblDepartment表上的每次更新后执行,最后一行即t2.DepartmentID = inserted.DepartmentID将仅检查更新的记录。如果同一记录设置为Inactive,则您的tblEmployee记录将设置为Active