How to set dynamic key for READ TABLE?

B. Bowles picture B. Bowles · May 29, 2012 · Viewed 45.2k times · Source

I'm trying to work out a way to read an internal table that has to be created dynamically. I have created the following report that fills a dynamic internal table with data.

On the last line, I'm trying to read it with a key (mandt for example), but I I get this syntax error:

The specified type has no structure and therefore no component called MANDT

I have debugged and I can see that <any_tab> has been populated successfully and the structure of the table (field names) are correct. The problem presents itself when I try to read the table into a work area. Maybe I'm doing this wrong, but it seems like something that should be possible to do, and I have a feeling I'm missing something small.

The reason I am trying this out is that I have found identical selects happening in a program and want to buffer records in memory and read them from there to avoid DB accesses. This is easy to implement, however I haven't done this when the table, where clause and into clause of the OPEN SQL statement I'm trying to optimize are dynamic.

How to correct the syntax error?

DATA: t681_rep TYPE TABLE OF t681 , wa_681 LIKE LINE OF t681_rep,
      tabref TYPE REF TO data , waref TYPE REF TO data.

FIELD-SYMBOLS: <any_tab> TYPE ANY TABLE,
               <any_wa> TYPE ANY,
               <var1> TYPE ANY.
"fill t681_rep
SELECT *
  FROM t681
  INTO TABLE t681_rep
   UP TO 1 ROWS WHERE kotab = 'A002'.

READ TABLE t681_rep INTO wa_681 WITH KEY kotab = 'A002'.
IF sy-subrc = 0.

  "if A002 is found create a table of that type and fill it
  CREATE DATA tabref TYPE TABLE OF (wa_681-kotab).
  ASSIGN tabref->* TO <any_tab>.
  SELECT * UP TO 10 ROWS
    FROM (wa_681-kotab)
    INTO TABLE <any_tab>.

ENDIF.

CREATE DATA waref TYPE a002.
ASSIGN waref->* TO <any_wa>.

READ TABLE <any_tab> ASSIGNING <any_wa> WITH KEY mandt = '800'. <- problem area
IF sy-subrc = 0.
  "do stuff with <any_wa>...
ENDIF.

Answer

Bryan Cain picture Bryan Cain · May 29, 2012

You just need to put the field name in parentheses.

data: field type string.
field = 'MANDT'.
READ TABLE <any_tab> ASSIGNING <any_wa> WITH KEY (field) = '800'. 
IF sy-subrc = 0.
  "do stuff with <any_wa>...
ENDIF.