Loop in loop with parallel cursor

Hi, in some cases you have to use a loop inside the loop. Why is that? because you return the inner table at every value of the outer table until you find the result in the WHERE condition. If you do not have hundreds of thousands of values in your hand, you will not notice it in terms of performance, but you should consider them when asked for performance improvement.

Example: outer table lt_vbak
Inner table lt_vbap

What is a parallel cursor? If the parallel cursor reads the keys of the inner table (lt_vbap) and does our job, enter the loop with index and check the keys, if the keys does not meet the value, exit the inner table loop with the exit.

The point to note here is that you will see the example below, instead of directly using the sy-tabix, throw it into a local variable.

The complete sample code:

SELECT *
  FROM vbak
  INTO TABLE @DATA(lt_vbak)
  UP TO 1000 ROWS.

CHECK lt_vbak IS NOT INITIAL.

SELECT *
  FROM vbap
  INTO TABLE @DATA(lt_vbap)
  FOR ALL ENTRIES IN @lt_vbak
  WHERE vbeln = @lt_vbak-vbeln.

"preparation for parallel cursor
DATA: lv_tabix TYPE i.

" you need to sort both tables,
SORT: lt_vbak BY vbeln,
      lt_vbap BY vbeln.

LOOP AT lt_vbak ASSIGNING FIELD-SYMBOL(<fs_vbak>).

* We are reading the keys of the second table.
* We will only take index, so TRANSPORTING NO FIELDS
  READ TABLE lt_vbap TRANSPORTING NO FIELDS
       WITH KEY vbeln = <fs_vbak>-vbeln
       BINARY SEARCH.
  IF sy-subrc EQ 0.
    lv_tabix = sy-tabix.
    LOOP AT lt_vbap FROM lv_tabix ASSIGNING FIELD-SYMBOL(<fs_vbap>) .
*   Instead of using WHERE, exit the loop by comparing values as follows.
      IF <fs_vbap>-vbeln NE <fs_vbak>-vbeln.
        EXIT.
      ENDIF.

      " If the conditions are met, write the code you will write here after

    ENDLOOP.
  ENDIF.
ENDLOOP.

Leave a Reply

Your email address will not be published. Required fields are marked *