Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I loop through a table variable in T-SQL?

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.

like image 880
Kuyenda Avatar asked Oct 16 '09 13:10

Kuyenda


People also ask

How do you create a loop table in SQL?

First, create two table variables - and store in them 1-5, and 1-53 (for days and weeks). Then cartesian join the two and you're done! Change the last SELECT statement into an insert into your destination table and you're done.

Can you do a for loop in a SQL query?

Or, to repharse what I've just said - there isn't a for loop in SQL. WHILE @I < 10; SET @I = @I + 1; BEGIN; ...; END ? However, this should not be used for most query processing (but is sometimes required for imperative manipulation).


2 Answers

Add an identity to your table variable, and do an easy loop from 1 to the @@ROWCOUNT of the INSERT-SELECT.

Try this:

DECLARE @RowsToProcess  int DECLARE @CurrentRow     int DECLARE @SelectCol1     int  DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )   INSERT into @table1 (col1) SELECT col1 FROM table2 SET @RowsToProcess=@@ROWCOUNT  SET @CurrentRow=0 WHILE @CurrentRow<@RowsToProcess BEGIN     SET @CurrentRow=@CurrentRow+1     SELECT          @SelectCol1=col1         FROM @table1         WHERE RowID=@CurrentRow      --do your thing here--  END 
like image 149
KM. Avatar answered Oct 25 '22 09:10

KM.


DECLARE @table1 TABLE (     idx int identity(1,1),     col1 int )  DECLARE @counter int  SET @counter = 1  WHILE(@counter < SELECT MAX(idx) FROM @table1) BEGIN     DECLARE @colVar INT      SELECT @colVar = col1 FROM @table1 WHERE idx = @counter      -- Do your work here      SET @counter = @counter + 1 END 

Believe it or not, this is actually more efficient and performant than using a cursor.

like image 44
Justin Niessner Avatar answered Oct 25 '22 08:10

Justin Niessner