ABAP 7.40 Inline Loop

2016/12/01

Despite not very programmer-friendly syntax of new features ABAP 7.40 you might have situations where it can be extremely useful.

Occasionally I have to have nested loops. It is a case when I need to calculate some key figures over the dataset depending on the time interval (Start / End date). I try to explain this with an example. Let’s say you have the internal table for the working hours of your external workers:

TYPES: BEGIN OF ts_working_hours_extern,
   employee_id TYPE e_id,
   begda       TYPE begda,
   endda       TYPE endda,
   hours       TYPE i,
 END OF ts_working_hours_extern.
TYPES tt_working_hours_extern TYPE STANDARD TABLE OF ts_working_hours_extern.
DATA lt_working_hours TYPE tt_working_hours_extern.

The second internal table contains the sales produced by external workers:

TYPES: BEGIN OF ts_sales,
   sale_id     TYPE s_id,
   employee_id TYPE begda,
   date        TYPE d,
 END OF ts_sales.
TYPES tt_sales TYPE STANDARD TABLE OF ts_sales.
DATA lt_sales TYPE tt_sales.

Your task is to calculate the ratio of working hours to the result of work for each external worker. Earlier you go:

LOOP AT lt_working_hours ASSAGNING <fs_wh>.
  CLEAR ls_result.
  MOVE-CORRESPONDING <fs_wh> TO ls_result.
LOOP AT lt_sales ASSIGNING <fs_sales> 
                   WHERE employee_id = <fs_wh>-employee_id
                     AND date <= <fs_wh>-endda
                     AND date >= <fs_wh>-begda.
    ls_result-number_sales = ls_result-number_sales + 1.
 ENDLOOP.
 APPEND ls_result TO lt_result.
ENDLOOP.

Using ABAP 7.40 you can achieve the same the way faster:

LOOP AT lt_working_hours ASSAGNING <fs_wh>.
  CLEAR ls_result.
  MOVE-CORRESPONDING <fs_wh> TO ls_result.
  DATA(lt_sales_wa) = VALUE tt_sales( FOR wa in lt_sales )
                    ( WHERE employee_id = <fs_wh>-employee_id
                     AND date <= <fs_wh>-endda
                     AND date >= <fs_wh>-begda )
                    ( wa ) ).
  ls_result-number_sales =  lines( lt_sales_wa ).
  APPEND ls_result TO lt_result.
ENDLOOP.

If you have a large dataset of sales the inline loop can improve your performance significantly. But if you try to activate this code you’ll get an error message saying that dynamic type can’t be constructed. As it turned out the type tt_sales has to be a table with a key. If you can’t have a key in your internal table you can use newly introduced DEFAULT KEY addition. Basically, the whole line of your internal table becomes a key:

TYPES tt_sales TYPE STANDARD TABLE OF ts_sales WITH DEFAULT KEY.
>> Home