Application Development Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
cancel
Showing results for 
Search instead for 
Did you mean: 
Former Member
7,527

ABAP provides useful commands for selecting data from database tables. One of them is FOR ALL ENTRIES. This keyword is used before the WHERE statements. When FOR ALL ENTRIES is supplied for the SQL queries, WHERE condition will be applied for the internal table defined after for all entries.

Consider the following code snippet:

DATA:
ls_customer type KNA1,
lt_customer type table of KNA1,
lt_results type table of KNA1.
ls_customer-KUNNR =  '5010010346'.
ls_customer-LAND1 = 'DE'
ls_customer-KUNNR =  '5010010347'.
ls_customer-LAND1 = 'TR'
APPEND ls_customer  TO lt_customer.
SORT lt_customer BY kunnr.
SELECT * INTO TABLE lt_results
FROM KNA1
FOR ALL ENTRIES IN lt_customer
WHERE LAND1 = 'DE'.

In the execution of query LAND1='DE' first applied to lt_customer. After that database select is sent with the table entries that is filtered. Since the where condition is applied to internal table it makes significant performance improvement.

Consider the case where the internal table is empty.

DATA:
ls_customer type KNA1,
lt_customer type table of KNA1,
lt_results type table of KNA1.
APPEND ls_customer  TO lt_customer.
SELECT * INTO TABLE lt_results
FROM KNA1
FOR ALL ENTRIES IN lt_customer
WHERE LAND1 = 'DE'.

You assume that KNA1 is queried for LAND1 = 'DE'. Wrong! If internal table is empty WHERE condition has no importance. WHERE condition is omitted. This causes all KNA1 is selected!

To use FOR ALL ENTRIES keyword safely

1 - Do not forget to check if the internal table that's pass to FOR ALL ENTRIES is not empty

2 - SORT the internal table

Our code will look like this as result

DATA:
ls_customer type KNA1,
lt_customer type table of KNA1,
lt_results type table of KNA1.
ls_customer-KUNNR =  '5010010346'.
ls_customer-LAND1 = 'DE'
ls_customer-KUNNR =  '5010010347'.
ls_customer-LAND1 = 'TR'
APPEND ls_customer  TO lt_customer.
     IF lt_customer IS NOT INITIAL.
     SORT lt_customer BY kunnr.
     SELECT * INTO TABLE lt_results
     FROM KNA1
     FOR ALL ENTRIES IN lt_customer
     WHERE LAND1 = 'DE'.
ENDIF.
4 Comments
Labels in this area