Search code examples
abapopensql

Dynamic Order by [variable] instead of column names?


Is it possible to create a dynamic Order by? something like

Select * from ztable_name Order by variable_name

Or maybe are there any other way to do similar with this if it is not possible? Thanks, Appreciate any help in advance.


Solution

  • To provide further detail to the answer of vwegert: In your example, variable_name has to be the name of a column (because you want to order by a column). But this goes not by using a text variable, but a text table. Imagine the table you want to order has 5 columns:

    • COL1
    • COL2
    • COL3
    • COL4
    • COL5

    If you want to order it dynamically by, let's say COL2 and COL4, it goes like this:

    DATA: itab_order TYPE TABLE OF  char_72,
          wa_order   LIKE LINE OF   itab_order.
    
    wa_order = 'COL2'.
    APPEND wa_order TO itab_order.
    wa_order = 'COL4'.
    APPEND wa_order TO itab_order.
    
    SELECT *
      FROM ztable_name
      INTO itab_ztable_name
      ORDER BY (itab_order).
      ENDSELECT.
    

    Hope this helps :)