INSTEAD OF UPDATE Trigger - is this possible?

烈酒焚心 提交于 2019-12-01 15:18:47

Using the UPDATE(columnname) test, you can check in a trigger whether a specific column was updated (and then take specific actions), but you can't have a trigger fire only on the update of a specific column. It will fire as soon as the update is performed, regardless of the fact which column was the target of the update.

So, if you think you have to use an INSTEAD OF UPDATE trigger, you'll need to implement two kinds of actions in it:

1) insert into tbDeletedUsers + delete from tbUsers – when IsDeleted is updated (or, more exactly, updated and set to 1);

2) update tbUsers normally – when IsDeleted is not updated (or updated but not set to 1).

Because more than one row can be updated with a single UPDATE instruction, you might also need to take into account that some rows might have IsDeleted set to 1 and others not.

I'm not a big fan of INSTEAD OF triggers, but if I really had to use one for a task like yours, I might omit the UPDATE() test and implement the trigger like this:

CREATE TRIGGER trg_ArchiveUsers
ON tbUsers
INSTEAD OF UPDATE
AS
BEGIN
  UPDATE tbUsers
  SET
    column = INSERTED.column,
    …
  FROM INSERTED
  WHERE INSERTED.key = tbUsers.key
    AND INSERTED.IsDeleted = 0
  ;
  DELETE FROM tbUsers
  FROM INSERTED
  WHERE INSERTED.key = tbUsers.key
    AND INSERTED.IsDeleted = 1
  ;
  INSERT INTO tbDeletedUsers (columns)
  SELECT columns
  FROM INSERTED
  WHERE IsDeleted = 1
  ;
END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!