Search code examples
abaprtts

Create a structure from a dynamically assigned <itab>


In a method I have a reference to a table that was declared like this:

DATA: tabname TYPE tabname,
      dref    TYPE REF TO data,
FIELD-SYMBOLS: <itab> TYPE ANY TABLE.

CREATE DATA dref TYPE TABLE OF (tabname).
ASSIGN dref->* TO <itab>.

SELECT * FROM (tabname)
    UP TO 5 ROWS
  INTO TABLE <itab>.

How do I create a structure based on ?


Solution

  • Just use good ol' RTTS for that. You can create reference and read directly into it

    FIELD-SYMBOLS: <itab> TYPE STANDARD TABLE.
    DATA: ref_wa        TYPE REF TO data,
          ref_rowtype   TYPE REF TO cl_abap_structdescr,
          ref_tabletype TYPE REF TO cl_abap_tabledescr.
    
    ref_rowtype ?= cl_abap_typedescr=>describe_by_name( tabname ).
    
    CREATE DATA ref_wa TYPE HANDLE ref_rowtype.
    READ TABLE <itab> REFERENCE INTO ref_wa INDEX 1.
    

    or create field-symbol based on this reference and use it in READ TABLE

    ASSIGN ref_wa->*  TO FIELD-SYMBOL(<fsym_wa>).
    READ TABLE <itab> ASSIGNING <fsym_wa> INDEX 1.
    

    Pay attention I declared <itab> as STANDARD table to get rid of index error operation you got.

    enter image description here

    UPDATE: for creating structure from <itab> object use this syntax:

    ref_tabletype ?= cl_abap_typedescr=>describe_by_data( <itab> ).
    ref_rowtype  ?= ref_tabletype->get_table_line_type( ).
    

    The last two lines will be identical.