用于DELETE的MSsql触发器

时间:2017-03-27 12:42:24

标签: sql sql-server

如果该员工已经在处理任务,我希望触发器能够阻止从Role-table中删除员工。如果任务尚未启动,则应该能够从角色表中删除该员工。

触发:

CREATE TRIGGER trg_role_del
ON Role
FOR DELETE AS

IF EXISTS (SELECT Task.StartTask, Role.EmployeeId,
FROM Task, Role, deleted
WHERE Role.EmployeeId = deleted.EmployeeId
AND Role.EmployeeId = Task.EmployeeId
AND GETDATE() > Task.StartTask)
BEGIN
    RAISERROR ('This role is working on a task, cannot be removed', 16, 1)
ROLLBACK TRANSACTION
END;

删除声明:

DELETE FROM Role
WHERE EmplyeeId = '003'

但是上面的触发器不起作用。所有删除都会通过,触发器不会停止任何操作。如果SELECT语句本身单独运行,它会从表中选择正确的值,因此SELECT似乎很好。我似乎无法使代码正常工作。非常感谢帮助!

2 个答案:

答案 0 :(得分:2)

我会使用而不是删除触发器:

CREATE TRIGGER trg_role_del
ON Role
INSTEAD OF DELETE AS

DELETE r
FROM Role r
INNER JOIN deleted ON r.EmployeeId = deleted.EmployeeId
LEFT JOIN Task ON r.EmployeeId = Task.EmployeeId
               AND GETDATE() > Task.StartTask
WHERE Task.Id IS NULL -- Any non-nullable column on the task table is good here

See a live demo on rextester

答案 1 :(得分:0)

你创建了一个“AFTER DELETE”触发器,你应该创建一个“INSTEAD OF”触发器。