How to use Table Expressions in SAP ABAP

Table expressions is similar to Read table query. The syntax for table expressions looks compact. It can read only one data record from an internal table.

The table expressions can be used in the following ways.

  1. Using Index
  2. Using Key
  3. Using Table Key

Using Index: –

DATA lt_contact TYPE TABLE OF ztt_db_table2.

DATA ls_contact TYPE ztt_db_table2.

SELECT *FROM ztt_db_table2 INTO TABLE lt_contact.

ls_contact = lt_contact[1].

The above assignment is done to a work area. It can also be assigned to a Field Symbol like below.

ASSIGN lt_contact[1] TO FIELD_SYMBOL(<ls_contact1>).

It is assigned to the Field_Symbol through inline declaration.

Using Key: –

ASSIGN lt_contact[ contact_id = 102 ] TO FIELD_SYMBOL(<ls_contact1>).

Using Table Key: –

DATA lt_sorted_contact TYPE SORTED TABLE OF ztt_db_table2 WITH UNIQUE KEY contact_id.

DATA ls_sorted_contact TYPE ztt_db_table2.

SELECT *FROM ztt_db_table2 INTO TABLE lt_sorted_contact.

ls_sorted_contact = lt_sorted_contact[ KEY primary_key COMPONENTS contact_id = 101 ].

WRITE: / ls_sorted_contact-contact_name.

Through field symbol.

ASSIGN lt_sorted_contact[ KEY primary_key COMPONENTS contact_id = 101] TO                                          FIELD_SYMBOL(<ls_contact>).

WRITE: / <ls_contact>-contact_name.

What is similar to the Read Table query in SAP ABAP during the assignment to field symbol.

ASSIGN lt_contact[contact_id = 102 ] TO FIELD_SYMBOL(<ls_contact>).

IF sy_subrc = 0

              WRITE: / ‘Data Record is found’.

Else

              WRIITE: / ‘Data Record not found’.

ENDIF.

During assignment of Data record to a field-symbol, if the record exists then it returns sy_subrc = 0. It is similar to the following Read Table query in SAP ABAP.

READ TABLE lt_contact ASSIGNING FIELD_SYMBOL(<ls_contact>).

IF sy_subrc = 0.

              Write: / ‘Data record exists’.

ELSE

              Write: / ‘Data record does not exist’.

ENDIF.

What is difference between Table expressions and Read table during the assignment to a work area.

Table expressions: It result in runtime error with the following exception when the Data record is not found ‘CX_SY_ITAB_LINE_NOT_FOUND’ error.

Read Table: It returns sy_subrc = 8 when the Data record is not found.

TRY.

              ls_contact = lt_contact[contact_id = 106].

              CATCH cx_sy_itab_line_not_found INTO DATA(lx_error).

ENDTRY.