I want to loop a table such that If first-row Ratio >= AllocatedCount then it should increment the AllocatedCount once this condition fails then move to the next row and check the same logic as above till the last row. But Once it completes all the rows. For the first time allocating process works till the last row. But I want to reiterate the table from the start and increment the AllocatedCount according to the ratio. Please find the below code which I am trying.
CREATE TABLE #UserRatio
(
UserCode VARCHAR(10),
Ratio INT,
OrderBy INT,
AllocatedCount INT DEFAULT(0),
CanAllocate VARCHAR(1) DEFAULT('N')
)
INSERT INTO #UserRatio (UserCode, Ratio, OrderBy, AllocatedCount, CanAllocate)
VALUES('1001', 10, 1, 0, ''),('1002', 10, 2, 0, ''),('1003', 10, 3, 0, '')
DECLARE @IsAllocated VARCHAR(1) = 'N'
DECLARE @UserCode VARCHAR(10),@Ratio INT, @OrderBy INT, @AllocatedCount INT;
DECLARE Cursor_UserAllocation CURSOR FOR
SELECT UserCode,Ratio, OrderBy,AllocatedCount
FROM #UserRatio Order By OrderBy ASC
OPEN Cursor_UserAllocation
FETCH NEXT FROM Cursor_UserAllocation INTO @UserCode,@Ratio,@OrderBy,@AllocatedCount
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Ratio >= @AllocatedCount AND @IsAllocated = 'N')
BEGIN
Update #UserRatio
SET AllocatedCount = AllocatedCount + 1,
CanAllocate = 'Y'
WHERE UserCode = @UserCode
SET @IsAllocated = 'Y'
END
ELSE
BEGIN
Update #UserRatio
SET CanAllocate = 'N'
WHERE UserCode = @UserCode
END
FETCH NEXT FROM Cursor_UserAllocation INTO @UserCode,@Ratio,@OrderBy,@AllocatedCount
END
CLOSE Cursor_UserAllocation
DEALLOCATE Cursor_UserAllocation
GO
SELECT UserCode,Ratio, OrderBy,AllocatedCount
FROM #UserRatio Order By OrderBy ASC
Till now above code works fine. But now I want to reallocate from the start that's where I am stuck down.
Any help would be appreciated.
Thanks in Advance
