14.01.2020 Views

ABAP_to_the_Future

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2

New Language Features in ABAP 7.4

2.6.7 Internal Table Queries with REDUCE

In Section 2.2.5, you learned a new way to create internal tables by using a FOR

loop. After you’ve filled up your internal tables, though, you often want to query

them. Say, for example, that you want to know how many really mad monsters

you have. As of 7.4, you can do this by using a constructor operator called REDUCE,

which contains logic to process an internal table and return a single result. In the

example in Listing 2.63, you will first say what variable you want created and

what type that variable is going to be, thenset an initial value for your result variable,

and finally loop over the table, performing assorted logic. That sounds really

complicated, but as you will see the code is not.

DATA:( ld_mad_monsters_count ) = REDUCE sy-tabix(

INIT result = 0

FOR ls_monsters IN lt_neurotic_monsters

NEXT result = result +

lo_checker->is_it_mad( ls_monsters-monster_number ).

Listing 2.63 How Many Really Mad Monsters?

The SY-TABIX after the REDUCE statement defines the type of the variable being

created, LD_MAD_MONSTER_COUNT. It also defines the type of the temporary variable

after the INIT statement, which is going to be the result; i.e., both LD_MAD_MON-

STER_COUNT and RESULT have the type SY-TABIX. You then loop over your internal

table, and every time your is_it_mad method comes back with a value of 1, you

increase the count of the RESULT variable. After the FOR loop is finished, the value

of RESULT gets copied into LD_MAD_MONSTERS.

2.6.8 Grouping Internal Tables

You are most likely familiar with the GROUP BY addition you can add to a database

SELECT, which condenses similar records into a single row. In the past, when you

wanted to do something similar to an internal table you would maybe use the

COLLECT statement or the very dodgy AT NEW statement, which did not work very

well in a lot of circumstances. In fact, the AT NEW statement was so unpredictable

that it was wiser to avoid it altogether and use other means to process related

chunks from your internal table. ABAP 7.4 brings good news: a GROUP BY option

has been added to looping at internal tables.

To understand what this means, let’s lo ok at an example. Say that you have a

huge great table of open customer items.You only want to process one customer

122

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!