一个例子:
这里加入的是一列日期,大体的结构就是这样。
FORM frm_create_dyntable TABLES it_table .
DATA lt_table TYPE TABLE OF dfies. "字段结构表
DATA ls_table TYPE dfies.
DATA lr_struc TYPE REF TO cl_abap_structdescr.
DATA lr_table TYPE REF TO cl_abap_tabledescr.
DATA lt_comp TYPE abap_component_tab.
DATA ls_comp LIKE LINE OF lt_comp.
DATA dyn_wa TYPE REF TO data.
DATA dyn_table TYPE REF TO data.
DATA lr_type TYPE REF TO cl_abap_typedescr.
DATA: l_tabledescr_ref TYPE REF TO cl_abap_tabledescr,
l_descr_ref TYPE REF TO cl_abap_structdescr.
FIELD-SYMBOLS: <fs_wa> ,
<fs_comp_wa> TYPE abap_compdescr.
DATA: l_sta_date TYPE zpp_moldsche-sdate ,
l_end_date TYPE zpp_moldsche-sdate .
FIELD-SYMBOLS : <field> .
DATA:l_mng01 TYPE mng01 .
DATA:l_it_output TYPE ty_output.
l_tabledescr_ref ?= cl_abap_typedescr=>describe_by_data( it_table[] ).
l_descr_ref ?= l_tabledescr_ref->get_table_line_type( ).
"循环表头的每一个字段
LOOP AT l_descr_ref->components ASSIGNING <fs_comp_wa>.
ls_comp-name = <fs_comp_wa>-name .
ASSIGN COMPONENT <fs_comp_wa>-name OF STRUCTURE l_it_output TO <field> .
CALL METHOD cl_abap_datadescr=>describe_by_data
EXPORTING
p_data = <field>
RECEIVING
p_descr_ref = lr_type
EXCEPTIONS
OTHERS = 2.
ls_comp-type ?= lr_type.
APPEND ls_comp TO lt_comp.
ENDLOOP.
"这里如果只有月份字段,可以这样处理,CONCATENATE s_month-low+0(4) s_month-low+4(2) '01' INTO l_month_c.l_month = l_month_c.传l_month到FM.
l_sta_date = g_sta_date.
l_end_date = g_end_date.
"创建日期字段
WHILE l_sta_date <= l_end_date .
CONCATENATE zprefix l_sta_date INTO ls_comp-name.
ASSIGN l_mng01 TO <field> .
CALL METHOD cl_abap_datadescr=>describe_by_data
EXPORTING
p_data = <field>
RECEIVING
p_descr_ref = lr_type
EXCEPTIONS
OTHERS = 2.
ls_comp-type ?= lr_type.
APPEND ls_comp TO lt_comp.
CALL FUNCTION 'RP_CALC_DATE_IN_INTERVAL'
EXPORTING
date = l_sta_date
days = 1
months = 0
signum = '+'
years = 0
IMPORTING
calc_date = l_sta_date
EXCEPTIONS
OTHERS = 2.
ENDWHILE .
*根据字段目录创建动态结构类型
CALL METHOD cl_abap_structdescr=>create
EXPORTING
p_components = lt_comp
RECEIVING
p_result = lr_struc.
*根据动态结构创建动态内表类型
CALL METHOD cl_abap_tabledescr=>create
EXPORTING
p_line_type = lr_struc
RECEIVING
p_result = lr_table.
*参照动态结构类型和动态内表类型创建内表与工作区
CREATE DATA dyn_wa TYPE HANDLE lr_struc.
CREATE DATA dyn_table TYPE HANDLE lr_table.
*指定内表与工作区到字段符号
ASSIGN dyn_wa->* TO <dyn_wa>.
ASSIGN dyn_table->* TO <dyn_table>.
ENDFORM. "frm_create_dyntable