Search code examples
abapinternal-tables

Best way to check if a line with non-initial field exists?


Let's say I have a table quants and want to find out if any line exists, where the field lenum is not initial. The table is declared inline using a select statement, so I do not have a key available.

Because I don't have a key, the following solution does not work:

line_exists( VALUE #( FOR wa IN quants WHERE ( lenum IS NOT INITIAL ) ( wa ) ) )

Since I want to check for inequality, a table expression does not work:

line_exists( quants[ lenum NE '' ] )

The only solution that I have come up with so far is the following:

abap_true EQ REDUCE abap_bool( INIT bool = abap_false FOR quant IN quants WHERE ( lenum IS NOT INITIAL ) NEXT bool = abap_true )

Obviously there are "old fashioned" solutions, but is there any newer-style?

By "old fashioned" I mean solutions like this:

LOOP AT quants INTO DATA(wa).
  IF wa-lenum IS INITIAL.
    DATA(found) = abap_true.
  ENDIF.
ENDLOOP.
IF found EQ abap_true.
  ...
ENDIF.

Solution

  • The only thin in "new fashion" would be SELECT, FROM @itab.

    DATA(lv_exists) = abap_false.
    SELECT SINGLE @abap_true FROM @lt_quant AS quant WHERE quant~lenum IS NOT INITIAL INTO @lv_exists.
    

    See documentation link for performance impact (best case is handled like a table in the table buffer) and limitations (e.g. no string column).

    The most performant and less restrictions would be this:

    LOOP AT lt_quant TRANSPORTING NO FIELDS WHERE lenum IS NOT INITIAL.
      EXIT.
    ENDLOOP.
    DATA(lv_exists) = xsdbool( sy-subrc = 0 ).