Check whether an itab1 lines exist in itab2?

3.7k Views Asked by At

I have 2 internal tables typeв TYPE STANDARD TABLE OF string

The first table contains the data

| K1 |  K2 | K3 |

The second table contains the data

| K1 | K2 |

In ABAP, what is the fastest method to check if the second table entries are completely present in the first table? Maybe some inline function?

DATA lt_current_values TYPE stringtab.
DATA lt_previous_values TYPE stringtab.

APPEND 'K1' TO lt_previous_values.
APPEND 'K2' TO lt_previous_values.
APPEND 'K3' TO lt_previous_values.

APPEND 'K1' TO lt_current_values.
APPEND 'K2' TO lt_current_values.

DATA lv_count TYPE i.
LOOP AT lt_current_values INTO DATA(ls_cur).
  READ TABLE lt_previous_values TRANSPORTING NO FIELDS WITH KEY table_line = ls_cur.
  IF sy-subrc = 0.
    lv_count += 1.
  ENDIF.
ENDLOOP.

IF lv_count = LINES( lt_current_values ).
  " present => current_table values are already present in previous_table
ENDIF.
2

There are 2 best solutions below

2
On BEST ANSWER

The solution would be to temporarily use hashed tables with FILTER.

DATA lt_current_values TYPE stringtab.
FIELD-SYMBOLS <ls_current_values> LIKE LINE OF lt_current_values.
DATA lt_previous_values TYPE stringtab.
FIELD-SYMBOLS <ls_previous_values> LIKE LINE OF lt_previous_values.
DATA lth_current_values LIKE HASHED TABLE OF <ls_current_values> WITH UNIQUE KEY table_line.
DATA lth_previous_values LIKE HASHED TABLE OF <ls_previous_values> WITH UNIQUE KEY table_line.

lt_previous_values = VALUE #( ( `K1` ) ( `K2` ) ( `K3` ) ).
lt_current_values = VALUE #( ( `K1` ) ( `K2` ) ).

lth_current_values = lt_current_values.
lth_previous_values = lt_previous_values.

DATA(lt_difference) = FILTER #( lth_current_values EXCEPT IN lth_previous_values WHERE table_line = table_line ).

IF lines( lt_difference ) = 0.
  BREAK-POINT.
  " present => current_table values are already present in previous_table
ENDIF.
0
On

I would recommend 2 changes to your code:

DATA lt_current_values TYPE stringtab.
DATA lt_previous_values TYPE stringtab.

APPEND 'K1' TO lt_previous_values.
APPEND 'K2' TO lt_previous_values.
APPEND 'K3' TO lt_previous_values.

APPEND 'K1' TO lt_current_values.
APPEND 'K2' TO lt_current_values.
SORT lt_previous_values. " Sort the table to use binary search

DATA lv_count TYPE i.
LOOP AT lt_current_values INTO DATA(ls_cur).
  READ TABLE lt_previous_values TRANSPORTING NO FIELDS WITH KEY table_line = ls_cur BINARY SEARCH. " use Binary Search
  IF sy-subrc NE 0. " Check if it DOESN'T exist
    DATA(lv_not_contains_all) = abap_true. " Use a flag to check later
    EXIT. " Don't need to continue checking, this can save a lot of time
  ENDIF.
ENDLOOP.

IF lv_not_contains_all IS INITIAL.
  " present => current_table values are already present in previous_table
ENDIF.