COLLECT statement in ABAP

COLLECT statement in ABAP is used for inserting the components of a work area into an internal table by avoiding duplicate entries and also in a summarized way.

Syntax

COLLECT <line> INTO <itab>

When we use collect statement the following steps are occurring.

  1. First it will check in internal table for any record matching with the key in work area data.
  2. If it couldn’t find any matching record, then the new data from work area will be inserted in internal table
  3. If any record found with the same key, then instead of inserting a new record, it will add the numeric field values of work area components with the corresponding field components in the matched record and update the internal table record.

You will understand more clearly after seeing the following sample program and its output.

DATA: BEGIN OF LINE,

COL1(3) TYPE C,

COL2(2) TYPE N,

COL3    TYPE I,

END OF LINE.

 

DATA ITAB LIKE SORTED TABLE OF LINE

WITH NON-UNIQUE KEY COL1 COL2.

 

LINE-COL1 = INDIA’. LINE-COL2 = ’20’. LINE-COL3 = 6.

COLLECT LINE INTO ITAB.

LINE-COL1 = ‘USA’. LINE-COL2 = ’10’. LINE-COL3 = 5.

COLLECT LINE INTO ITAB.

 

LINE-COL1 = ‘INDIA’. LINE-COL2 = ’20’. LINE-COL3 = 7.

COLLECT LINE INTO ITAB.

 

LOOP AT ITAB INTO LINE.

WRITE: / LINE-COL1, LINE-COL2, LINE-COL3.

ENDLOOP.

 

Output will be

INDIA  20  13

USA     10   5

You can see that the third work area data is not inserted. Instead of that it found the matching entry in the table and adds the numerical fields only. Here only COL3 is defined as numerical , so it add the values of work area and internal table filed value ( 6 + 7) and update the table.

Other notes about COLLECT statement in ABAP

  1. When we execute this statement the system fields SY-TABIX will contain the index of the line in internal table where the data stored.
  2. ASSIGNING and REFERENCE INTO are some additions that can be used with this statement, for assign a field symbol to the inserted line.
  3. The exception COLLECT_OVERFLOW occurs due to the overflow in integer field while creating total
  4. The exception COLLECT_OVERFLOW_TYPE_P occurs due to the overflow in p fields while creating total.

The exception TABLE_COLLECT_CHAR_IN_FUNCTION occurs when we use the COLLECT statement for non-numeric fields.

Also Read : View Other ABAP Keywords & Syntax -> ABAP Transaction codes