你好我在表上有以下触发器
CREATE TRIGGER [dbo].[trigger_FxHedge_AuditTrail]
ON [dbo].[FXHedge]
AFTER UPDATE
AS
BEGIN
IF ((SUBSTRING(COLUMNS_UPDATED(),1,1)) & 4 = 4)
DECLARE @oldManagementIntentId int
DECLARE @newManagementIntentId int
SET @oldManagementIntentId = (SELECT TOP(1)ManagementIntentId FROM Deleted);
SET @newManagementIntentId = (SELECT TOP(1)ManagementIntentId FROM Inserted);
IF ((@oldManagementIntentId @newManagementIntentId) OR (@oldManagementIntentId IS NULL AND @newManagementIntentId IS NOT NULL) OR (@oldManagementIntentId IS NOT NULL AND @newManagementIntentId IS NULL))
INSERT INTO FxHedge_AuditTrail (EntityId
,ModificationDate
,PropertyChangedName
,OperationType
,ModifyBy
,OldValue
,NewValue)
SELECT Inserted.Id
,Inserted.ModificationDate
,'ManagementIntentId'
,'UPDATE'
,Inserted.ModificationUser
,CONVERT(VARCHAR(250),Deleted.ManagementIntentId)
,CONVERT(VARCHAR(250),Inserted.ManagementIntentId)
FROM Inserted,Deleted
每当我运行更新语句时,每个更新的行都会插入更新的行时间
UPDATE FXHedge SET ModificationDate = SYSDATETIME()
,ManagementIntentId = 4
,ModificationUser = 'AW4256'
WHERE FXHedge.Id in (780,803);
对于此示例,每行都在我的审计表中插入两次。如果我有3个修改过的行,每行将被插入3次。
我该如何解决这个问题?
答案 0 :(得分:1)
您没有将inserted
和deleted
放在一起。此外,对于您的程序部分,您可以随意地将ManagementIntentId
中的inserted
与来自ManagementIntentId
的另一个deleted
进行比较,但不保证值的两行来自有关系。我认为这会更好:
CREATE TRIGGER [dbo].[trigger_FxHedge_AuditTrail]
ON [dbo].[FXHedge]
AFTER UPDATE
AS
BEGIN
INSERT INTO FxHedge_AuditTrail (EntityId
,ModificationDate
,PropertyChangedName
,OperationType
,ModifyBy
,OldValue
,NewValue)
SELECT i.Id
,i.ModificationDate
,'ManagementIntentId'
,'UPDATE'
,i.ModificationUser
,CONVERT(VARCHAR(250),d.ManagementIntentId)
,CONVERT(VARCHAR(250),i.ManagementIntentId)
FROM Inserted i
inner join
Deleted d
on
i.ID = d.ID
WHERE
i.ManagementIntentId != d.ManagementIntentId or
i.ManagementIntentId IS NULL and d.ManagementIntentId IS NOT NULL or
i.ManagementIntentId IS NOT NULL and d.ManagementIntentId IS NULL
我不确定COLUMNS_UPDATED
检查是否实际上是为了实现任何有用的东西(它在当前查询中没有效果),或者只是将此触发器从其他地方拉到一起的一部分,所以我'我也删除了。