In the 2nd loop of the given stored sql procedure
BEGIN
SET NOCOUNT ON;
DECLARE
@ACounter INT = 1,
@AMax INT = 0,
@BCounter INT = 1,
@BMax INT = 0,
@selected_A_Id int,
@selected_B_Id int
Declare @A TABLE (
[ID] int identity,
A_Id int
)
Declare @B TABLE (
[ID] int identity,
B_Id int
)
INSERT INTO @A (A_Id)
SELECT A_Id FROM Table_A
SELECT @AMax = COUNT(Id) FROM @A
-- Loop A
WHILE @ACounter <= @AMax
BEGIN
select @selected_A_Id = A_Id FROM @A WHERE ID=@ACounter
Delete FROM @B;
INSERT INTO @B (B_Id)
SELECT B_Id FROM Table_B WHERE (FK_A_ID = @selected_A_Id)
SELECT @BMax = COUNT(ID) FROM @B
set @BCounter = 1
-- Loop B
WHILE @BCounter <= @BMax
BEGIN
select @selected_B_Id = B_Id FROM @B WHERE ID=@BCounter;
-- here I want to do something with @selected_B_Id
-- but @selected_B_Id gets set to the B_Id of the first record of table B and stays the same
-- throughout both loops
SET @BCounter = @BCounter + 1
END
SET @ACounter = @ACounter + 1
END
END
the declared variable @selected_B_Id should be set to a value from table B which is filled with records in loop A. But for some reason the value of @selected_B_Id does not change while looping through both loops.
I placed the declaration of @selected_B_Id inside loop B but that did not change the outcome.
Could someone please help me to get this correct?