I have created an stored procedure in SQL Server 2008 and it contains the following code snippet:
WHILE (@COUNTER <= @COUNT_ROWSTOBEPROCESSED )
BEGIN
DECLARE @INFID AS INT =0;
DECLARE @TPID AS INT =0;
SELECT @INFID = InfID FROM @TEMPTABLE WHERE @@ROWCOUNT = @COUNTER;
print @INFID ;
SET @COUNTER = @COUNTER + 1;
END
But it gives me following result:
(106 row(s) affected)
0
-26
0
0
0
0
0
0
0
0 all are zeros ....
I have already values in the temp table but it is not initialized into @INFID variable.
Why it is happening? I don’t understand…
Please help me, if anyone have a solution.
—-Comment—
yeap, I have seen into my code. But here I have already added counter increment in my code. but still i have same problem.
when i have run the below query inside the loop. i found that @@RowCount is always 1.
SELECT InfID,@ROWCOUNT FROM @TEMPTABLE WHERE @@ROWCOUNT = @COUNTER;
Can u tell me how to iterate each row of temptable using while loop or for loop in sql?
WHERE @@ROWCOUNT = @COUNTERis incorrect.@@ROWCOUNTreturns the number of rows affected by the previous statement.It will only evaluate to
trueonce. (When@COUNTER= 1) so the rest of the time no assignment is made to@INFIDfrom theSELECToperation.What are you trying to do? My best guess is that you need to add an
IDENTITYcolumn to your table and reference that instead of@@ROWCOUNTor use a cursor.But if you explain your end goal we may be able to tell you a set based way of achieving whatever your goal is without RBAR processing.