How to create Secondary Indexes for Internal Tables?


Introduction to the new concept of secondary keys/index within internal tables.


We first declare a type 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.



Next, all records from table vbak are read into table it_vbak.


Then, the 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.






No comments:

Post a Comment