Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Processing External Data →  ABAP Database Accesses →  Open SQL →  Open SQL - Read Accesses →  SELECT →  SELECT - ORDER BY 

SELECT, Dynamic ORDER-BY Clause

This example demonstrates how sorting is specified dynamically for SELECT.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    TYPES flag TYPE c LENGTH 1.
    DATA: flag_tab  TYPE TABLE OF flag WITH EMPTY KEY,
          order_by  TYPE string,
          spfli_tab TYPE TABLE OF spfli WITH EMPTY KEY.

    "Input screen for columns
    DATA(components) = CAST cl_abap_structdescr(
      cl_abap_typedescr=>describe_by_name( 'SPFLI' ) )->components.
    LOOP AT components FROM 2 ASSIGNING FIELD-SYMBOL(<component>).
        EXPORTING text = CONV string( <component>-name )
        CHANGING  field =  <flag> ).
    cl_demo_input=>request( ).

    "Create ORDER BY clause
    LOOP AT components FROM 2 ASSIGNING <component>.
      DATA(idx) = sy-tabix.
      DATA(flag) = flag_tab[ idx - 1 ].
      order_by = order_by &&
        COND string( WHEN to_upper( flag ) = `X` OR
                          to_upper( flag ) = `A`
                            THEN |, { <component>-name } ASCENDING|
                     WHEN to_upper( flag ) = `D`
                            THEN |, { <component>-name } DESCENDING|
                     ELSE `` ).
    SHIFT order_by BY 2 PLACES LEFT.

    "Database access
        SELECT *
               FROM spfli
               ORDER BY (order_by)
               INTO TABLE @spfli_tab.
      CATCH cx_sy_dynamic_osql_error INTO DATA(exc).
        cl_demo_output=>display( exc->get_text( ) ).
    cl_demo_output=>display( spfli_tab ).


RTTI is used to create input fields for all columns of the table SPFLI except for the client column. The values X or A for ascending sorts and D for descending sorts can be entered in these columns. A dynamic ORDER BY clause is generated from the input as a character string and used in a SELECT statement.