Reading data from an Internal Table

Two statements are commonly used to read the data from an internal table.
  • loop at
  • read table
loop at is used to read multiple rows from the internal table.
read table is used to read a single row.

To read some or all rows from an internal table, you can use the loop at statement. loop at reads the contents of the internal table, placing them once at a time into a work area.

Syntax for the loop at statement :

loop at <internal table body> into <internal table work area>.
<statements>.
endloop.

Example :

loop at ITAB[] into ITAB.
write : / ITAB-A, ITAB-B.
endloop.

Syntax for conditional loop statement :

loop at <internal table body> into <internal table work area> from <m> to <n> where <expression>.
<statements>.
endloop.

Example :

loop at ITAB[] into ITAB from 2 to 5 where B = 10.
write : / ITAB-A, ITAB-B.
endloop.

Explanation :

  • internal table body is the name of the internal table body.
  • internal table work area is the name of the internal table work area.
  • m and n are integer literals, constants, or variables representing a relative row number. For example 1 means the first row in the table, 2 means the second, and so on.
  • expression is a logical expression restricting the rows that are read.
  • <statements> represents any number of lines of code. These lines are executed once for each row retrieved from the internal table.
The rows are read from the internal table one at a time and placed in succession into the work area. The lines of code between the loop at and endloop are executed for each row retrieved. The loop finishes automatically when the last row has been read, and the statement following the endloop is then executed.

The statement loop at ITAB[] into ITAB reads the row from ITAB[] and places it into header line ITAB . The statement loop at ITAB does the same thing, because the default work area is the header line. Being more succint, the latter is usually used.

The below program adds the 5 rows to the internal table and then displays it.

DATA : BEGIN OF ITAB OCCURS 5,
             A TYPE I,                                            
             B TYPE I,                                                    
             END OF ITAB.

ITAB-A = 1.
ITAB-B = 10.
APPEND ITAB.

ITAB-A = 2.
ITAB-B = 20.
APPEND ITAB.

ITAB-A = 3.
ITAB-B = 30.
APPEND ITAB.

ITAB-A = 4.
ITAB-B = 40.
APPEND ITAB.

ITAB-A = 5.
ITAB-B = 50.
APPEND ITAB.

LOOP AT ITAB.
WRITE : / ITAB-A. ITAB-B.
ENDLOOP.
--------------------------------------------------------------------------------------------------------------------------
O/P :

1       10
2       20
3       30
4       40
5       50
------------------------------------------------------------------------------------------------------------------------------




1 comment: