我的应用程序中有一个评论系统,我想制作一个触发器,可以在删除评论时激活。我希望触发器将注释文本更改为[已删除]。这是我到目前为止所做的,如何确保它只会影响已被删除的行?
Create trigger tr_Comment_On_Delete on Comment
Instead of delete
AS
begin
update Comment
SET CommentText = '[Deleted]'
end
答案 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;