Loops
Loops let ABAP process data repeatedly, most importantly iterating over internal tables. Writing loops correctly, and efficiently, is central to almost every ABAP program.
Looping with ASSIGNING FIELD-SYMBOL avoids copying each row into a work area, faster and letting you modify the table row in place.
- The single most important ABAP performance rule involves loops: never put a database SELECT inside a loop over many rows.
- LOOP AT itab: iterate an internal table (the workhorse).
- DO... ENDDO: a counted or unconditional loop.
- Watch out: SELECT inside a loop, the top performance killer.
The main loop constructs
- LOOP AT itab: iterate an internal table (the workhorse).
- DO ... ENDDO: a counted or unconditional loop.
- WHILE ... ENDWHILE: loop while a condition holds.
Looping an internal table
LOOP AT lt_orders INTO DATA(ls_order) WHERE status = 'OPEN'.
" process ls_order
WRITE: / ls_order-order_id, ls_order-amount.
ENDLOOP.
" modern, field-symbol for performance (no copy)
LOOP AT lt_orders ASSIGNING FIELD-SYMBOL(<ls>).
<ls>-processed = abap_true.
ENDLOOP.Performance: the golden rule
The single most important ABAP performance rule involves loops: never put a database SELECT inside a loop over many rows. Read all needed data once (into an internal table) before the loop, then work in memory. A SELECT-in-LOOP over thousands of rows is the classic cause of a slow program.
Field-symbols and references
Looping with ASSIGNING FIELD-SYMBOL avoids copying each row into a work area, faster and letting you modify the table row in place. Prefer it for large tables.
Common pitfalls
- SELECT inside a loop, the top performance killer.
- Copying rows when a field-symbol would avoid it.
- Modifying a table while looping it incorrectly.