Let’s take an example of a traditional read statement.
REPORT ztest_read_statement. SELECT * FROM vbap UP TO 50 ROWS INTO TABLE @DATA(lt_vbap). IF sy-subrc EQ 0. READ TABLE lt_vbap INTO DATA(ls_vbap) WITH KEY vbeln = '0000000020'. WRITE ls_vbap-vbeln. ENDIF.
The above read statement can be replaced with new ABAP syntax
REPORT ztest_read_statement. SELECT * FROM vbap UP TO 50 ROWS INTO TABLE @DATA(lt_vbap). IF sy-subrc EQ 0. DATA(ls_vbap) = VALUE #( lt_vbap[ vbeln = '0000000020' ] OPTIONAL ). WRITE ls_vbap-vbeln. ENDIF.
In both the case, the result would be Result: 20
What is the meaning of VALUE # and OPTIONAL keyword in the new syntax
VALUE – It is an operator which returns an operand with a specific data type. The syntax would be VALUE type(…) . Here we have mentioned # means the type would be determined based on the result of the operation.
If you want to extract a single field instead of an entire work area. then code would be like
DATA(lv_vbeln) = VALUE #( lt_vbap[ vbeln = '0000000020' ]-vbeln OPTIONAL ).
it just as similar to workarea-<Field name> after read statements
OPTIONAL – It is always safe to write the optional keyword. the functionality of this keyword when the table expression does not return value then it will return the default value.
Let’s test what will happen when internal table does not contain the required vbeln and you don’t write the OPTIONAL keyword.😅
DATA(lv_vbeln) = VALUE #( lt_vbap[ vbeln = '0000000999' ]-vbeln ).
Here there is no order with order number 999. the table expression will return nothing hence the runtime error😡
So there are two ways to handle the situation either handle by catching the raised expression which is a bitter way and the second one with the OPTIONAL keyword.
Let’s go to its advantage and disadvantage
1. These new syntaxes are easy to write and looks compact
2. As these are expressions, so this can be used wherever you can other expressions like in IF condition it was not possible to write read statement but possible with table expression. let’s take an example
IF ( VALUE #( lt_vbap[ vbeln = '0000000020' ]-matnr OPTIONAL ) ) EQ 'TEST CE'. WRITE: 'Found'. ENDIF.
1. The main disadvantage is SY-SUBRC. The new read statement/table expression always gives sy-subrc = 0 unlikely in the old read statement like 0 or 8. Take care of that during implementation
2. Also SY-TABIX won’t be updated.
3. There is no BINARY SEARCH😭 , unlike the old read table syntax.
Hopefully, it clear the concept of the new Read statement comment for questions/suggestions.
Check out our OData series: OData – ABAP Skill