How to use ‘LOOP AT’ IN SAP ABAP

LOOP AT is used to read more than one data record in an internal table. The Data record is assigned to a local work area or field symbol.

DATA lt_contact TYPE TABLE OF ztt_db_table2.

DATA ls_contact TYPE ztt_db_table2.

SELECT *FROM ztt_db_table2 INTO TABLE lt_contact.

LOOP AT lt_contact INTO ls_contact.

              WRITE:/ ls_contact-contact_id.

ENDLOOP.

The performance of the loop operation is better when it is assigned to a field symbol as the internal table is automatically modified based on the changed Field Symbol value.

FIELD-SYMBOLS: <ls_contact> TYPE ztt_db_table2.

LOOP AT lt_contact ASSIGNING <ls_contact>.

              <ls_contact> – address = ‘Street zz’.

ENDLOOP.

Internal table Data records will be changed for the column address with the value street 22.

The new inline declaration can also be used for LOOP AT like below.

LOOP AT lt_contact INTO DATA(ls_contact).

              WRITE: / ls_contact-contact_name.

ENDLOOP.

LOOP AT lt_contact ASSIGNING FIELD-SYMBOL(<ls_rec>).

              WRITE: / <ls_rec>–contact_name.

ENDLOOP.

The Data records which are processed inside the loop can be filtered using the ‘WHERE’ condition in the LOOP AT line.

LOOP AT lt_contact INTO ls_contact WHERE contact_name = ‘Thiru’.

              WRITE:/ ls_contact – contact_id.

ENDLOOP.

Specific set of records can be picked up for processing using the FROM index TO index options.

LOOP AT lt_contact INTO ls_contact FROM 1 to 2.

              WRITE: / ls_contact-contact_name.

ENDLOOP.

System field variables such as sy-tabix and sy-subrc can also be used in LOOP AT.

LOOP AT lt_contact ASSIGNING FIELD-SYMBOL(<ls_contact>).

              WRITE: / <ls_contact> – contact_name.

              WRITE: / ‘Current index of record’ , sy-tabix.

ENDLOOP.

IF sy_subrc = 0.

              WRITE: / ‘Data records are found inside the loop’.

ENDIF.

If sy_subrc = 4, then there is no data record found inside the internal table.

EXIT, CHECK, CONTINUE : These commands can be used inside LOOP AT.

LOOP AT lt_contact INTO ls_contact.

              EXIT. “Exits the complete loop operation”.

ENDLOOP.

LOOP AT lt_contact INTO ls_contact.

              CHECK ls_contact – contact_id = 102.

              WRITE: / ls_contact–contact_name.

ENDLOOP.

LOOP AT lt_contact INTO ls_contact.

              WRITE: / ‘Don’t execute for contact_id = 101’.

              IF ls_contact–contact_id = 101.

                            CONTINUE.

              ENDIF.

ENDLOOP.