How To Read a Dynamic Internal Table in SAP ABAP

How To Read a Dynamic Internal Table in SAP ABAP

You might have faced a situation where you have to read data from an internal table whose structure is declared dynamically through the program. When you use READ STATEMENT to read data from internal table using the key field you might have faced an error " The specified type has no structure and hence no component called "<fieldname>" <field name> is the name that you have specified in the key of read statement.

For example consider the below program.

REPORT ZTEST.

DATA: gv_tabname TYPE tabname VALUE 'BKPF',
            gv_field TYPE string VALUE 'BUKRS'.

DATA: tab_ref  TYPE REF TO DATA,
            wa
_ref  TYPE REF TO DATA.

FIELD-SYMBOLS: <itab> TYPE ANY TABLE,
                                   <wa> TYPE ANY.

CREATE DATA tab_ref  TYPE TABLE OF (gv_tabname) .
ASSIGN tab_ref->* to <itab>.

CREATE DATA wa_ref  TYPE  (gv_tabname) .
ASSIGN wa_ref->* to <wa>.

SELECT * FROM (gv_tabname)
INTO TABLE <itab>
UPTO 10 ROWS.

IF sy-subrc IS INITIAL.

    READ TABLE <itab> INTO <wa> WITH KEY (gv_field) = '1000'.

    IF sy-subrc IS INITIAL.

          WRITE: 'READ SUCCESS'.

    ENDIF

ENDIF.

If you observe the above program at READ TABLE the key field is specified in brackets as (gv_field). The internal table <itab> structure is not specified in the program. But based on the table name specified in gv_tabname the structure is prepared dynamically at runtime using the CREATE DATA statement. Here we have hardcoded table name as BKPF, but you can make it as input parameter also.

In this scenario as the structure is prepared at runtime we couldn't specify the key field directly as below.

READ TABLE <itab> INTO <wa> WITH KEY BUKRS = '1000'.

The above read will show errors when trying to activate the program. So we have to pass the field name in below format.

READ TABLE <itab> INTO <wa> WITH KEY ('BUKRS') = '1000'.

(or)

READ TABLE <itab> INTO <wa> WITH KEY (gv_field) = '1000'. when the table is passed from a variable gv_field.

I hope the above examples gave you a clear idea about how to prepare the structure for tables declared dynamically and difference in reading the data from dynamic internal table and a normal internal table.

Please like our page for more updates.

Post a Comment

Previous Post Next Post