PLSQL order by issue

后端 未结 4 1656
遥遥无期
遥遥无期 2020-12-22 08:49

Rolled back to revision one, then edited somewhat. See revised question.

I have an interesting issue with the below SELECT.

Its about ORDER BY clause; I am

相关标签:
4条回答
  • 2020-12-22 08:58

    Thanks a lot for your inputs. i have to sort using ORDER BY with a variable p_sortby where p_sortby can take any column_name or column position.

    0 讨论(0)
  • 2020-12-22 09:00

    Try to select the ORDER BY clause as a separate column using the DECODE() function:

    SELECT DECODE(p_sortby, 'ID', gl.group_id, 'NAME', group_name) AS sort, ...
    ...
    ORDER BY 1
    

    Edit:

    I'm not sure what you mean by "doesn't work". If you mean that member_count is not sorted as you expect, use TO_CHAR(gl.member_count, '000000') to enforce a formatted string conversion. (adjust format mask to expected number of digits)

    0 讨论(0)
  • 2020-12-22 09:05

    If you want to do that, you will have to do dynamic SQL with PL/SQL.

    DECLARE
      sql_str VARCHAR2(500);
      sortby  VARCHAR2(30) := 'your_column_name';
    BEGIN
     -- Dynamic PL/SQL block invokes subprogram:
      sql_str := 'select * from your_table where a = 1 order by :a';
    
      OPEN CURSOR v_your_cursor for sql_str USING sortby;
    
      -- Then iterate your cursor.
    END;
    /
    
    0 讨论(0)
  • 2020-12-22 09:19

    Seems like dynamic SQL is what you want.

    When you do things like:

    ... and (gl.group_name_key like '%' || p_name || '%' or p_name is null or p_name = '')

    the optimizer can't use an index on the group_name_key column. Are you sure you want to do it this way?

    0 讨论(0)
提交回复
热议问题