Register Login

LOOP AT with WHERE Clause

Updated May 18, 2018

Performance Problem with Internal Tables being Read with WHERE Clause in LOOP AT Statement

If one use a LOOP AT statement with a WHERE clause, the whole TABLE will be read through not only the entries that satisfy the WHERE clause. This can lead to performance problems when a very large internal table is being read many times with a WHERE clause.

The solution is to sort the table on the keyfields, use a READ statement to find the first entry that satisfies the key. Then you can start the loop here, and check for changes in the keyfield to exit the loop.

The following Code should not be applied:

loop at gi_mseg into g_mseg
where matnr = p_matnr and
werks = p_werks and
lgort = p_lgort and
sobkz = space,

endloop.

Instead of above-mentioned code, one should apply the following:

* Sort internal table with entries from MSEG
sort gi_mseg by matnr werks lgort.

* Find index of first entry that satisfies the where clause data:
l_tabix_from like sy-tabix.

read table gi_mseg with key matnr = p_matnr
werks = p_werks
lgort = p_lgort binary search
into g_mseg.
check sy-tabix > 0.

move sy-tabix to l_tabix_from.

* Loop over the table from l_tabix_from, check for changes in keyfields, and
* if necessary check other fields.

loop at gi_mseg into g_mseg from l_tabix_from.
if g_mseg-matnr <> p_matnr or
g_mseg-werks <> p_werks or
g_mseg-lgort <> p_lgort.
* Stop loop
exit.
endif.

* Check other fields
check g_mseg-sobkz = space.

endloop.

 


Comments

  • 28 Sep 2017 11:19 am Guest

    It would be better to define the table as sorted table <<with  key>>. Then no read is necessary.


×