SQL更新只在列被修改时触发

通过查看其他示例我已经想出了以下,但它似乎并没有工作,因为我想:我希望它只更新修改后的信息,如果QtyToRepair值已更新…但它不去做。

如果我在哪里注释掉,修改后的信息在每种情况下都会更新。 正如我所说的,其他例子让我感到乐观。 任何线索表示赞赏。 谢谢。

沃尔特

 ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified] ON [dbo].[SCHEDULE] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE SCHEDULE SET modified = GETDATE() , ModifiedUser = SUSER_NAME() , ModifiedHost = HOST_NAME() FROM SCHEDULE S INNER JOIN Inserted I on S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber WHERE S.QtyToRepair <> I.QtyToRepair END 

你有两个方法来解决你的问题:

1-在触发器中使用更新命令。

 ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified] ON [dbo].[SCHEDULE] AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF UPDATE (QtyToRepair) BEGIN UPDATE SCHEDULE SET modified = GETDATE() , ModifiedUser = SUSER_NAME() , ModifiedHost = HOST_NAME() FROM SCHEDULE S INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber WHERE S.QtyToRepair <> I.QtyToRepair END END 

2-使用插入表和删除表之间的连接

 ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified] ON [dbo].[SCHEDULE] AFTER UPDATE AS BEGIN SET NOCOUNT ON; UPDATE SCHEDULE SET modified = GETDATE() , ModifiedUser = SUSER_NAME() , ModifiedHost = HOST_NAME() FROM SCHEDULE S INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber WHERE S.QtyToRepair <> I.QtyToRepair AND D.QtyToRepair <> I.QtyToRepair END 

如果对表SCHEDULE和Set QtyToRepair Column使用update命令为新值,如果新值等于一个或多个行中的旧值,则解决scheme1将更新Schedule表中的所有更新行,但解决scheme2仅更新调度旧值不等的行以新的价值。

应该首先检查QtyToRepair是否被更新。

 ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified] ON [dbo].[SCHEDULE] AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF UPDATE (QtyToRepair) BEGIN UPDATE SCHEDULE SET modified = GETDATE() , ModifiedUser = SUSER_NAME() , ModifiedHost = HOST_NAME() FROM SCHEDULE S INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber WHERE S.QtyToRepair <> I.QtyToRepair END END 

代码我结束了:

 IF UPDATE (QtyToRepair) begin INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew) SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber WHERE I.QtyToRepair <> D.QtyToRepair end 

你想要做到以下几点:

 ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified] ON [dbo].[SCHEDULE] AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF (UPDATE(QtyToRepair)) BEGIN UPDATE SCHEDULE SET modified = GETDATE() , ModifiedUser = SUSER_NAME() , ModifiedHost = HOST_NAME() FROM SCHEDULE S INNER JOIN Inserted I ON S.OrderNo = I.OrderNo AND S.PartNumber = I.PartNumber WHERE S.QtyToRepair <> I.QtyToRepair END END 

请注意,无论数值是否相同,每次更新列时都会触发此触发器。