Dynamic Sort on Dynamic Internal Table

Code snippet to dynamically sort a dynamically generated internal table.

Below code used RTTI classes to get structure of table and then prepares internal table of type ABAP_SORTORDER_TAB which is then used to SORT this internal table.

REPORT zpw_test1.

DATA : lref TYPE REF TO data .
FIELD-SYMBOLS <fs_table> TYPE STANDARD TABLE .

*--------------------------------------------------------------------*
* Start-of-Selection
*--------------------------------------------------------------------*
START-OF-SELECTION .

  CREATE DATA lref TYPE STANDARD TABLE OF mara .
  ASSIGN lref->* TO <fs_table> .

  PERFORM sort_table USING <fs_table> .

*&---------------------------------------------------------------------*
*&      Form  SORT_TABLE
*&---------------------------------------------------------------------*
*       Sort Dynamic Internal Table
*----------------------------------------------------------------------*
FORM sort_table  USING  pt_table TYPE STANDARD TABLE ..

  DATA : lo_table      TYPE REF TO cl_abap_tabledescr,
         lo_struc      TYPE REF TO cl_abap_structdescr,

         li_components TYPE abap_component_tab,
         ls_component  TYPE abap_componentdescr,

         li_otab       TYPE abap_sortorder_tab,
         ls_otab       TYPE abap_sortorder.

  lo_table ?= cl_abap_typedescr=>describe_by_data( pt_table ).
  lo_struc ?= lo_table->get_table_line_type( ).

  li_components = lo_struc->get_components( ).

  LOOP AT li_components INTO ls_component .
    CLEAR ls_otab .
    ls_otab-name       = ls_component-name .
*   Put X in DESCENDING to override default ASCENDING order
*   ls_otab-descending = abap_true .
    ls_otab-astext     = abap_true .
    APPEND ls_otab TO li_otab .
  ENDLOOP.

  SORT pt_table BY (li_otab) .

ENDFORM.                    " SORT_TABLE

Leave a Reply