Search code examples
abaprtti

Is it possible to create dynamic internal table with keys?


Is it possible to create dynamic internal table with keys ? I am working with

    call method cl_alv_table_create=>create_dynamic_table
                     exporting 
                         it_fieldcatalog = lt_fldcat[]
                     importing 
                         ep_table        = lr_new_table

this gives the result without keys so I am not able to perform

    read table <ft_itab> from <fs_itab> ....

where "fs_itab" should be line of "ft_itab" with keys (specified in lt_fieldcat[]). Using method above is TABLE_LINE also a table key.


Solution

  • To create a variable of any type dynamically at runtime, you may use the RTTC classes, followed by the statement CREATE DATA data_reference TYPE HANDLE rtti_instance.

    For an internal table with its line being a structure (made of one or more fields), define first the structure with RTTC, then the internal table.

    @Allen has shown a code sample in this other question: Dynamically defined variable in ABAP

    To create a table type with a given primary key, use the parameters of the method CREATE of CL_ABAP_TABLEDESCR ; below is another writing of Allen's CREATE, but this one has a non-unique sorted primary key with components SIGN and LOW :

    lo_table_descr = cl_abap_tabledescr=>create(
          p_line_type  = lo_struc_descr
          p_table_kind = cl_abap_tabledescr=>tablekind_sorted
          p_unique     = abap_false
          p_key        = VALUE #( ( 'SIGN' ) ( 'LOW' ) )
          p_key_kind   = cl_abap_tabledescr=>keydefkind_user
          ).
    

    You may also create the type with secondary keys, but I guess you don't need it.