Search code examples
abapnetweaver

Dynamically defined variable in ABAP


Lets say I have a variable (char30) which contains a name of a Datatype and I would like to create another variable of this Datatype.

Example:

lv_type = 'BU_PARTNER'
data: rt_value type range of ( lv_type ).

Any tips how to achieve this in ABAP?

Thanks!


Solution

  • RANGE table is just a STANDARD table with component like 'LOW', 'HIGH', 'EQ' and 'OPTION'.

    Using RTTS related API to create such a STANDARD table.

    data:
        lr_data          type ref to data,
        lt_ra_string     type range of string,
        ls_ra_string     like line of lt_ra_string,
        ls_component     type line of abap_component_tab,
        lt_component    type abap_component_tab,
        lt_ra_components type abap_component_tab,
        lo_struc_descr type ref to cl_abap_structdescr,
        lo_table_descr type ref to cl_abap_tabledescr,
        lo_data_descr  type ref to cl_abap_datadescr.
    
    field-symbols:
        <lv_value> type any,
        <lt_ra_type> type standard table,
        <ls_ra_type> type any.
    
        data(lv_type) = 'BU_PARTNER'.
    
    create data lr_data type (lv_type).
    
    lo_struc_descr ?= cl_abap_structdescr=>describe_by_data( p_data = ls_ra_string ).
    
    lt_component = lo_struc_descr->get_components( ).
    
    lo_data_descr ?= cl_abap_elemdescr=>describe_by_name( lv_type ).
    
    lt_ra_components = value #( for comp in lt_component (
                                name = comp-name
                                type = cond #( 
                                    when comp-name eq 'SIGN' 
                                      or comp-name eq 'OPTION'
                                    then  comp-type
                                    else lo_data_descr )
                            ) ).
    lo_struc_descr ?= cl_abap_structdescr=>create( lt_ra_components ).
    lo_table_descr ?= cl_abap_tabledescr=>create( lo_struc_descr ).
    
    create data lr_data type handle lo_table_descr.
    assign lr_data->* to <lt_ra_type>.
    
    create data lr_data like line of <lt_ra_type>.
    assign lr_data->* to <ls_ra_type>.
    
    assign component 'SIGN' of structure <ls_ra_type> to <lv_value>.
    <lv_value> = 'I'.
    assign component 'OPTION' of structure <ls_ra_type> to <lv_value>.
    <lv_value> = 'EQ'.
    assign component 'LOW' of structure <ls_ra_type> to <lv_value>.
    <lv_value> = 'DUMMY1'.
    assign component 'HIGH' of structure <ls_ra_type> to <lv_value>.
    <lv_value> = 'DUMMY2'.
    
    * <lt_ra_type> is your range table
    append <ls_ra_type> to <lt_ra_type>.