I’m in SQL 2005 and I’m trying to convert this Cursor into something that isn’t a Cursor to determine if this is the most efficient way to do this.
--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
The system needs to go through and use the newest recieved inventory and price to determine what the paid for the on-hand is.
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
The Final Results tell me that the inventory I have on hand I paid $11 for. If I was doing this in C# or any other Object Oriented langauge this screams Recursion to me. I thought about a Recursive CTE could be more efficient. I’ve only successfully done any Recursive CTE’s for Heirarchy following types of Queries and I haven’t been able to successfully wrap my head around a query that would achieve this another way.
Any help or a simple thats how it has to be would be appreciated.
Welp, this was the solution I ended up coming up with. I like to think the fine folks watching the #sqlhelp hashtag for pointing me to this article by Jeff Moden:
http://www.sqlservercentral.com/articles/T-SQL/68467/
I did end up having to use a Rownumber on the table because it wasn’t getting the first set of cases correctly. Using this construct I brought retrieiving the dataset down from 17 minutes, best I been able to do, to 12 Seconds on my vastly slower dev box. I’m confident production will lower that even more.
I’ve tested the output and I get the exact same results as the old way except for when 2 items for the same product have different price and the update time is the exact same. One way may pick a different order then the other. It of 15,624 items that only happened once where the varience was >= a penny.
Thanks everyone who answered here. I ultimately went a different way but I wouldn’t have found it without you.