VERIFIED SOLUTION i
How to loop a table in MapBasic
One of the often used things in MapBasic is to loop thru a table to read values from the table and then react to or modify these values.
MapBasic has a number of looping methods:
- Do Until ... Loop
- Do While ... Loop
- While ... Wend
- For ... Next
However one seems better than the others when it comes to looping a table: Do Until ... Loop. At least that's the one I have been using for years. You can also use Do While ... Loop and While ... Wend.
But I will recommend that you stay away from For ... Next when looping thru a table. I'll get back to why.
Now you need a few other statements as well when looping a table:
- Fetch First From some_table_name
- Fetch Next From some_table_name
- EOT( some_table_name )
Let's try to put all this together:
Set CoordSys Table MY_TABLE Fetch First From MY_TABLE Do Until EOT(MY_TABLE) nRowID = MY_TABLE.ROWID oFeature = MY_TABLE.OBJ Fetch Next From MY_TABLE Loop
In the example above I loop the table called MY_TABLE. For each record I read the RowID, the hidden dynamic column referring to a specific post in a table or query, and the spatial object from the column called OBJ.
Oh, and I set my application to use the same coordinate system as the table before I start looping.
Now this loop doesn't really do anything clever yet. I would need to add my logic just before the Fetch Next From statement.
I also promised to explain why you shouldn't use the For ... Next loop when working with a table. The problem isn't as much the loop, but more that people tend to combine this loop with a different Fetch statement; Fetch Rec nRec From.
Dim nRec, nRowID As Integer, oFeature As Object Set CoordSys Table MY_TABLE For nRec = 1 To TableInfo(MY_TABLE, TAB_INFO_NROWS) Fetch Rec nRec From MY_TABLE nRowID = MY_TABLE.ROWID oFeature = MY_TABLE.OBJ Next
Don't use this structure!!
This Fetch statement will put the table cursor at a specific row in the table, which in most case is fine. But it has a drawback; it will fail if the specific row has been deleted. And if you haven't built-in error handling in your application, the application will crash.
Fetch Next, on the other side, will skip the deleted records during the loop.
UPDATED: March 26, 2018