简体   繁体   中英

Dynamic SELECT from arbitrary table

I have a Dropdown List in my Program in which I entered the names of different tables. So I worked with the IF-Statement. Basically:

if wa_list-key = '1'.
(replace name of table with the one choosen from the dropdown list)
endif.

I have this kind of selection:

select * from customer into table lt_customer.

Whats the syntax of replacing names of tables? I know replace-statements only work with strings but is there a way around?

You can dynamically select from a table:

DATA: lv_table TYPE tabname.

    SELECT * 
           INTO TABLE lt_table
           FROM (lv_table).

However the lt_table you select into, has to have the same structure like the database table you select from, otherwise it will dump. To overcome this you can use INTO COORESPONDING FIELDS OF lt_table (instead of INTO TABLE... ). You can also declare the WHERE conditions dynamically: WHERE (lv_where) It all depends on your exact needs.

In JozsefSzikszai answer you'll get dump when structure and database table will be different. So, you can try this-

DATA: lv_tabname TYPE tabname.

DATA: lo_tabtype     TYPE REF TO cl_abap_tabledescr,
      lo_struct_type TYPE REF TO cl_abap_structdescr,
      lr_data        TYPE REF TO data,
      lt_comp_tab    TYPE cl_abap_structdescr=>component_table,
      ls_comp_fld    TYPE cl_abap_structdescr=>component.

FIELD-SYMBOLS: <fs_tab> TYPE ANY TABLE,
               <fs_struct> TYPE ANY.

lv_tabname = 'ZTEST_DIV'.  " Give tab name from your dropdown select

lo_struct_type ?= cl_abap_typedescr=>describe_by_name( lv_tabname ).
lt_comp_tab  = lo_struct_type->get_components( ).

lo_struct_type = cl_abap_structdescr=>create( lt_comp_tab ).
lo_tabtype     = cl_abap_tabledescr=>create( lo_struct_type ).

CREATE DATA lr_data TYPE HANDLE lo_tabtype.
ASSIGN lr_data->* TO <fs_tab>.

*CREATE DATA lr_data TYPE HANDLE lo_struct_type. " Use this when you want same table structure
*ASSIGN lr_data->* TO <fs_struct>.

* dynamic select
SELECT *
  FROM (lv_tabname)
  INTO CORRESPONDING FIELDS OF TABLE <fs_tab>.

It will be more generic. It will create dynamic internal table using lv_tabname . So, on Select statement you won't get dump.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM