我想更新OrigOrderNbr和OrigOrderType(QT类型),因为当我创建第一列时,两列都是Null值。但是在创建S2(QT转换为S2)后,OrigOrderType和OrigOrderNbr(S2)取自QT参考。而不是那样,我想将它更新到QT。
http://i.stack.imgur.com/6ipFa.png
http://i.stack.imgur.com/E6qzT.png
CREATE TRIGGER tgg_SOOrder
ON dbo.SOOrder
FOR INSERT
AS
DECLARE @tOrigOrderType char(2),
@tOrigOrderNbr nvarchar(15)
SELECT @tOrigOrderType = i.OrderType,
@tOrigOrderNbr = i.OrderNbr
FROM inserted i
UPDATE dbo.SOOrder
SET OrigOrderType = @tOrigOrderType,
OrigOrderNbr = @tOrigOrderNbr
FROM inserted i
WHERE dbo.SOOrder.CompanyID='2'
and dbo.SOOrder.OrderType=i.OrigOrderType
and dbo.SOOrder.OrderNbr=i.OrigOrderNbr
GO
在我运行该触发器后,它显示了消息'错误#91:另一个进程已更新' SOOrder'记录。您的更改将会丢失。'。
答案 0 :(得分:3)
每一段评论,包括@marc_s和@Damien_The_Unbeliever关于正确触发器编写技巧的一些很好的建议,以及我现在对你的问题的更好理解,这里是重新触发的触发器:
CREATE TRIGGER tgg_SOOrder
ON dbo.SOOrder
FOR INSERT
AS
--Update QT record with S2 record's order info
UPDATE SOOrder
SET OrigOrderType = 'S2'
, OrigOrderNbr = i.OrderNbr
FROM SOOrder dest
JOIN inserted i
ON dest.OrderNbr = i.OrigOrderNbr
WHERE dest.OrderType = 'QT'
AND i.OrderType = 'S2'
AND dest.CompanyID = 2 --Business logic constraint
AND dest.OrigOrderNbr IS NULL
AND dest.OrigOrderType IS NULL
基本上,一旦创建了类型为“S2”的匹配记录,就会更新任何类型为“QT”的记录。这里的匹配意味着S2记录的OrigOrderNbr与QT记录的OrderNbr相同。我保留了关于CompanyID设置为2的业务逻辑约束。此外,我们只关心修改将OrigOrderNbr和OrigOrderType设置为NULL
的QT记录。
此触发器不依赖于单行插入;无论插入的行数是多少,它都能正常工作 - 这样就不太可能破坏这条线。