单个触发器用于多个事件

时间:2014-11-16 14:00:08

标签: sql-server tsql triggers

我的SQL Server数据库中有两个表Trainer(TrainerID, Username, Password, email, .... )TrainerPassword (ID, TrainerID, Password, CreationDate)。 TrainerPassword(TrainerID)指Trainer(TrainerID)。任务的基线是跟踪培训师的密码更改。我在Trainer表上使用了Trigger。

现在问题出现了如何触发事件的触发器

  • 插入后 - 在Trainer表中更新/插入后添加并输入TrainerPassword。
  • 删除之前 - 删除Trainer表中的记录应该删除TrainerPassword中的引用

这两个事件都可以在单个触发器中实现吗?

1 个答案:

答案 0 :(得分:2)

我会做这样的事......

用于插入和更新

CREATE TRIGGER tr_Trainer_For_Insert_Update
ON Trainer
FOR INSERT, UPDATE
AS
BEGIN
  SET NOCOUNT ON;

  INSERT INTO TrainerPassword (TrainerID, [Password], CreationDate)
  SELECT TrainerID, [Password] , GETDATE()
  FROM inserted

END

for delete

CREATE TRIGGER tr_Trainer_For_Delete
ON Trainer
FOR DELETE
AS
BEGIN
  SET NOCOUNT ON;

  DELETE FROM  TrainerPassword 
  WHERE EXISTS (SELECT 1 FROM deleted
                WHERE TrainerID = TrainerPassword.TrainerID )

END