Update tblStock set Quantity = Quantity + 10, Total = (Quantity + 10)* PPrice
where barcode = 'shandar'
CROSS APPLY
在FROM
子句中定义新数量,然后使用该值:Update s
set Quantity = v.Quantity,
Total = v.Quantity * s.PPrice
from tblStock s cross apply
(values (s.Quantity + 10)) v(quantity)
where s.barcode = 'shandar';
重复简单的操作,例如quantity + 10
并不是什么大问题。但是,如果计算更加复杂,那么最好只做一次。
话虽如此,您可能更适合使用total
作为一个计算列。这样它就是正确的了,而且永远不需要更新。将其从表中删除,然后重新添加为:
alter table tblStock add total as ( quantity * pprice );
那么total
的值总是正确的,因为它在查询表时计算。
quantity + 10
只出现了一次,而不是两次。 - Gordon Linoff
Total = Quantity * PPrice
refers to the existing value ofQuanity
as it is before the update. You need to doTotal = (Quantity + 10) * PPrice
- derpirscher