Internal Tables in SAP ABAP [ Part 2 ]

Reading contents of internal table:

Read statement is used to read a single row of internal table. Using this statement alters the value of sy-subrc and sy-tabix.

Syntax : read <internal_table> into <workarea> <condition>.
Ex:  read it_mara into wa_mara with key matnr = 100 binary search.
        read it_mara into wa_mara index 2.
After read statement , sy-tabix value will be the row number read and sy-subrc will be 0 if fetching is done. Index 2 means read the 2nd row of internal table it_mara.


Reading multiple lines in Internal table.

We can use loop to do the same.

Loop with Index.

LOOP AT it_mara INTO wa_mara FROM lv_index.
... <processing statements>.....
ENDLOOP.
Loop from row number lv_index.

Loop with Where condition.

LOOP AT it_mara INTO wa_mara where matnr = ‘123‘.
... <processing statements>.....
ENDLOOP.
Loop in it_mara where matnr value = 123

Loop without any index or Where condition

LOOP AT it_mara INTO wa_mara.
 ... <processing statements>.....
ENDLOOP.
sy-tabix holds the the current row number being processed .
sy-index is the loop counter.

When the loop is exited with ENDLOOP, sy-tabix is reset to the value it had before the loop was entered. sy-subrc is 0 (Implying the loop was run at least once) or 4(the loop was not run at all).

Modifying contents of internal table : 

'MODIFY' statement changes the content of one or several internal table lines that can be specified using the table key or the table index

Ex : MODIFY TABLE itab FROM wa TRANSPORTING field1.
Only change field1 taken from work area wa in internal table itab

MODIFY itab INDEX idx FROM wa TRANSPORTING field1.
Mentioning the line number for modification.

MODIFY itab FROM wa TRANSPORTING field2 WHERE field1 = ‘ ‘.
Additional condition apart from the primary fields of wa.

If you are looping through the internal table and modifying the contents , its recommended to use field symbols instead of work area.

In case of field symbols just use ASSIGNING <fieldsymbolname> instead of into.

EX:
LOOP AT it_mara ASSIGNING <wa_mara> FROM lv_index.
  ... <processing statements>.....
ENDLOOP.
Any changes done on <wa_mara> will be reflected back into the internal table