Supported by
Supported by Inetum

LOOP AT tbl ASSIGNING <line> CASTING

images/thumbnail.jpg - Thumbnail

Did you know that you can do a LOOP on an internal table of one type into a structure of a different type?

Consider the following types:

TYPES: BEGIN OF ty_s_linha1,
               kunnr TYPE kunnr,
               name1 TYPE name1,
          END OF ty_s_linha1,

          BEGIN of ty_s_linha2,
               kunnr TYPE kunnr,
          END OF ty_s_linha2.
 

You have an internal table of type LINHA1 and want to loop it into a structure of type LINHA2.

The old way of doing it required you to manually convert LINHA1 into LINHA2:

    DATA: t_linha1 TYPE STANDARD TABLE OF ty_s_linha1,
              s_linha2 TYPE ty_s_linha2.

    FIELD-SYMBOLS: <s_linha1> TYPE ty_s_linha2.

   LOOP AT t_linha1 ASSIGNING <s_linha1>.
     MOVE-CORRESPONDING <s_linha1> TO s_linha2.
     do_something( s_linha2 ).
  ENDLOOP.

But a simple word, CASTING, makes everything so much simpler:

    DATA: t_linha1 TYPE STANDARD TABLE OF ty_s_linha1.
    FIELD-SYMBOLS: <s_linha2> TYPE ty_s_linha2.

   LOOP AT t_linha1 ASSIGNING <s_linha2> CASTING.
    faz_algo( s_linha2 ).
  ENDLOOP.

Note that this doesn’t work with INTO, only with ASSIGNING.

Thank you Nuno Morais for the tip.

Thank you Eelco for the photo.