I have the below SQL query that works but it's very slow. it takes about 1 min to run the query. This would be made into a stored procedure. which is not the problem. but that store procedure would be called for every item of which there are about 600 items. The estimated run time probably would end up taking about 10 hours. Does anyone have any suggestions of a better way of doing it?
What I'm trying to do is get a running stock level for every day for the past year for each item.
If you need any more information. Please let me know.
DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
DECLARE @CurrentDate AS DATETIME
DECLARE @ItemName As Varchar(450)
DECLARE @QOH DECIMAL(19,4)
SET @QOH = 0
SET @ItemName = 'TUR001-02'
SET @StartDate = '2020-04-01'
SET @EndDate = GETDATE()
SET @CurrentDate = @StartDate
CREATE TABLE #TempTable
(
Date datetime,
ItemName char(450),
QOH DECIMAL(19,4)
);
WHILE (@CurrentDate < @EndDate)
BEGIN
DECLARE @daySales DECIMAL(19,4)
SELECT @daySales = SUM(Quantity)
FROM qbInvoiceLineDetail
WHERE TxnDate = @CurrentDate AND FullName = @ItemName;
SET @QOH = @QOH - @daySales
INSERT INTO #TempTable (Date, ItemName, QOH)
SELECT @CurrentDate, @ItemName, @QOH;
SET @CurrentDate = DATEADD(DAY, 1, @CurrentDate);
END
SELECT * FROM #TempTable
DROP TABLE #TempTable