Skip to Content
avatar image
Former Member

Is it safe to have nested loops on the same internal table?

Hello experts,

I am wondering that whether the follow code is legal/safe:

CLEAR old_key.

LOOP AT itab INTO itab_wa.

IF itab_wa-key <> old_key.

old_key = itab_wa-key.

LOOP AT itab INTO itab_wa1 WHERE key = old_key.

* do some processing here.

ENDLOOP.

ENDIF.

ENDLOOP.

Thanks and best regards.

zj

Add comment
10|10000 characters needed characters exceeded

  • Follow
  • Get RSS Feed

1 Answer

  • avatar image
    Former Member
    Nov 14, 2003 at 02:59 PM

    If the code is unclear then the maintenance of the code will be expensive, and lead to errors.

    Try:

    SORT ITAB BY key.

    CLEAR old_key

    LOOP AT itab INTO itab_wa.

    IF itab_wa-key <> old_key.

    old_key = itab_wa-key.

    * Do first time through processing.

    ENDIF.

    • Do some processing here.

    ENDLOOP.

    If you do not have any need for first time through process then you do not need 'old_key'.

    Add comment
    10|10000 characters needed characters exceeded

    • Former Member Former Member

      Me too, I think the code is okay. It could be better as Matthew mentioned.

      But there is one good advice when using the variable sy-tabix:

      save it as soon as possible!

      Code:

      CLEAR old_key.

      LOOP AT itab INTO itab_wa.

      outer_sy_tabix = sy-tabix. " save sy-tabix

      IF itab_wa-key <> old_key.

      old_key = itab_wa-key.

      LOOP AT itab INTO itab_wa1 WHERE key = old_key.

      * do some processing here.

      ENDLOOP.

      ENDIF.

      • process outer sy-tabix

      if outer_sy_tabix = 1.

      ....

      endif.

      ENDLOOP.

      If you're doing things in a LOOP, for example another loop or a perform or other things, and you have to use sy-tabix in the lower part of the loop, always save it!

      The same is to do with other system variables as sy-index or sy-subrc in similar cases.

      KInd Regards Axel Kiltz