In this recipe, we will see the new concept of secondary keys/index within internal tables. This lets you optimize your programs when accessing data residing within an internal table.
In this recipe, we will create a program that will store all data of table VBAK
into an internal table. Then we will use the secondary key in order to fetch a record pertaining to a given order number, aufnr
. The primary emphasis of this recipe is on the definition and usage of a secondary key for internal tables.
For creating a program using secondary index in internal tables, follow the steps below:
ty_vbak
based on the database table vbak
. We create two keys for this table type. The first is a non-unique primary key having vbeln
as the key field. We also create a non-unique sorted secondary key sec_key
having one field aufnr
. An internal table it_vbak
is defined based on the type ty_vbak
. In addition, a work area wa_vbak
is declared for the table it_vbak
. It is always better in terms of performance to use field symbols rather than work areas. In this example, for simplicity's sake and since the performance gain is minimal, work areas have been used.vbak
are read into table it_vbak
.read table
statement is used to read the row of internal table it_vbak
pertaining to aufnr 503002
using the secondary key sec_key
.In the table type definition, we specified a non-unique sorted secondary key (based on aufnr
) along with the primary key. For the read
statement, we also specify that the secondary key sec_key
is to be used when searching in internal table it_vbak
the row corresponding to aufnr 503002
. Since the secondary key is used, the aufnr
field is first searched in the secondary index sec_key
. A faster binary search is used since it is a sorted index. The row number of the actual internal table it_vbak
containing the aufnr 503002
field is then determined. Once this number is known, the relevant row is read and values assigned to the structure wa_vbak
. The vbeln
field is then printed. Had no secondary index been specified, a sequential search through the internal table it_vbak
would have been used, which was very time consuming.
3.16.81.33