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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
4 | |
3 | |
2 | |
2 | |
1 | |
1 | |
1 | |
1 | |
1 | |
1 |