Concatenate fields of a dynamic structure

Czarinaaaaa29 picture Czarinaaaaa29 · Dec 28, 2017 · Viewed 7.9k times · Source

How do we concatenate fields of a dynamic work area? The idea is in the below code:

LOOP AT lt_final INTO DATA(ls_final).
  CONCATENATE ls_final-field1
              ls_final-field2
              ls_final-field3
              ls_final-field4
              ls_final-field5
         INTO ls_attachment SEPARATED BY lc_tab.   "lc_tab is horizontal tab

  APPEND ls_attachment TO lt_attachment.
  CLEAR: ls_attachment.
ENDLOOP.

(This code will be used for sending email attachment.) Now, my problem is, the internal table in the above code is a dynamic internal table, therefore I am not sure how many fields will be there and the field names as well.

How do I concatenate the fields? Any idea, please help..

LOOP AT <dynamic_table> INTO DATA(ls_final).
  CONCATENATE ls_final-(?)
              ls_final-(?)
              ls_final-(?)
              ls_final-(?)
              ls_final-(?) 
              "or more fields insert here depending on dynamic table
         INTO ls_attachment SEPARATED BY lc_tab.   "lc_tab is horizontal tab

  APPEND ls_attachment TO lt_attachment.
  CLEAR: ls_attachment.
ENDLOOP.

Answer

J&#243;zsef Szikszai picture József Szikszai · Dec 29, 2017
FIELD-SYMBOLS: <lv_field> TYPE ANY.

LOOP AT lt_final
     ASSIGNING FIELD-SYMBOL(<ls_final>).
  DO.
    ASSIGN COMPONENT sy-index
           OF STRUCTURE <ls_final>
           TO <lv_field>.
    IF sy-subrc EQ 0.
      IF sy-index EQ 1.
        ls_attachment = <lv_field>.
      ELSE.
        ls_attachment = ls_attachment && lc_tab && <lv_field>.
      ENDIF.
    ELSE.
      EXIT.
    ENDIF.
  ENDDO.
ENDLOOP.

I hope it is self explaining, but: You can use the system variable (sy-index), it is incremented automatically by SAP. In the first step, just copy the value, there is nothing to concatenate yet (otherwise there will be an unnecessary lc_tab at the beginning of the string).