Looping Statements in SAP ABAP

Loops
In a loop, a statement block is executed several times in succession. There are four kinds of loops in ABAP:
·        Unconditional loops using the DO statement.
·        Conditional loops using the WHILE statement.
·        Loops through internal tables and extract datasets using the LOOP statement.
·        Loops through datasets from database tables using the SELECT statement.
This section deals with DO and WHILE loops. SELECT is an Open SQL statement, and is described in the Open SQLsection. The LOOP statement is described in the sections on internal tables and extract datasets.
Unconditional Loops
To process a statement block several times unconditionally, use the following control structure:
DO [n TIMES] ...
  [statement_block]
ENDDO.
Use the TIMES addition to restrict the number of loop passes to n.
If you do not specify any additions, the statement block is repeated until it reaches a termination statement such as EXIT or STOP (see below). The system field sy-index contains the number of loop passes, including the current loop pass.
You can nest DO loops and combine them with other loop forms.
Example
Simple example of a DO loop:
DO.
WRITE sy-index.
  IF sy-index = 3.
    EXIT.
  ENDIF.
ENDDO.
The list output is:
         1          2          3
The loop is processed three times. Here, the processing passes through the loop three times and then leaves it after the EXIT statement.
Example
Example of two nested loops with the TIMES addition:
DO 2 TIMES.
  WRITE sy-index.
  SKIP.
  DO 3 TIMES.
    WRITE sy-index.
  ENDDO.
  SKIP.
ENDDO.
The list output is:
         1
         1          2          3
         2
         1          2          3
The outer loop is processed twice. Each time the outer loop is processed, the inner loop is processed three times. Note that the system field sy-index contains the number of loop passes for each loop individually.
Conditional Loops
To repeat a statement block for as long as a certain condition is true, use the following control structure:
WHILE log_exp
  [statemaent_block]
ENDWHILE.
log_exp can be any logical expression. The statement block between WHILE and ENDWHILE is repeated as long as the condition is true or until a termination statement such as EXIT or STOP occurs. The system field sy-index contains the number of loop passes, including the current loop pass.
You can nest WHILE loops to any depth, and combine them with other loop forms.
Example
REPORT demo_flow_control_while.
DATA: length     TYPE i VALUE 0,
      strl       TYPE i VALUE 0,
      string(30) TYPE c VALUE 'Test String'.
strl = strlen( string ).
WHILE string NE space.
  WRITE string(1).
  length = sy-index.
  SHIFT string.
ENDWHILE.
WRITE: / 'STRLEN:          ', strl.
WRITE: / 'Length of string:', length.
The output appears as follows:
T e s t   S t r i n g
STRLEN:                    11
Length of String:          11
Here, a WHILE loop is used to determine the length of a character string. This is done by shifting the string one position to the left each time the loop is processed until it contains only blanks. This example has been chosen to demonstrate the WHILE statement. Of course, you can determine the length of the string far more easily and efficiently using the strlen function.
Terminating Loops
ABAP contains termination statements that allow you to terminate a loop prematurely. There are two categories of termination statement - those that only apply to the loop, and those that apply to the entire processing block in which the loop occurs. The STOPand REJECT statements belong to the latter group (see Exiting Eventblocks).
The termination statements that apply only to the loop in which they occur are CONTINUE, CHECKand EXIT. You can only use the CONTINUE statement in a loop. CHECK and EXIT, on the other hand, are context-sensitive. Within a loop, they only apply to the execution of the loop itself. Outside of a loop, they terminate the entire processing block in which they occur (subroutine, dialog module, event block, and so on).
CONTINUE, CHECK and EXITcan be used in all four loop types in ABAP (DO, WHILE, LOOP and SELECT).
Terminating a Loop Pass Unconditionally
To terminate a single loop pass immediately and unconditionally, use the CONTINUE statement in the statement block of the loop.
CONTINUE.
After the statement, the system ignores any remaining statements in the current statement block, and starts the next loop pass.
Example
DO 4 TIMES.
  IF sy-index = 2.
    CONTINUE.
  ENDIF.
  WRITE sy-index.
ENDDO.
The list output is:
         1          3          4
The second loop pass is terminated without the  WRITE statement being processed.
Terminating a Loop Pass Conditionally
To terminate a single loop pass conditionally, use the CHECK condition statement in the statement block of the loop.
CHECK condition.
If the condition is not true, any remaining statements in the current statement block after the CHECK statement are ignored, and the next loop pass starts. condition can be any logical expression.
Example
DO 4 TIMES.
  CHECK sy-index BETWEEN 2 and 3.
  WRITE sy-index.
