I have wrote this small piece of code which updates the data in it_alv based on values in another internal table it_alv_to_check.
At some point while executing the code in the ELSE statement block, I got the error:
field symbol has not been assigned yet
But I had it at first assigned dynamically using READ TABLE statement.
How to make sure that even if sy-subrc <> 0, the field symbol will be assigned?
FIELD-SYMBOLS: <to_check> LIKE LINE OF it_alv.
LOOP AT it_alv ASSIGNING FIELD-SYMBOL(<fs_alv_2>).
READ TABLE it_alv_to_check ASSIGNING <to_check> WITH KEY belnr = <fs_alv_2>-belnr.
IF sy-subrc = 0.
<fs_alv_2>-statement_year = <to_check>-statement_year.
<fs_alv_2>-laufi = <to_check>-laufi.
<fs_alv_2>-user_field_1 = <to_check>-user_field_1.
<fs_alv_2>-stceg = <to_check>-stceg.
<fs_alv_2>-name1 = <to_check>-name1.
<fs_alv_2>-monat_from = <to_check>-monat_from.
ELSE.
<fs_alv_2>-statement_year = <to_check>-statement_year.
<fs_alv_2>-laufi = <to_check>-laufi.
<fs_alv_2>-user_field_1 = <to_check>-user_field_1.
<fs_alv_2>-stceg = <to_check>-stceg.
<fs_alv_2>-name1 = <to_check>-name1.
<fs_alv_2>-monat_from = <to_check>-monat_from.
<fs_alv_2>-color = VALUE #( ( color-col = 6
color-int = 0
color-inv = 1
)
).
ENDIF.
ENDLOOP.
You cannot have your field-symbol assigned in this scenario. You read an internal table using
READ TABLEstatement and in case the entry was found with the given key (i.e.sy-subrc = 0), the found table row is assigned to a field symbol and the field symbol points to the table row in the memory.Otherwise, if no table row is found, you have no entry to assign field-symbol to, and the field symbol remains unchanged or initial. In this case you cannot rely on it being assigned (it can be assigned but point to the wrong entry) or assume the assignment itself (remains initial because it was not previously assigned).
More about it: READ TABLE, result ... ASSIGNING
Depending on what you want to achieve you can assign some default values in the else branch or implement some other logic to handle this scenario.