简体   繁体   English

从任意表动态选择

[英]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.所以我使用了 IF 语句。 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.但是,您选择的 lt_table 必须与您从中选择的数据库表具有相同的结构,否则它将转储。 To overcome this you can use INTO COORESPONDING FIELDS OF lt_table (instead of INTO TABLE... ).为了克服这个问题,您可以使用INTO COORESPONDING FIELDS OF lt_table (而不是INTO TABLE... )。 You can also declare the WHERE conditions dynamically: WHERE (lv_where) It all depends on your exact needs.您还可以动态声明 WHERE 条件: WHERE (lv_where)这一切都取决于您的确切需求。

In JozsefSzikszai answer you'll get dump when structure and database table will be different.在 JozsefSzikszai 的回答中,当结构和数据库表不同时,您会得到转储。 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 .它将使用lv_tabname创建动态内部表。 So, on Select statement you won't get dump.因此,在 Select 语句中,您不会得到转储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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