Sql server 2008 使用以前更新的值进行更新
我试图在一次查询运行中使用以前更新的值更新记录。这是一个正在运行的总体案例,但它是一个更新查询,而不是选择查询 简化表库存Sql server 2008 使用以前更新的值进行更新,sql-server-2008,Sql Server 2008,我试图在一次查询运行中使用以前更新的值更新记录。这是一个正在运行的总体案例,但它是一个更新查询,而不是选择查询 简化表库存 Id Qty RunningQty ItShouldBeUpdatedTo InsteadItsUpdatedTo 1 200 0 200 200 2 300 0 500 300 3 400 0 900 400 4 1
Id Qty RunningQty ItShouldBeUpdatedTo InsteadItsUpdatedTo
1 200 0 200 200
2 300 0 500 300
3 400 0 900 400
4 100 0 1000 100
我当前的查询是这样的
UPDATE Inventory
SET RunningQty = ISNULL(A.RunningQuantity, 0) + Quantity
FROM Inventory I
OUTER APPLY
(
-- Take previous row RunningQty
SELECT TOP 1 RunningQty
FROM Inventory
WHERE Id < I.Id
ORDER BY Id DESC
) A
它似乎要更新下一行,sql server没有使用以前更新的值
注意:它将是一个相当大的表,所以我使用前一行运行数量计算它,并将该值与当前行数量相加,而不是从第一行开始计算
正确的方法是什么
提前感谢。让我先说一句,在SQL Server 2012中,这将非常容易做到。在该版本中,您将能够使用以下内容:
update i1
set i1.runningqty = i2.RunningQty
from inventory i1
inner join
(
select id, SUM(qty) OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) RunningQty
from inventory
) i2
on i1.id = i2.id;
declare @total int
set @total = 0
update inventory
set runningqty = @total,
@total = @total + qty;
看
但是,在SQL Server 2008中,这并不像在SQL Server 2008中那么容易,但是您应该能够使用以下内容:
update i1
set i1.runningqty = i2.RunningQty
from inventory i1
inner join
(
select id, SUM(qty) OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) RunningQty
from inventory
) i2
on i1.id = i2.id;
declare @total int
set @total = 0
update inventory
set runningqty = @total,
@total = @total + qty;
看
还有其他方法,包括在SQLServer2008中使用游标来执行此操作