ABAP开发之双层LOOP的优化

话不多说,直接上代码:

REPORT  ZLOOPLUS.
DATA GT_SCHOOL TYPE TABLE OF ZSCHOOL WITH HEADER LINE.
DATA GT_STUDENT TYPE TABLE OF ZSTUDENT WITH HEADER LINE.
SELECT *
  FROM ZSCHOOL
  INTO CORRESPONDING FIELDS OF TABLE GT_SCHOOL.
SELECT *
  FROM ZSTUDENT
  INTO CORRESPONDING FIELDS OF TABLE GT_STUDENT.
*LOOP AT GT_SCHOOL.
*  WRITE:/ '学校:',GT_SCHOOL-ZSCHOOL,GT_SCHOOL-ZSNAME,GT_SCHOOL-ZADD.
*  LOOP AT GT_STUDENT WHERE ZSCHOOL = GT_SCHOOL-ZSCHOOL.
*    WRITE:/ '  学生:',GT_STUDENT-ZCODE,GT_STUDENT-ZNAME,GT_STUDENT-ZSEX,GT_STUDENT-ZWEIGH,GT_STUDENT-ZUNIT.
*  ENDLOOP.
*ENDLOOP.

*双层循环的优化
SORT GT_STUDENT BY ZSCHOOL.
LOOP AT GT_SCHOOL.
  WRITE:/ '学校:',GT_SCHOOL-ZSCHOOL,GT_SCHOOL-ZSNAME,GT_SCHOOL-ZADD.
  READ TABLE GT_STUDENT WITH KEY ZSCHOOL = GT_SCHOOL-ZSCHOOL
                                           BINARY SEARCH TRANSPORTING NO FIELDS.
  IF SY-SUBRC = 0.
    LOOP AT GT_STUDENT FROM SY-TABIX.
      IF GT_STUDENT-ZSCHOOL <> GT_SCHOOL-ZSCHOOL.
        EXIT.
      ENDIF.
      WRITE:/ '  学生:',GT_STUDENT-ZCODE,GT_STUDENT-ZNAME,GT_STUDENT-ZSEX,GT_STUDENT-ZWEIGH,GT_STUDENT-ZUNIT,SY-TABIX.
    ENDLOOP.
  ENDIF.
ENDLOOP.

执行结果:


ABAP开发之双层LOOP的优化_第1张图片

这里的内循环一定要加上FROM SY-TABIX,否则102下面的学生信息就不会显示出来。

你可能感兴趣的:(ABAP开发之双层LOOP的优化)