Internal Tables Part 8: LOOP Patterns — WHERE, Control Levels and Totals
Preview · a free account unlocks the full lesson
Process tables with the right loop pattern: LOOP WHERE, control-level processing with AT FIRST/AT NEW/AT END OF/SUM, FROM/TO ranges, and modern GROUP BY, VALUE FOR and REDUCE.
In this lessonShow sectionsHide sections
Visual overview
Explanation
Parts 1 through 7 covered table operations in general. Loops are where most business logic actually happens, and this part works through the patterns you will meet in classic code alongside their modern equivalents.
Filtering inside a loop is done with LOOP AT … WHERE, which filters inside the loop statement — cleaner, and on sorted tables faster, than putting an IF inside the loop body. For example: LOOP AT gt_flight INTO gs_flight WHERE carrid = 'LH' AND seatsocc < seatsmax. Index ranges work similarly for paging: LOOP AT gt_flight INTO gs_flight FROM 11 TO 20. On sorted tables, a WHERE condition on the leading key fields is optimized by the runtime.
Classic reports build subtotals using control-level processing: AT FIRST runs before the first row, useful for headers; AT NEW carrid runs whenever carrid, or any field to its left, changes, marking a new group; AT END OF carrid runs on the last row of a group, typically paired with SUM for a subtotal; and AT LAST runs after the very last row, for a grand total.
Control levels AT NEW / AT END OF / SUM need a table SORTED by the control fields, from left to right — the table must be sorted by the control fields first, and the control field order has to match the structure's own field order, since fields to the left count toward the grouping.
Inside an AT … ENDAT block, fields to the right of the control field show as '*' or come back initial, so anything you still need from them must be copied out before the AT block runs. SUM itself adds up all the numeric fields of the current group into the work area.
One trap to watch for: combining LOOP … WHERE together with AT NEW produces unexpected groups, since the control-level logic sees only the filtered rows — filter first, in a separate step, then loop with the control levels afterward.
Create a free account to keep reading
You have read the opening of this lesson. A free ERPClimb account unlocks the rest of it, every other lesson and topic, and your learning history, so you can pick up exactly where you stopped. No card needed.
- Full explanation
- Code example
- Real project scenario
- Common mistakes
- Best practices
- Interview angle
One tap with Google works too. Every topic keeps its first lesson open to everyone.
Keep exploring
Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.