我在 SQL 2005 中,我正在尝试将此 Cursor 转换为不是 Cursor 的东西,以确定这是否是最有效的方法。
--Create cursor to determint total cost
DECLARE CostCursor CURSOR FAST_FORWARD
FOR SELECT ReceiptQty
,Price
FROM @temp_calculate
ORDER BY UpdateDate DESC
OPEN CostCursor
FETCH Next FROM CostCursor INTO @ReceiptQty,@Price
WHILE @@FETCH_STATUS = 0
BEGIN
IF @OnHandQty >= @ReceiptQty
BEGIN
--SELECT @ReceiptQty,@Price, 1,@OnHandQty
SET @Cost = @ReceiptQty * @Price
SET @OnHandQty = @OnHandQty - @ReceiptQty
SET @TotalCost = @TotalCost + @Cost
END
ELSE
BEGIN
IF @OnHandQty < @ReceiptQty
BEGIN
--SELECT @ReceiptQty,@Price, 2,@OnHandQty
SET @Cost = @OnHandQty * @Price
SET @OnHandQty = 0
SET @TotalCost = @TotalCost + @Cost
BREAK;
END
END
FETCH Next FROM CostCursor INTO @ReceiptQty,@Price
END
CLOSE CostCursor
DEALLOCATE CostCursor
系统需要通过并使用最新收到的库存和价格来确定为现有量支付的费用。
Ex. 1st Iteration: @OnHandQty = 8 RecievedQty = 5 Price = 1 UpdateDate = 1/20 Results: @HandQty = 3 @TotalCost = $5
2nd Iteration: @OnHandQty = 3 RecievedQty = 6 Price = 2 UpdateDate = 1/10 Results: @HandQty = 0 @TotalCost = $11
最终结果告诉我,我手头的库存是我花了 11 美元买的。如果我在 C# 或任何其他面向对象的语言中执行此操作,这会向我尖叫递归。我认为递归 CTE 可能更有效。我只成功地为 Heirarchy 的以下类型的查询成功地完成了任何递归 CTE,并且我无法成功地围绕一个可以以另一种方式实现这一目标的查询。
任何帮助或简单的方式将不胜感激。