我构建了一个触发器,只要将某些数据插入到Sales表中,就会触发该触发器。当它触发时,它会在“帐户”表中更新剩余的购买金额,并按“销售”表中的销售总金额减去该金额。但触发器给出了错误的结果。这是代码:
CREATE TRIGGER [dbo].[TRG_Conta_Insert]
ON [dbo].[Sale]
FOR INSERT, UPDATE
AS
BEGIN
declare @IDAccount bigint
declare @SaleTotalAmount money
declare @RemainingAmount money
select @IDAccount= Inserted.ID_Account, @SaleTotalAmount = Sale.Amount, @RemainingAmount = RemainingAmount from Inserted, Account
if (@IDAccount is not null) and (@RemainingAmount - @SaleTotalAmount >= 0)
begin transaction
update Account set RemainingAmount = @RemainingAmount - @SaleTotalAmount where Account.ID_Account = @IDAccount
commit
为什么触发器在RemainingAmount列中更新了Account表并显示错误的结果?
答案 0 :(得分:1)
你的整个触发器应该是这样的。
update a set RemainingAmount = a.RemainingAmount - s.SaleTotalAmount
from inserted i
join Account a on i.SomeKey = a.SomeKey
join Sale s on s.SomeOtherKey = a.SomeOtherKey
另外,请勿将交易置于触发器中。你问的是问题,因为sql server中的嵌套事务是一个神话。我会首先重新考虑你在这里做的事情。您实际上是通过触发器存储计算值。在sql server中有计算列,这似乎比触发器更适合。