Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

abap

opensql

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?

like image 763
Frank Avatar asked Oct 22 '25 00:10

Frank


2 Answers

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.
like image 72
Philipp Avatar answered Oct 25 '25 01:10

Philipp


As mentioned in the comment there is no syntax error on an SAP HANA system. What you can do is following.

REPORT zzz.

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

START-OF-SELECTION.
  SELECT SINGLE belnr
    FROM bseg
    INTO @DATA(lv_belnr)
    WHERE belnr = @gs_zfi-number.

  DATA(lv_belnr_exists) = xsdbool( sy-subrc = 0 ).

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

Alternatively

REPORT zzz.

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

START-OF-SELECTION.
  SELECT belnr FROM bseg
    INTO @DATA(lv_belnr)
    WHERE belnr = @gs_zfi-number.
    DATA(lv_belnr_exists) = abap_true.
    EXIT.
  ENDSELECT.

  IF lv_belnr_exists IS INITIAL.
    MESSAGE a011(zfivald).
  ENDIF.
like image 32
Jagger Avatar answered Oct 25 '25 02:10

Jagger