SAP 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.
ABAP has three loop constructs: LOOP AT over an internal table, DO and ENDDO for a counted or unconditional loop, and WHILE for as long as a condition holds. Loop with ASSIGNING FIELD-SYMBOL rather than INTO a work area on large tables, since it avoids copying each row, and never place a database SELECT inside a loop over many rows.
- 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.