ABAP – create dynamic variable knowing reference tabname and fieldname

SAPIf you want to create a variable during runtime knowing only the reference table name and its field name (in string form), you can achieve it following the code presented in this article

data:
* Names of the table and its field
  g_tabname type tabname,
  g_fieldname type fieldname,

* Data references to table and its field
  gr_data_line type ref to data,
  gr_data_field type ref to data,

* Testing values
  g_test_value1 type char255 value '2021_error',
  g_test_value2 type char255 value '2021'.

FIELD-SYMBOLS:
  <fs_table_line> type any,
  <fs_table_line_field> type any.

* We want to create dynamic variable of type MARC-WERKS
g_tabname = 'MARC'.
g_fieldname = 'WERKS'.

*Create dynamic line of given table name
CREATE DATA gr_data_line TYPE (g_tabname).
ASSIGN gr_data_line->* to <fs_table_line>.

*Get reference to the required field
ASSIGN COMPONENT g_fieldname  OF STRUCTURE <fs_table_line> to <fs_table_line_field>.
CHECK sy-subrc = 0.

*Create dynamic variable with the same "structure" like the table field
CREATE DATA gr_data_field LIKE <fs_table_line_field>.

*Validation of data entered (not using either check or value table)
*just to make sure the value entered is accepted
<fs_table_line_field> = g_test_value1.
if <fs_table_line_field> = g_test_value1.
  write:/ 'OK'.
else.
  write:/ 'Error'.
endif.

<fs_table_line_field> = g_test_value2.
if <fs_table_line_field> = g_test_value2.
  write:/ 'OK'.
else.
  write:/ 'Error'.
endif.

Leave a Reply