Search code examples
abapopensql

Checking whether a record from a structure exist in a cluster table


I am trying to validate if a record in a structure is in a cluster table. The code that I thought of using is the following:

REPORT zzz.

DATA: BEGIN OF gs_zfi,
        number TYPE bseg-belnr,
      END OF gs_zfi.

START-OF-SELECTION.
  SELECT SINGLE @abap_true
    FROM bseg
    INTO @DATA(lv_belnr_exists)
    WHERE belnr = @gs_zfi-number. "number field has the same data element as the belnr(belnr_d)

  IF lv_belnr_exists IS INITIAL.
    MESSAGE a011(zfivald).
  ENDIF.

However, I am not allowed to use abap_true in a cluster table. Is there any similar way to check whether a record in the structure, i.e. the field number, exist in the belnr field of the table bseg?


Solution

  • To my knowledge, the most efficient and concise way to check if a certain row exists in a database table is SELECT SINGLE COUNT( * ). You don't even need a temporary variable, because you can just check sy-subrc or sy-dbcnt:

    SELECT SINGLE COUNT( * )
       FROM bseg
       WHERE belnr = @gs_zfi-number.
    IF sy-subrc = 0.
       " Record exists
    ELSE.
       " Record does not exist
    ENDIF.