Dynamic typing: loop through string table, output typed table

Routine below shows method that takes string internal table, and outputs to typed table.

...
  types:
    BEGIN OF ty_tape,
        data(10000),
      END OF ty_tape .
  types:
    ty_t_tape TYPE STANDARD TABLE OF ty_tape WITH NON-UNIQUE KEY data .
...

...
METHODS:
      set_attribute
        IMPORTING
          im_t_tape      TYPE ty_t_tape
        EXPORTING
          ex_t_attribute TYPE ANY TABLE.
...


  METHOD set_attribute.

   FIELD-SYMBOLS:
      <fs_it_table> TYPE ANY TABLE,
      <fs_wa_line>  TYPE any.

    DATA:
      lo_tabledescr     TYPE REF TO cl_abap_tabledescr,
      lo_elemdescr TYPE REF TO cl_abap_elemdescr,
      lv_structure_name TYPE typename,
      lo_dt_table       TYPE REF TO data,
      lo_dt_line        TYPE REF TO data.

    lo_tabledescr    ?= cl_abap_tabledescr=>describe_by_data( ex_t_attribute ).

    DATA(lo_datadescr) = lo_tabledescr->get_table_line_type( ).

    DATA(lv_type_offset) = find(
                            val   = lo_datadescr->absolute_name
                            sub   = c_type_string ).

    IF lv_type_offset < 0.
      MESSAGE e016(pn) WITH 'Error determining TYPE dynamically'.
    ENDIF.

    lo_elemdescr ?= cl_abap_datadescr=>describe_by_data( lv_structure_name ).

    lv_type_offset = lv_type_offset + strlen( c_type_string ).
    lv_structure_name = lo_datadescr->absolute_name+lv_type_offset(lo_elemdescr->output_length).

    CREATE DATA lo_dt_table TYPE TABLE OF (lv_structure_name).
    ASSIGN lo_dt_table->* TO <fs_it_table>.

    CREATE DATA lo_dt_line TYPE (lv_structure_name).
    ASSIGN lo_dt_line->* TO <fs_wa_line>.

    LOOP AT im_t_tape
      INTO DATA(lw_tape).

      WRITE lw_tape TO <fs_wa_line>.
      INSERT <fs_wa_line> INTO TABLE ex_t_attribute.

    ENDLOOP.

  ENDMETHOD.

Leave a Reply