0

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.

Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
J A
  • 3
  • 3

2 Answers2

1

Please check the documentation:

Specifying the Columns Dynamically

To specify the columns in the ORDER BY clause dynamically, use: SELECT ... ORDER BY (<itab>). where <itab> is an internal table with line type C and maximum length 72 characters containing the column names.

vwegert
  • 18,371
  • 3
  • 37
  • 55
  • appreciate the help, vwegert. I usually declare internal table like this, Data itab Type Table of ztable_name. I think i'm confused with how to do the itab with line type c and with the column names. – J A Aug 10 '14 at 08:07
  • sorry. I did not saw the documentation before adding a Comment. Anyway. Thanks a lot for helping. – J A Aug 12 '14 at 16:42
1

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 :)

  • yes. It did help. Thanks a lot for giving additional details in vwegert's answer. Appreciate it. – J A Aug 12 '14 at 16:36