How do I loop through each row in a table variable

For MS SQL 2005. I have a table variable with no ID column. How do I loop through each row, or how do I create an ID column so I can loop through it?
Who is Participating?
BrandonGalderisiConnect With a Mentor Commented:
I'm with unified in that you probably don't need to loop.  But here is how you define an ID column in your table variable.

declare @SomeTable table
  (ident       int identity primary key clustered
  ,field1       ......
What do you hope to accomplish by looping through the table?
The simple answer is: Don't. It's better to avoid looping through rows one at a time by writing set-based queries instead. Also, every table should have a key. There's no excuse for not having one on a table variable.
Never miss a deadline with

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

NobleRLCAuthor Commented:
I'm passing variables from the table variable to a stored procedure executed on each row.
You could pass all the rows to the proc as a table-valued parameter.
Or you could write the proc so that it works on the whole result instead of one row at a time.

Try to avoid writing procs that need to be called for every single row. Doing it that way greatly increases the complexity of your code and destroys performance and scalability.
Table valued parameters aren't available until 2008. :)  But the rest is all valid about doing procs to work with data sets not rows.
Chris LuttrellSenior Database ArchitectCommented:
When you have to do something like that we avoid cursors and do something like the code below, assuming that you have to leave the original table alone and that your values are unique so the delete just deletes the one:

Select Variable 
into #TmpTable  -- could be table variable, but you have to set it up
from Table
DECLARE @thisVariable [typeneeded]
	SELECT TOP 1 @thisVariable = Variable FROM #TmpTable
	EXEC yourStoredProcedure (@thisVariable)
	DELETE FROM #TmpTable WHERE Variable = @thisVariable

Open in new window

If you must call a proc for each row then I suggest you use an explicit DECLARE CURSOR iwith the FAST_FORWARD option. Using a cursor has the advantage over SELECT TOP because you can specify the order without having to requery the whole table on each iteration of the loop. Also a DECLARE CURSOR arguably makes it more explicit what is happening in loop.
All Courses

From novice to tech pro — start learning today.