Triggers SQL server 2008 R2-触发器插入多行
你好,我有一个桌子上的触发器Triggers SQL server 2008 R2-触发器插入多行,triggers,sql-server-2008-r2,Triggers,Sql Server 2008 R2,你好,我有一个桌子上的触发器 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 @newManagementInten
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语句时,每个更新的行都会插入更新的行数时间
UPDATE FXHedge SET ModificationDate = SYSDATETIME()
,ManagementIntentId = 4
,ModificationUser = 'AW4256'
WHERE FXHedge.Id in (780,803);
在本例中,每行在审计表中插入两次。如果我有3个修改的行,每一行将插入3次
如何解决此问题?您没有将插入的
和删除的关联在一起。此外,对于您的程序部分,您随意将插入的中的一个ManagementIntentId
与删除的ManagementIntentId
中的另一个ManagementIntentId
进行比较,无法保证值来自的两行是相关的。我认为这样会更好:
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\u是否真的要实现任何有用的功能(它在当前查询中没有任何效果),或者只是从其他地方将触发器拉到一起的一部分,所以我也删除了它。更新的COLUMNS\u允许我知道哪个列已经更新。我只粘贴了较长触发器的一部分。谢谢你的帮助,一切顺利。但我还是不明白。为什么我必须连接插入的伪表和删除的伪表?因为inserted
和deleted
包含多行-受更新影响的每行一行。至于更新的列
,正如您的问题所述,它所影响的(后面没有开始…结束
块)是@oldManagementIntentId
的以下声明
。但由于DECLARE
s不尊重控制流,因此它对该查询没有影响。