ENDDO.
The list output is:
         2          3
The first and fourth loop passes are terminated without the WRITE statement being processed, because sy-index is not between 2 and 3.
Exiting a Loop
To terminate an entire loop immediately and unconditionally, use the EXIT statement in the statement block of the loop.
EXIT.
After this statement, the loop is terminated, and processing resumes after the closing statement of the loop structure (ENDDO, ENDWHILE, ENDLOOP, ENDSELECT). In nested loops, only the current loop is terminated.
Example
DO 4 TIMES.
  IF sy-index = 3.
    EXIT.
  ENDIF.
  WRITE sy-index.
ENDDO.
The list output is:
         1          2
In the third loop pass, the loop is terminated before the WRITE statement is processed.

LOOP AT itab.
LOOP AT itab INTO wa.

Additions

1. … FROM n1
2. … TO n2
3. … WHERE logexp
4. … TRANSPORTING NO FIELDS

Effect
Processes
an internal table (DATA ) in a loop which begins with LOOP and ends
with ENDLOOP . Each of the internal table entries is sent to the output
area in turn.

When LOOP AT itab. is used, the header line of the
internal table itab is used as output area. In the case of LOOP AT itab
INTO wa , there is an explicitly specified work area wa .

If the internal table is empty, all the statements between LOOP and ENDLOOP are ignored.

In
each loop pass, SY-TABIX contains the index of the current table entry.
After leaving a LOOP , SY-TABIX has the same value as it had before.

Inserting and/or deleting lines in a LOOP affects subsequent loop passes.

For
control break processing in a LOOP on internal tables, there are
special control break control structures for internal tables you can
use.

You can use the CONTINUE statement to leave the current
loop pass prematurely and continue with the next loop pass. To leave
loop processing altogether, you use EXIT .

At the end of loop
processing (i.e. after ENDLOOP ), the return code value of SY-SUBRC
specifies whether the loop was actually processed.

SY-SUBRC = 0 The loop was executed at least once.
SY_SUBRC
= 4 The loop was not executed, either because there was no entry at all
or because there was no entry which satisfied the conditions.

Example
The table T is defined as follows:

DATA: BEGIN OF T OCCURS 100,
BAREA(2), BLNCE TYPE P,
END OF T.

After the table has been filled with data (using APPEND ), it is then output:

LOOP AT T.
WRITE: / T-BAREA, T-BLNCE.
ENDLOOP.

Notes
If
an internal table is processed only on a restricted basis (with the
additions FROM , TO and /or WHERE ), you should not use the control
structures for control break processing because the interaction of a
restricted LOOP and the AT statement is undefined at present.
If SUM
is used in a LOOP and an explicit output area wa has also been
specified, this output area must be compatible with the line type of
the internal table itab .

Addition 1
… FROM n1
Addition 2
… TO n2

Effect
Places
all internal table entries from the entry with the index ( SY-TABIX ) =
n1 to the entry with the index = n2 inclusive in the output area in
turn.

Note
If either one of the additions ” FROM n1 ” or ” TO
n2 ” is missing, then the table is processed either from the first
entry or up to the last entry (according to what is missing).

Example
Output table entries 7 and 8:

DATA: BEGIN OF T OCCURS 100,
BAREA(5), BLNCE(5),
END OF T.

LOOP AT T FROM 7 TO 8.
WRITE: / T-BAREA, T-BLNCE.
ENDLOOP.

Addition 3
… WHERE logexp

Effect
Places
all internal table entries which satisfy the condition logexp in turn
in the output area. The condition logexp can be almost any logical
expression . The only restriction is that the first field for each
comparison must be a sub-field of the line structure of the internal
table itab .

Example

DATA: BEGIN OF T OCCURS 100,
BAREA(5), BLNCE(5),
END OF T.

LOOP AT T WHERE BAREA > 0.
WRITE: / T-BAREA, T-BLNCE.
ENDLOOP.

which has the same effect as:

LOOP AT T.
CHECK T-BAREA > 0.
WRITE: / T-BAREA, T-BLNCE.
ENDLOOP.

