04-26-2021 3:50 AM
Not sure if it's a bug or a feature, but I tried to use REDUCE statement in ABAP with an alphanumeric Internal table. Contents of internal table I_TAB(Inline declaration from SELECT statement) after explicit SORT is as follows:
123
234
345
ABC
DEF
Then I executed the ff REDUCE code:
v_string = REDUCE string( INIT text TYPE string sep = '' FOR ls_tab IN i_tab NEXT text = text && sep && ls_tab-field1 sep = ',' ).
The expected output would have been:
"123,234,345,ABC,DEF"
But no, SAP reduced it like this:
"ABC,DEF,123,234,345"
Totally ignoring the sort order of the internal table prior to REDUCE.
Anyone who has any idea what's going on?
Thanks!
04-26-2021 5:24 AM
Hi!
The ABAP Documentation for FOR ... IN itab suggests that:
As in LOOP, the order of the lines read depends on the table category or a key specified in cond.
And looking at the ABAP Documentation for LOOP AT itab, Basic Form, we see that:
Standard tables and sorted tables
The lines are read by ascending line numbers in the primary table index. In each loop pass, the system field sy-tabix contains the line number of the current line in the primary table index.
Hashed tables
The lines are processed in the order in which they were inserted into the table, and after a sort using the statement SORT in the sort order. In each loop pass, the system field sy-tabix contains the value 0.
So I guess it all comes down to the type and declaration of your structure and table, if your result is a bug of a feature... 🙂
04-26-2021 5:24 AM
Hi!
The ABAP Documentation for FOR ... IN itab suggests that:
As in LOOP, the order of the lines read depends on the table category or a key specified in cond.
And looking at the ABAP Documentation for LOOP AT itab, Basic Form, we see that:
Standard tables and sorted tables
The lines are read by ascending line numbers in the primary table index. In each loop pass, the system field sy-tabix contains the line number of the current line in the primary table index.
Hashed tables
The lines are processed in the order in which they were inserted into the table, and after a sort using the statement SORT in the sort order. In each loop pass, the system field sy-tabix contains the value 0.
So I guess it all comes down to the type and declaration of your structure and table, if your result is a bug of a feature... 🙂
04-26-2021 8:04 AM
I would suggest defining the internal table with EMPTY key or using GROUP BY and with a user-defined ordering
FOR GROUPS group OF elements IN itab GROUP BY ... ASCENDING
04-26-2021 1:00 PM
04-26-2021 5:31 PM
Please check following code:
TYPES tt_string TYPE STANDARD TABLE OF char100 WITH DEFAULT KEY.
DATA(lt_string) = VALUE tt_string( ( '123' ) ( '234' ) ( '345' ) ( 'ABC' ) ( 'DEF' ) ).
DATA(l_string) = REDUCE string( INIT text TYPE string sep = ''
FOR ls_tab IN lt_string NEXT text = text && sep && ls_tab sep = ',' ).
WRITE l_string.
The output is:
123,234,345,ABC,DEF