Read internal table with dynamic specified keys

Here is a sample solution used when you need to read the internal table and when the names of keys can vary (they have to be specified dynamically).
REPORT zread_dyn.

TYPES:
  ts_data TYPE tstct, " table with descriptions of transakctions
  tt_data TYPE TABLE OF ts_data,

  BEGIN OF ts_query,
    name TYPE string,
    value TYPE string,
  END OF ts_query,
  tt_query TYPE TABLE OF ts_query.

  DATA:
    lt_data TYPE tt_data,
    ls_data TYPE ts_data,
    lt_query TYPE tt_query,
    ls_query TYPE ts_query.

START-OF-SELECTION.

* Load sample data
  SELECT *
    INTO TABLE lt_data
    FROM tstct
    WHERE sprsl = 'EN'
      AND tcode LIKE 'B%'.

* Specify combination of the keys for search
  ls_query-name = 'SPRSL'.  ls_query-value = 'EN'.    APPEND ls_query TO lt_query.
  ls_query-name = 'TCODE'.  ls_query-value = 'BAPI'.  APPEND ls_query TO lt_query.

  PERFORM read_table USING    lt_data
                              lt_query
                     CHANGING ls_data.

  WRITE: / ls_data-ttext.  " BAPI Explorer

*&---------------------------------------------------------------------*
*&      Form  read_table
*&---------------------------------------------------------------------*
FORM read_table USING    pt_data  TYPE tt_data
                         pt_query TYPE tt_query
                CHANGING ps_data  TYPE ts_data.

  DATA:
    ls_query     TYPE ts_query,
    lv_name_txt  TYPE string,
    lv_value_txt TYPE string,
    lv_tabix_txt TYPE string,
    lv_name1     TYPE string,
    lv_name2     TYPE string,
    lv_name3     TYPE string,
    lv_value1    TYPE string,
    lv_value2    TYPE string,
    lv_value3    TYPE string.

  FIELD-SYMBOLS:
    <fs_name>  TYPE string,
    <fs_value> TYPE string.

  LOOP AT pt_query INTO ls_query.
    lv_tabix_txt = sy-tabix.

    CONCATENATE 'LV_NAME' lv_tabix_txt INTO lv_name_txt.
    ASSIGN (lv_name_txt) TO <fs_name>.
    <fs_name> = ls_query-name.

    CONCATENATE 'LV_VALUE' lv_tabix_txt INTO lv_value_txt.
    ASSIGN (lv_value_txt) TO <fs_value>.
    <fs_value> = ls_query-value.
  ENDLOOP.

* Empty (lv_nameX) are ignored
  READ TABLE pt_data INTO ps_data WITH KEY (lv_name1) = lv_value1
                                           (lv_name2) = lv_value2
                                           (lv_name3) = lv_value3.
ENDFORM.                    "read_table
Full list of examples in my infodepot

If you have a question, have found an error or just want to contact me, please use this form.

Copyright (C) 2012 http://www.kerum.pl/infodepot/

Disclaimer: I am not affiliated or related to any division or subsidiary of SAP AG.
Trademarks or registered trademarks of any products or companies referred to on this site belong to those companies.
Anyone using the given solutions, is doing it under his/her own responsibility and at own risk.