Summary -

In this topic, we described about the below sections -

COLLECT statement used for populating the internal tables. COLLECT is used while inserting lines into an internal table with unique standard key.

Syntax -

COLLECT [<work-area> INTO] <itable>.

In standard tables, the row is appended at the end of the table. In sorted tables, new row is inserted in the sort order of the internal table according to the key values and the existing table index of the subsequent rows is increased by 1.

If the table defined with header line, INTO option is ignored. If the line is present in the table with the same key and trying to append the same key then new line is not added to the table and throws runtime error.

The SY-TABIX variable contains the index number of the inserted line after each COLLECT statement.


Example -

Simple example to insert the data using COLLECT to the product information internal table with below structure.

Pid -Character (10)
Pname - Character (40)
Pamount - Decimal (10)


Code -

*&---------------------------------------------------------------------*
*& Report  Z_INTERNAL_TABLE
*&---------------------------------------------------------------------*
*& Written by TutorialsCampus
*&---------------------------------------------------------------------*

REPORT  Z_INTERNAL_TABLE.

* internal table Structure creation
TYPES: BEGIN OF t_product,
       pid(10)     TYPE C,
       pname(40)   TYPE C,
       pamount(10) TYPE P,
       END OF t_product.

* Data & internal table declaration
DATA: wa TYPE t_product,
      it TYPE TABLE OF t_product.

* inserting data to the internal table of INDEX 1
wa-pid     = 'IFB1'.
wa-pname   = 'IFB WASHING MACHINE'.
wa-pamount = 31000.
COLLECT wa INTO it.

* inserting data to the internal table of INDEX 2
wa-pid     = 'IFB2'.
wa-pname   = 'IFB SPLIT AC'.
wa-pamount = 38000.
COLLECT wa INTO it.

* Reading internal table for all the records
LOOP AT it INTO wa.
  IF sy-subrc = 0.
    WRITE :/ wa-pid, wa-pname, wa-pamount.
  ELSE.
    WRITE 'No Record Found'.
  ENDIF.
ENDLOOP. 

Output -

Collect Statement Example output

Explaining Example -

In the above example, each and every statement is preceeded with a comment to explain about the statement. Go through them to get clear understanding of example code.

t_product - Structure declaration, wa - work area of type t_product and it - internal table declaration of type t_product.

COLLECT wa INTO it. - Inserting work area(wa) to the table(it) and READ TABLE it INTO wa INDEX 1. - Reading internal table with index 1.