How to use control levels at first, at last, at new etc in loop
I would like to explain the control levels in loop which do not exist in JAVA or another language. I have programmed in Java but these controls, I did not get it in JAVA. So it is interesting and useful to understand these control levels for abaper programmers.
Control levels statements | Alternative |
LOOP.
| Loop. IF sy-tabix = 1. " Do something |
LOOP. | DATA lv_count TYPE i. “ Number of records in ITAB DESCRIBE TABLE itab LINES lv_count. LOOP. IF sy-tabix = lv_count. “ last one |
LOOP . | LOOP . IF ls_sflight-carrid <> lv_carrid.” "new WRITE:/ ls_sflight-carrid. ENDIF. ENDLOOP. |
So actually, it is not difficult to program it what we want. It is only logic, but ABAP has facilitated it and made it ready and easy to use it instead to program it.
It is really needed when you need to build a tree or complex tree. I will try to explain more how we use them to build a ALV tree with using these control statements as well as to the new statement on change ofwhich has the same behavior of at new
Don't use at first, at last when you use WHERE condition with LOOP.
LOOP AT lt_sflight into ls_sflight where carrid = 'LH'.
ENDLOOP.
Here the index of loop is not 1. So it is not correct to use this statement AT FIRST. As well as to the statement AT LAST.
Example
Report Zibo_Control_levels
DATA: ls_sflight TYPE sflight,
lt_sflight TYPE TABLE OF sflight.
DATA lv_carrid TYPE sflight-carrid.
DATA lv_carrid_next LIKE lv_carrid.
DATA lv_connid TYPE sflight-connid.
DATA lv_cnt TYPE i.DATA lv_indx TYPE i.
Start-of-selection.
SELECT * FROM sflight INTO TABLE lt_sflight UP TO 200 ROWS.
DESCRIBE TABLE lt_sflight LINES lv_cnt.
DATA ls_tmp TYPE sflight.LOOP AT lt_sflight INTO ls_sflight.
AT FIRST.
WRITE:/ 'CARRID'.
WRITE: 8 'CONNID'.
ENDAT.
AT NEW carrid.
WRITE:/ ls_sflight-carrid.
ENDAT.
AT LAST.
ULINE.
EXIT.
ENDAT.
AT END OF carrid.
ULINE.
WRITE:/ 'CARRID'.
WRITE: 8 'CONNID'.
ENDAT.*
AT NEW connid.
WRITE:/8 ls_sflight-connid.
ENDAT.
ENDLOOP.