LOOP

LOOP - Loop on an extract 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).

When you have processed a dataset with SORT or LOOP ... ENDLOOP, you cannot extract any more records with EXTRACT.

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