Notes
The
interaction between the LOOP AT … WHERE statement and the AT control
break statements is currently undefined. It is therefore important to
avoid using either the AT NEW/END OF or FIRST/LAST statements in a LOOP
loop with a WHERE condition.
The performance of a LOOP AT … WHERE
statement can be improved significantly if the fields to be compared
always have the same data type. The comparison fields should be defined
as follows:

DATA LIKE .

Example

DATA: BEGIN OF T OCCURS 100,
BAREA(5), BLNCE(5),
END OF T.
DATA CMP_BAREA LIKE T-BAREA.
CMP_BAREA = ’01’.
LOOP AT T WHERE BAREA = CMP_BAREA.
WRITE: / T-BAREA, T-BLNCE.
ENDLOOP.

Addition 4
… TRANSPORTING NO FIELDS

Effect
There
is no field transport in the output area of the internal table. This
addition can be used only in conjunction with a WHERE condition. Since
it would make no sense to specify a work area with INTO wa when using
the addition TRANSPORTING NO FIELDS , this option does not exist.

This
addition can be used to determine a set of line indexes (index set) or
to determine the number of lines in a table which satisfy a given
condition.

Example
Determining the number COUNT of lines in a
name table TAB which contain the name ‘Walter’ and the corresponding
index set INDEX_SET .

DATA: BEGIN OF TAB OCCURS 100,
NAME(30) TYPE C,
END OF TAB,
COUNT TYPE I,
INDEX_SET LIKE SY-TABIX OCCURS 10 WITH HEADER LINE.

LOOP AT TAB TRANSPORTING NO FIELDS WHERE NAME CS ‘Walter’.
INDEX_SET = SY-TABIX.
APPEND INDEX_SET.
ADD 1 TO COUNT.
ENDLOOP.

LOOP – Loop on an extract dataset

Basic form
LOOP.

Effect
Processes the extracted dataset.

By
using LOOP … ENDLOOP , you can process the dataset generated by
EXTRACT like an internal table (as in LOOP AT itab ) – if required,
after sorting with SORT .

For control break processing in a LOOP
on an extract dataset, there are special control break control
structures for extracts you can use.

At the end of a control
level, the control total of a numeric field f is stored in the field
SUM(f) . This total includes all records read, even if further
processing in the LOOP has been skipped by CHECK .

At the end of
a control level, the number of different values which a field f has
accepted from the sort key within the group, i.e. the number of control
records where the field f has changed its value, is stored in the field
CNT(f) .

You can use the CONTINUE statement to leave the current
loop pass prematurely and continue with the next loop pass. To leave
loop processing altogether, you use EXIT .

At present, the
return code value in SY-SUBRC is not set when you use LOOP with
extracts. In Release 4.0, however, SY-SUBRC will also specify for LOOP
via extracts at the end of loop processing (i.e. after ENDLOOP )
whether the loop was processed at least once when (similar to LOOP with
internal tables).

Notes
When you have processed a dataset with SORT or LOOP … ENDLOOP , you cannot extract any more records with EXTRACT .
You
cannot nest loops on extracted datasets (unlike internal tables), i.e.
only one loop on an extracted dataset can be active at any time.
However, several consecutive loops are allowed.

Example

DATA: ONR(7), POSITION(3) TYPE N,
CUSTOMER(20),
PNR(5) TYPE N, NAME(15), UNITS TYPE I,
ORDERS TYPE I.
FIELD-GROUPS: HEADER, ORDER, PRODUCT.
INSERT ONR POSITION INTO HEADER.
INSERT CUSTOMER INTO ORDER.
INSERT PNR NAME UNITS INTO PRODUCT.
ONR = ‘GF00012’. POSITION = ‘000’.
CUSTOMER = ‘Good friend’.
EXTRACT ORDER.
ADD 1 TO POSITION.
PNR = ‘12345’. NAME = ‘Screw’. UNITS = 100.
EXTRACT PRODUCT.
ADD 1 TO POSITION.
PNR = ‘23456’. NAME = ‘Nail’. UNITS = 200.
EXTRACT PRODUCT.
ONR = ‘NB00056’. POSITION = ‘000’.
CUSTOMER = ‘Nobody’.
EXTRACT ORDER.
ONR = ‘MM00034’. POSITION = ‘000’.
CUSTOMER = ‘Moneymaker’.
EXTRACT ORDER.
ADD 1 TO POSITION.
PNR = ‘23456’. NAME = ‘Nail’. UNITS = 300.
EXTRACT PRODUCT.
ADD 1 TO POSITION.
PNR = ‘34567’. NAME = ‘Hammer’. UNITS = 4.
EXTRACT PRODUCT.
SORT.
LOOP.
AT ORDER.
WRITE: /, / ONR, CUSTOMER.
ENDAT.
AT ORDER WITH PRODUCT.
WRITE ‘ordered:’.
ENDAT.
AT PRODUCT.
WRITE: / ONR, PNR, NAME, UNITS.
ENDAT.
AT END OF ONR.
WRITE: / ‘Sum of units:’, 26 SUM(UNITS).
ORDERS = CNT(POSITION) – 1.
WRITE: / ‘Number of orders:’, ORDERS.
ENDAT.
ENDLOOP.

