仅更新触发器

时间:2018-01-07 23:33:12

标签: sql sql-server database

我的应用程序中有一个评论系统,我想制作一个触发器,可以在删除评论时激活。我希望触发器将注释文本更改为[已删除]。这是我到目前为止所做的,如何确保它只会影响已被删除的行?

    Create trigger tr_Comment_On_Delete on Comment
Instead of delete
AS
begin
    update Comment
    SET CommentText = '[Deleted]'

end

1 个答案:

答案 0 :(得分:1)

假设您的id表中的列Comment上有一个主键,您可以参考deleted表来获取您要操作的特定行(执行更新) )。

CREATE TRIGGER tr_Comment_On_Delete on Comment
INSTEAD OF delete
AS
BEGIN
  UPDATE Comment
  SET CommentText = '[Deleted]'
  FROM Comment
  JOIN deleted d ON Comment.id = d.id
END

在SQL Server 2014 EE上测试

完整测试方案(删除id = 2的评论):

create table Comment(id int, CommentText text);
insert into Comment values (1, 'asd'), (2, 'bcf');
select * from comment;
go

CREATE TRIGGER tr_Comment_On_Delete on Comment
INSTEAD OF delete
AS
begin
  UPDATE Comment
  SET CommentText = '[Deleted]'
  FROM Comment
  JOIN deleted d ON Comment.id = d.id

end
go

delete from comment where id = 2;
select * from comment;