ABAP:如何通过动态确定 table 字段在循环中获取值

ABAP : How to get value in loop by determine table field dynamically

在 SAP 中有一个 table T552A。有几个字段,如 TPR、TTP、FTK、VAR、KNF,每个月的日期,如 TPR01、TPR02 等

在一个循环中,我想通过动态确定 table 字段而不是硬编码字段名称来访问上述字段,如下所示:

  DATA: ld_begda LIKE sy-datum,
        ld_endda LIKE sy-datum.
  DATA: lc_day(2) TYPE c.
  DATA: lc_field(10) TYPE c.
  DATA: lc_value TYPE i.

  ld_begda = sy-datum.
  ld_endda = ld_begda + 30.

  WHILE ld_begda <= ld_endda.
    lc_day = ld_begda+6(2).
    CONCATENATE 't552a-tpr' lc_day INTO lc_field.
    lc_value = &lc_field.   " Need support at this point.
    

    ld_begda = ld_begda + 1.
  ENDWHILE.

要存储动态字段的结果,需要一个可以存储任意类型值的变量,在 ABAP 中,这是通过 field symbols 支持的。 然后可以将结构的组件(即 table 的行)分配给具有 ASSIGN COMPONENT:

的字段符号
ASSIGN COMPONENT lc_field OF STRUCTURE row_of_table TO FIELD-SYMBOL(<value>).
" work with <value> here

最近 new generic expressions were introduced (and now also support structures) 允许你写这个(迟早):

 ... row_of_table-(lc_field) ...

像这样(取决于具体要求):

  FIELD-SYMBOLS: <lv_tpr> TYPE tprog.  
  DATA: ls_t552a TYPE t552a.
  DATA: lv_field TYPE fieldname.

  WHILE ld_begda <= ld_endda.
    lv_field = |TPR| && ld_begda+6(2).  "Dynamic field name
    ASSIGN COMPONENT lv_field
           OF STRUCTURE ls_t552a
           TO <lv_tpr>.
    IF sy-subrc EQ 0.
      ... "<lv_tpr> has now the value of the corresponding field
    ENDIF.

    ld_begda = ld_begda + 1.
  ENDWHILE.