我想将Customer表中发生的更改保存到SQL Server 2008中的另一个表Notification中。为此,我编写了以下触发器:
CREATE TRIGGER [CustomerNotifier]
ON [dbo].[Customer]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @Action as char(1);
SET @Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED)
AND EXISTS(SELECT * FROM DELETED)
THEN 'U' -- Set Action to Updated.
WHEN EXISTS(SELECT * FROM INSERTED)
THEN 'I' -- Set Action to Insert.
WHEN EXISTS(SELECT * FROM DELETED)
THEN 'D' -- Set Action to Deleted.
ELSE NULL -- Skip. It may have been a 'failed delete'.
END)
IF @Action = 'I'
BEGIN
INSERT INTO Notification (CustomerId, BookingId, [Type], [Read], TenantId, TenantUsername, CreatedDateTime)
SELECT CustomerId, null, 0, 0, TenantId, AspNetUsers.UserName, CURRENT_TIMESTAMP FROM inserted
JOIN AspNetUsers ON inserted.TenantId = AspNetUsers.Id;
END
ELSE IF @Action = 'U'
BEGIN
INSERT INTO Notification (CustomerId, BookingId, [Type], [Read], TenantId, TenantUsername, CreatedDateTime)
SELECT CustomerId, null, 1, 0, TenantId, AspNetUsers.UserName, CURRENT_TIMESTAMP FROM inserted
JOIN AspNetUsers ON inserted.TenantId = AspNetUsers.Id;
END
ELSE IF @Action = 'D'
BEGIN
INSERT INTO Notification (CustomerId, BookingId, [Type], [Read], TenantId, TenantUsername, CreatedDateTime)
SELECT CustomerId, null, 1, 0, TenantId, AspNetUsers.UserName, CURRENT_TIMESTAMP FROM deleted
JOIN AspNetUsers ON deleted.TenantId = AspNetUsers.Id;
END
END
当客户表格中的客户已插入或已删除时触发器成功执行,但触发器未在更新时执行。
我可能知道原因:它没有执行,因为我们正在更新另一个表AspNetUsers中的条目,该表通过共享主键关系与Customer表链接。
所以我的问题是如何在Update ??
上执行此触发器答案 0 :(得分:0)
只有在定义了触发器的表上存在相应的DML时,触发器才会触发。
要在此处执行触发器,您应该在AspNetUsers
表上创建实际更新的触发器,或者更新Customer
表。请记住,inserted
和deleted
伪表将包含定义触发器的表的数据。