Search code examples
loopsabapinternal-tables

Nested loop conditional


Supposed I have this table:

 TDID    TDLINE
 F04     04-AA
 F04     04-BB    <-- call a function
 F05     05-AA
 F05     05-BB    <-- call a function
 F06     06-AA    <-- call a function

I would like to call a function while the TDID field is not the same as the previous one. I have the code below, it works but somehow it's not perfectly works (it missed the last row):

LOOP AT lines ASSIGNING <fs1>.
  IF <fs2> IS INITIAL.
    <fs2> = <fs1>.
  ELSE.
    li_line-tdline = <fs2>-tdline.
    APPEND li_line.

    IF <fs1>-tdid NE <fs2>-tdid.
      li_thead-tdid = <fs2>-tdid.

      CALL FUNCTION 'SAVE_TEXT'
        EXPORTING
          header          = li_thead
          savemode_direct = 'X'
        TABLES
          lines           = li_line

      CLEAR: li_thead,
             li_line.
      FREE:  li_thead,
             li_line.
    ENDIF.
  ENDIF.
ENDLOOP.

ANSWER

Thank you to vwegert for the answer:

LOOP AT lines ASSIGNING <fs1>.
  AT NEW tdid.
    REFRESH li_thead.
    REFRESH li_line.

    li_thead-tdid     = <fs1>-tdid.
    APPEND li_thead.
  ENDAT.

  li_line-tdline    = <fs1>-tdline.
  APPEND li_line.

  AT END OF tdid.
    CALL FUNCTION 'SAVE_TEXT'
      EXPORTING
        header          = li_thead
        savemode_direct = 'X'
      TABLES
        lines           = li_line
  ENDAT.
ENDLOOP.

Solution

  • Assuming that the table is sorted by TDID and no field left of TDID changes more frequently than TDID:

    LOOP AT lines ASSIGNING <fs1>.
      AT NEW tdid.
        REFRESH some_other_tab.
      ENDAT.
      APPEND <fs1> TO some_other_tab.
      AT END OF tdid.
        CALL FUNCTION ...
      ENDAT.
    ENDLOOP.