This code generates the following list:

GF00012 Good friend ordered:
GF00012 12345 Screw 100
GF00012 23456 Nail 200
Sum of units: 300
Number of orders: 2

MM00034 Moneymaker ordered:
MM00034 23456 Nail 300
MM00034 34567 Hammer 4
Sum of units: 304
Number of orders: 2

NB00056 Nobody
Sum of units: 0
Number of orders: 0
Related EXTRACT , LOOP AT itab

Note
Runtime errors

LOOP_WITHIN_LOOP : Nested loop on an extracted dataset.

LOOP – Loops on screen fields

Basic form
LOOP AT SCREEN.

Effect
All fields of the current screen are stored in the system table SCREEN with their attributes.
The ” LOOP AT SCREEN ” statement places this information in the header line of the system table.
If
you want to change the attributes, you must put back the changed header
line with MODIFY SCREEN . However, you can only do this in the PBO
module of a screen .
If you use this statement for step loop
processing, the information (and any changes) apply only to the current
steploop line. Outside step loop processing, the information for a step
loop field applies to the complete column.
Step loop fields should never be changed after the corresponding step loop processing has been performed.
You can use the CONTINUE statement to leave the current loop pass prematurely and continue with the next loop pass.
Overview of all SCREEN fields:

Field Length Type Meaning

SCREEN-NAME 30 C Field name
SCREEN-GROUP1 3 C Evaluation of
modification group 1
SCREEN-GROUP2 3 C Evaluation of
modification group 2
SCREEN-GROUP3 3 C Evaluation of
modification group 3
SCREEN-GROUP4 3 C Evaluation of
modification group 4
SCREEN-REQUIRED 1 C Field input mandatory
SCREEN-INPUT 1 C Field ready to accept input
SCREEN-OUTPUT 1 C Field will be displayed
SCREEN-INTENSIFIED 1 C Field highlighted
SCREEN-INVISIBLE 1 C Field invisible
SCREEN-LENGTH 1 X Field length
SCREEN-ACTIVE 1 C Field active

Example
Make all fields display only:

CONSTANTS OFF VALUE ‘0’.
LOOP AT SCREEN.
SCREEN-INPUT = OFF.
MODIFY SCREEN.
ENDLOOP.

LOOP – loop processing with a database table

Basic form
LOOP AT dbtab.

Addition

… VERSION vers

Note
This
variant is no longer maintained and should therefore not be used (see
also Obsolete key words ). Instead, please use a SELECT statement.

Effect
Loop processing of the database table dbtab .

You
must declare the table dbtab under TABLES in the program. dbtab is a
table name which begins with “T” and consists of up to five characters.
The
processing is the same as for variant 1 (except that the system field
SY-TABIX is not set). If you want to process the whole table, you must
set all table fields to SPACE . Otherwise, the table fields you want to
use as a generic argument must be filled beforehand (READ TABLE dbtab.
).

Note
Fields of type P and type N have an initial value
other than SPACE . This means that fields of this type after CLEAR or
MOVE SPACE TO … are not set to SPACE .
In the case of tables which
have arguments containing fields of type P or type N , the entire table
header line must be set to SPACE ( MOVE SPACE TO dbtab , not (!) CLEAR
dbtab ). It is preferable to use SELECT instead.

Addition
… VERSION vers

Note
You
should use this addition only if it is absolutely necessary. In some
cases, you can (and it makes sense) to avoid this LOOP addition by
using a generation program.

Effect
Specifies a dynamically
definable table name. The field vers must be a 4-character C field
which contains the table name. It is declared under PARAMETERS and
evaluated at runtime. The entry read is always placed in the assigned
table T…. .

Popular posts from this blog

How to create Interactive Report in SAP ABAP

How to create ALV Interactive Report in SAP ABAP

BDC Call Transaction Method Program