-1

我正在从全局临时表执行更新,如下所示:

update some_table
set Amount = (##GlobalTable.InitialAmount) + (##GlobalTable.[Difference])
from ##GlobalTable
where Amount = ##GlobalTable.InitialAmount

Amount、InitialAmount 和 Difference 列都是数字 (21,2)

Amount 和 InitialAmount 始终为正数。问题是,当差异为负时,产生的金额实际上会因负差异而增加。它应该执行减法,但事实并非如此。当差异为正时,它工作正常。任何想法为什么会发生这种情况?

我在使用 SQL Server 2008 R2 的 Windows 7 Enterprise SP1 64 位

4

1 回答 1

0

One way this can happen...(but may not be what you are seeing)

See if you have two rows in ##GlobalTable with the same value for InitialAmount but different values for Difference.

If so, then a row in some_table may match both (or more) rows in ##GlobalTable, and SQLServer makes no guarantee what answer you will get.

In my experience SQLServer will choose a row to use in the update and it is usually the last qualifying row retrieved from ##GlobalTable based on the execution plan. Since the execution plan is subject to change as table contents change the result is not so predicable, and not something to count on when writing code.

Unless you know that each row in ##GlobalTable has a unique value for InitialAmount, you should choose a more reliable way to join some_table with ##GlobalTable.

于 2012-07-20T21:58:35.647 回答