Is there anyway to loop through a table variable in T-SQL?
DECLARE @table1 TABLE ( col1 int )
INSERT into @table1 SELECT col1 FROM table2
I use cursors as well, but cursors seem less flexible than table variables.
DECLARE cursor1 CURSOR
FOR SELECT col1 FROM table2
OPEN cursor1
FETCH NEXT FROM cursor1
I would like to be able to use a table variable in the same manner as a cursor. That way I could execute some query on the table variable in one part of the procedure, and then later execute some code for each row in the table variable.
Any help is greatly appreciated.
You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.
I would suggest finding a SET-BASED answer to your question (we can help with that) and move away from rbars as much as possible.
look like this demo:
Version without idRow, using ROW_NUMBER
Here is my version of the same solution...
Here's another answer, similar to Justin's, but doesn't need an identity or aggregate, just a primary (unique) key.
Here's my variant. Pretty much just like all the others, but I only use one variable to manage the looping.
Raj More's point is relevant--only perform loops if you have to.
Believe it or not, this is actually more efficient and performant than using a cursor.