Is parameter in ORDER BY clause possible?

I'm using a function to return a ref cursor and currently pass a parameter without any problems. I would like to change the sort on the fly by passing a parameter to the order by clause, but Oracle ignores it.
CREATE OR REPLACE PACKAGE pkg_agent_appt_status AS
TYPE rcur IS REF CURSOR;
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2) RETURN rcur;
END pkg_agent_appt_status;
CREATE OR REPLACE PACKAGE BODY pkg_agent_appt_status AS
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2)
RETURN rcur
IS
retval rcur;
BEGIN
OPEN retval FOR
SELECT agncy.CORPORATE_NAME "Agency Name",
agnt_state.APPT_STATE "State",
agnt.AGENT_STATUS "Appt Status",
TO_CHAR(agnt_state.APPT_STATE_EFF_DT,'mm/dd/yyyy') "Effective Date",
agnt.AGENT_NUMBER "Agent ID",
agnt.AGENT_STATUS "Agent Status",
STATE.STATE_NAME
FROM AGNT_APPT_STAT_PRDCR_WRK agnt,
AGNT_APPT_STAT_WRK agncy,
AGNT_APPT_STATE_STAT_PRDCR_WRK agnt_state,
STATE
WHERE agnt.AGENT_TAX_ID = ssn
AND agnt.COMPANY_CODE = agncy.COMPANY_CODE
AND agnt.PARENT_AGENT_AGENCY_ID = agncy.AGENT_NUMBER
AND agnt.COMPANY_CODE = agnt_state.COMPANY_CODE
AND agnt.AGENT_AGENCY_ID = agnt_state.AGENT_AGENCY_ID
AND agnt.AGENT_NUMBER = agnt_state.AGENT_NUMBER
AND agnt_state.APPT_STATE = STATE.STATE_CODE
ORDER BY
sort_str;                     
RETURN retval;
END f_agent_appt_status;
END pkg_agent_appt_status;

If you want to do this, you'd have to use dynamic SQL (execute immediate or DBMS_SQL). For the easier 'execute immediate' approach, you'd do something like
create or replace someProc( someArg varchar2 )
as
  strSQL varchar2(4000)
begin
  strSQL := <<string containing your SQL statement up to the order by clause>>
  strSQL := strSQL || 'ORDER BY ' || someArg
  execute immediate strSQL;
endJustin

Similar Messages

  • Is passing parameter to ORDER BY clause possible?

    I'm using a function to return a ref cursor and currently pass a parameter without any problems. I would like to change the sort on the fly by passing a parameter to the order by clause, but Oracle ignores it.
    CREATE OR REPLACE PACKAGE pkg_agent_appt_status AS
    TYPE rcur IS REF CURSOR;
    FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2) RETURN rcur;
    END pkg_agent_appt_status;
    CREATE OR REPLACE PACKAGE BODY pkg_agent_appt_status AS
    FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2)
    RETURN rcur
    IS
    retval rcur;
    BEGIN
    OPEN retval FOR
    SELECT agncy.CORPORATE_NAME "Agency Name",
    agnt_state.APPT_STATE "State",
    agnt.AGENT_STATUS "Appt Status",
    TO_CHAR(agnt_state.APPT_STATE_EFF_DT,'mm/dd/yyyy') "Effective Date",
    agnt.AGENT_NUMBER "Agent ID",
    agnt.AGENT_STATUS "Agent Status",
    STATE.STATE_NAME
    FROM AGNT_APPT_STAT_PRDCR_WRK agnt,
    AGNT_APPT_STAT_WRK agncy,
    AGNT_APPT_STATE_STAT_PRDCR_WRK agnt_state,
    STATE
    WHERE agnt.AGENT_TAX_ID = ssn
    AND agnt.COMPANY_CODE = agncy.COMPANY_CODE
    AND agnt.PARENT_AGENT_AGENCY_ID = agncy.AGENT_NUMBER
    AND agnt.COMPANY_CODE = agnt_state.COMPANY_CODE
    AND agnt.AGENT_AGENCY_ID = agnt_state.AGENT_AGENCY_ID
    AND agnt.AGENT_NUMBER = agnt_state.AGENT_NUMBER
    AND agnt_state.APPT_STATE = STATE.STATE_CODE
    ORDER BY
    sort_str;
    RETURN retval;
    END f_agent_appt_status;
    END pkg_agent_appt_status;

    This is quite easy, as you are already using a REF CURSOR. Instead of
    OPEN retval FOR
    SELECT ...
    ORDER BY sort_str;we can code this:
    OPEN retval FOR
    'SELECT ...
    ORDER BY '|| sort_str;Watch out for the single quotes in your query e.g. the date format mask: you need to wrap these in an additional set of single quotes i.e. 'mm/dd/yyyy' becomes ''mm/dd/yyyy''.
    Cheers, APC

  • Dynamic ORDER BY clause - Possible different data types...

    I have a lexical parameter in my ORDER BY clause:
    ORDER BY &P_ORDER_BY
    My problem is that I have to designate this parameter as either a date, character or number, but the user defined column being ordered by could be any one of these. When I designate the parameter as a character type, and a number data type column is chosen, it orders by that value, but it orders it as though it were a character field, referencing the initial digit and not the overall numeric value. If I choose a number parameter type, and a character value is chosen, I get an invalid number error, and so on.
    Anyone have any ideas how I can do this?

    Okay, now we're on the right track. The lexical parameter I'm using allows the user to choose from a list of the columns being retrieved in the SELECT statement, so it will always be one that's in there, as you said. Now, since I don't know which one it's going to be, I can't just make all but one of them 'None' for the break order, BUT, what I intended to do was to add a column to the SELECT statement that would always return the column they chose, and I could put the break order on that column, leaving all the rest 'None'. However, in the past, this has created 2 problems for me.
    1.) As I mentioned in the first post, the column being returned could have a data type of character, number or date, but the parameter must be designated as only one of these. So, if the user chooses to order by a column having a value with a data type other than what the parameter is designated to be, then I get errors, it doesn't order correctly, etc...
    2.) This is the strange, but anytime I've marked all but one column as 'None' for the Break Order, my child data doesn't always stay with the parent. For example, the report is on an IT request database. The 'group fields' consist of data elements that are demographic info.of a request (requester, date requested, description, etc...), and the details for each request list out the comments that have been made in the system for that request. The problem I'm seeing when I set the break orders this way is that each request displays not only its own comments, but it lists out comments for other requests as well, and there doesn't seem to be any logic to which request's comments it lists in addition to its own, it just lists as many as will fit on the page...I don't know if I explained that very well, but that's what's happening.
    Does any of that make sense? Any ideas?

  • Order by clause  based on parameter value

    hi,
    i am using reports 6i with 10 g db
    I have to create a report sorted in order of four fields. there is a parameter for selecting which field should come first in order by clause.
    ie the user has provision to view the report in selected sorted order
    suppose the four fields are emp_id, name, dept_id, desig .
    if the user select dept_id , then the order by clause should be in order of dept_id,emp_id,name,desig
    Please help to solve this scenario.
    Thanks

    Hi Rinz,
    Use the query as follows :
    select column_name1, column_name1, ....
    from  table_name
    &order_by_clauseNow in the AFTER-PARAMETER-FORM trigger set the order by clause as below depending upon requirements :
    if :sort_column = dept_id then
      :order_by_clause := 'order by dept_id,emp_id,name,desig';
    else
      :order_by_clause := 'order by emp_id, dept_id, name,desig';
    end if;
    Here sort_column is User parameter which will be selected by user, provide list of Values for it.
    Hope this helps
    Best Regards
    Arif Khadas

  • Writing order by clause with user parameter

    I have a user parameter where the user is supposed to choose what column they want to sort by.
    And they can choose between k.personnr and k.personnavn. I am trying to do this with a decode function.
    Now this would work fine if there was no union between these select statements.
    But with the union I get a ORA-01785, where they tell me to put in a number.
    Here is the sql:
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    r.belop as SUM,
    concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY'))) AS PERIODE
    FROM
    reskontro r,
    klient k,
    kontoplan p,
    konto c
    WHERE
    r.distriktnr='21'
    and r.distriktnr=c.kontoid
    and r.distriktnr=k.distriktnr
    and r.personnr=k.personnr
    and r.kontonr=p.kontonr
    and (((r.bilagdato between :p_fra_dato and :p_til_dato) and (:p_fra_dato <= c.overfort) and (:p_til_dato <= c.overfort))
    or ((r.bilagdato between :p_fra_dato and c.overfort) and (:p_fra_dato <= c.overfort) and (:p_til_dato >= c.overfort)))
    UNION ALL
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    (t.belop/100) as SUM,
    concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')),:P_HORISONTAL) AS PERIODE
    FROM
    transaksjon t,
    klient k,
    kontoplan p
    WHERE
    t.distriktnr='21'
    and t.distriktnr=k.distriktnr
    and t.personnr=k.personnr
    and t.kontonr=p.kontonr
    and t.bilagdato between :p_fra_dato and :p_til_dato
    This is the order by clause I would like to use:
    order by decode(:p_order_by,'Personnavn',k.personnavn,k.personnr)
    I also get an error when I use:
    order by decode(:p_order_by,'Personnavn',2,1)
    Can anybody tell me how to work around this problem?

    Hi,
    One way you can do to get around this problem could be :
    select * from (
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    r.belop as SUM,
    concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(r.bilagdato,'MM'), to_char(r.bilagdato,'YYYY'))) AS PERIODE
    FROM
    reskontro r,
    klient k,
    kontoplan p,
    konto c
    WHERE
    r.distriktnr='21'
    and r.distriktnr=c.kontoid
    and r.distriktnr=k.distriktnr
    and r.personnr=k.personnr
    and r.kontonr=p.kontonr
    and (((r.bilagdato between :p_fra_dato and :p_til_dato) and (:p_fra_dato <= c.overfort) and (:p_til_dato <= c.overfort))
    or ((r.bilagdato between :p_fra_dato and c.overfort) and (:p_fra_dato <= c.overfort) and (:p_til_dato >= c.overfort)))
    UNION ALL
    SELECT
    k.personnr as PERSON ,
    k.personnavn as NAVN,
    (t.belop/100) as SUM,
    concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')) AS MND,
    PERIODE(concat(to_char(t.bilagdato,'MM'), to_char(t.bilagdato,'YYYY')),:P_HORISONTAL) AS PERIODE
    FROM
    transaksjon t,
    klient k,
    kontoplan p
    WHERE
    t.distriktnr='21'
    and t.distriktnr=k.distriktnr
    and t.personnr=k.personnr
    and t.kontonr=p.kontonr
    and t.bilagdato between :p_fra_dato and :p_til_dato)
    order by decode(:p_order_by,'Personnavn', NAVN, PERSON)
    /Uffe

  • Passing parameter in report for order by clause

    how can we pass the name of the column on which we want the order by clause to sort as a parameter through parameter from in a report??

    Hi Guptha,
    We can create a bind parameter in report and we can send it as a parameter or enter in the parameter form.
    The Query will be
    select * from emp
    order by :Order_Bu_Column
    I think it will help you.
    Regards,
    Siva.

  • IS IT POSSIBLE TO  WRITE ORDER BY CLAUSE WITHIN INNER QUERY

    IS IT POSSIBLE TO WRITE ORDER BY CLAUSE WITHIN INNER QUERY

    So you still can't :) I still don't see it that strict:
    You know of course that this is possible:
    select ename, (select ename
                     from (select   empno, ename
                               from emp
                              where deptno = 10
                           order by 1) e2
                    where e.empno = e2.empno) a
      from emp eso we have an »ORDER BY CLAUSE WITHIN INNER QUERY« which is even correlated (though through the outer query).
    Whether this makes sense or not is not question imho :-) ... but you can

  • Passing parameters in order by clause of cursor

    Hi friends,
    I am facing a strange problem
    I have a cursor with a order by clause.
    OPEN cursor_nomrpt FOR
    SELECT DISTINCT
    CAST(plano.desc3 AS VARCHAR2(50)) category
    ,plano.name plan_name
    ,nvl(CAST(plano.desc6 AS VARCHAR2(50)),'not applicable') pcrr
    ,nvl(trunc(plano.value18,2),0) nominal_slm
    ,nvl(trunc(plano.value19,2),0) blm
    ,plano.dbdateeffectivefrom date_live
    plano.dbkey pog_id
    ,case when plano.value47 < 0 THEN 0 when plano.value47 IS NULL THEN 0 ELSE plano.value47 END AS parent_id
    FROM
    dplapro1.ix_spc_planogram plano
    INNER JOIN dplapro1.ix_spc_performance perf ON plano.dbkey = perf.dbparentplanogramkey
    INNER JOIN dplapro1.ix_spc_product product ON perf.dbparentproductkey = product.dbkey
    INNER JOIN dplapro1.ix_spc_product_key prodkey ON product.dbkey2 = prodkey.dbkey
    AND prodkey.keylevel = 2
    WHERE
    plano.value50 = 0
    AND plano.dbkey4 = p_subcatkey
    ORDER BY ltrim(rtrim(p_orderby)) ASC;
    p_orderby is the parameter being passed. But the output is not sorted. But when I run the cursor by hardcoding the parameter value it works fine...
    Need your help on this

    Hi,
    When you use a local variable in a cursor, it's as if you had hard-coded a literal in its place, so you can't use a variable for a column name.
    If you know all the possible values of p_orderby, you can do something like this:
    ORDER BY  TRIM ( CASE  p_orderby
                   WHEN  'DESC'     THEN  plano.desc
                   WHEN  'VALUE'     THEN  plano.value
               END
                ) ASC;If you don't know all the possible values, you could use dynamic SQL.
    By the way,
    TRIM (x)returns the same results as
    LTRIM ( RTRIM (x))

  • Decode in order by clause

    Is it possible to use a decode function in the order by clause, when you have two select statements with a union between? I seem to be getting an error-message telling me to type a number.
    Can anybody help me?

    Tove,
    Is this what you mean?
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(1
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
          7369 SMITH          CLERK
          7499 ALLEN          SALESMAN
          7521 WARD           SALESMAN
          7566 JONES          MANAGER
          7654 MARTIN         SALESMAN
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
          7788 SCOTT          ANALYST
          7839 KING           PRESIDENT
          7844 TURNER         SALESMAN
          7876 ADAMS          CLERK
          7900 JAMES          CLERK
          7902 FORD           ANALYST
          7934 MILLER         CLERK
    18 rows selected.Now, to order by the second column, I set the first parameter of the
    DECODE to "2":
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(2
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
            10 ACCOUNTING     NEW YORK
          7876 ADAMS          CLERK
          7499 ALLEN          SALESMAN
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
          7902 FORD           ANALYST
          7900 JAMES          CLERK
          7566 JONES          MANAGER
          7839 KING           PRESIDENT
          7654 MARTIN         SALESMAN
          7934 MILLER         CLERK
            40 OPERATIONS     BOSTON
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
          7788 SCOTT          ANALYST
          7369 SMITH          CLERK
          7844 TURNER         SALESMAN
          7521 WARD           SALESMAN
    18 rows selected.
    SQL> SELECT
      2  *
      3  FROM
      4  (SELECT
      5      empno     no
      6  ,   ename     name
      7  ,   job       description
      8  FROM          emp
      9  UNION
    10  SELECT
    11      deptno    no
    12  ,   dname     name
    13  ,   loc       description
    14  FROM          dept
    15  )
    16  ORDER BY
    17  DECODE(3
    18  ,      1,TO_CHAR(no)
    19  ,      2,name
    20  ,      3,description)
    21  /
            NO NAME           DESCRIPTION
          7788 SCOTT          ANALYST
          7902 FORD           ANALYST
            40 OPERATIONS     BOSTON
            30 SALES          CHICAGO
          7369 SMITH          CLERK
          7934 MILLER         CLERK
          7900 JAMES          CLERK
          7876 ADAMS          CLERK
            20 RESEARCH       DALLAS
          7566 JONES          MANAGER
          7698 BLAKE          MANAGER
          7782 CLARK          MANAGER
            10 ACCOUNTING     NEW YORK
          7839 KING           PRESIDENT
          7499 ALLEN          SALESMAN
          7844 TURNER         SALESMAN
          7654 MARTIN         SALESMAN
          7521 WARD           SALESMAN
    18 rows selected.I needed to put the TO_CHAR in the DECODE so all of the columns
    by which I could potentially order are VARCHAR2's, else I was
    getting
    SQL> /
    DECODE(1
    ERROR at line 17:
    ORA-01785: ORDER BY item must be the number of a SELECT-list expressionHTH
    T.

  • Can i assign an 'order by' clause dynamically in forms ??

    I know it's possible to assign an 'order by' clause in reports with lexical parameter.
    for example..
    select A
    from TABLE
    where A is not null
    &V_ORDERBY
    In this, v_orderby might be 'order by name' like that,,,
    can i assign an 'order by' clause dynamically IN FORMS ??
    If you understan my question, please answer to me,,,ㅜㅜ

    Have you tried this build-in function?
    SET_BLOCK_PROPERTY('[BLOCK_NAME]', ORDER_BY, 'SORTCOL1, SORTCOL2...');
    Where 'SORTCOL1, SORTCOL2...' are the table columns name.

  • Suppress "Order By" clause in Answers Query

    Hello,
    Is it possible to Suppress "Order By" clause in Answers Query.
    I'm using a database view as data source. In the view definition, "order by" clause is already specified. Is it possible to get the same order in the OBIEE report??
    I do not want to use Sort Order column in the repository.
    Thanks,
    Girish

    You add a rownumber to your DB view and use that to 'sort' your report.
    regards
    John
    http://obiee101.blogspot.com/

  • Order By clause in Receiver JDBC adapter

    Hello All,
    Is it possible to construct a select statement that uses an Order by clause in JDBC receiver adapter?
    ex : I would like the JDBC adapter to from a query as follows:
    <b>Select * from EMP where sal = 10000 order by empid</b>
    We are able to construct the select statement without order by clause but not with it.
    Can any one suggest me how to do it. This is bit urgent for us.
    Thanks
    Abinash

    hi,
    did you try with
    SQL_DML
    http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm
    Regards,
    michal

  • Order by clause with union

    Hi,
    I wanted to know if this is possible with order by clause and union. some how union messes up the ordering of the left part of the union statement.
    assume the data is as below in table tab1
    c1 c2
    4 1
    4 2
    5 1
    5 2
    7 1
    7 2
    8 3
    9 4
    the expected output must be for all c1 < 7 ordering must be on c1 and for all c1 > 7 ordering must be on c2.
    so the query i tried was
    select c1,c2 from tab1 where c1 <7 order by c1
    union
    select c1,c2 from tab1 where c1 >=7 order by c2
    it is giving the message 'Sql command not properly ended'.
    Suggestions are welcome

    SQL>
    SQL> With t As
      2  (
      3  Select 4 c1, 1 c2 From dual Union All
      4  Select 4 ,2       From dual Union All
      5  Select 5 ,1       From dual Union All
      6  Select 5 ,2       From dual Union All
      7  Select 7 ,1       From dual Union All
      8  Select 7 ,2       From dual Union All
      9  Select 8 ,3       From dual Union All
    10  Select 9 ,4       From dual
    11  ), t1 As (Select c1,c2 From t Where c1 <7 Order By c1)
    12  ,t2 As (select c1,c2 from t where c1 >=7 Order By c2)
    13  Select * From t1 Union All
    14  Select * From t2;
            C1         C2
             4          1
             4          2
             5          1
             5          2
             7          1
             7          2
             8          3
             9          4
    8 rows selected
    SQL> /*-- Union All
      2   select c1,c2 from t where c1 >=7
      3   Order By c1,c2;
      4  */
      5 
    with union clause order by must be placed in the end,,
    select c1 from dual union all
    select c2 from dual
    order by  c1

  • Order by clause in PL/SQL cursors

    I am trying to execute a procedure with some input parameters. I open a cursor
    with a select statement. However, the order by clause in the query does not
    recognize parameter sent through the procedure input parameters.
    For example:
    open <<cursor name>> for
    select id from member order by <<dynamic parameter>>" does not work (Compiles fine but does not return the right result).
    But if I try and give a static order by <<column name>> it works. Is the
    order by clause in the PL/SQL a compile time phenomenon?
    I have also tried it through dynamic sql. All the other parameters work except the order by <<parameter>> asc|desc
    Also "asc" and "desc" does not work if given dynamically.
    What alternatives do I have?
    null

    I don't think order by can be dynamic in a cursor, but it sure can be using dynamic sql. The only issue is that you must do a replace in the sql string with the dynamic variable. For example:
    create or replace procedure test_dyn(p_col in varchar2, p_order in varchar2) as
    q varchar2(500);
    u_exec_cur number;
    u_columnnumber NUMBER;
    u_columndate DATE;
    u_columnvarchar varchar2(50);
    u_cur_count number;
    u_ename varchar2(20);
    u_sal number;
    begin
    q := 'select ename, sal from scott.emp order by p_col p_order';
    -- got to do these two replaces
    q:= replace(q,'p_col',p_col);
    q:= replace(q,'p_order',p_order);
    u_exec_cur := dbms_sql.open_cursor;
    dbms_sql.parse(u_exec_cur,q,dbms_sql.v7);
    dbms_sql.define_column(u_exec_cur, 1, u_columnvarchar, 20);
    dbms_sql.define_column(u_exec_cur, 2, u_columnnumber);
    u_cur_count := dbms_sql.execute(u_exec_cur);
    loop
    exit when (dbms_sql.fetch_rows(u_exec_cur) <= 0);
    dbms_sql.column_value(u_exec_cur, 1, u_ename);
    dbms_sql.column_value(u_exec_cur, 2, u_sal);
    dbms_output.put_line(u_ename);
    dbms_output.put_line(u_sail);
    --htp.p(u_ename);
    --htp.p(u_sal);
    end loop;
    end;
    show errors;
    Now when when I execute my procedure I can change the order by clause all I want, for example:
    SQL> set serveroutput on;
    SQL> exec gmika.test_dyn('sal','asc');
    SMITH
    800
    ADAMS
    1100
    WARD
    1250
    MARTIN
    1250
    MILLER
    1300
    TURNER
    1500
    ALLEN
    1600
    JLO
    2222
    BLAKE
    2850
    JONES
    2975
    SCOTT
    3000
    FORD
    3000
    LOKITZ
    4500
    KING
    5000
    JAMES
    5151
    JAMES
    5555
    PL/SQL procedure successfully completed.
    SQL>
    null

  • Order by clause  Dynamic in Oracle function

    How can i get order by Clause Dynamic in Oracle function
    My function Returns sql query with SYS_REFCURSOR . and i will pass the order by column as input parameter
      create or replace
    FUNCTION TEST_SSK
            p_srot  number
    RETURN SYS_REFCURSOR
    AS
    C_testssk SYS_REFCURSOR;
    BEGIN
    OPEN C_TESTSSK FOR
    SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER
    order by P_SROT;
    return C_testssk;
    end;Edited by: user10736825 on Dec 22, 2010 11:34 AM

    you can go for a dynamic query ;)
    create or replace
    FUNCTION TEST_SSK
            p_srot  number
    RETURN SYS_REFCURSOR
    AS
    C_testssk SYS_REFCURSOR;
    l_str VARCHAR2(4000);
    l_order VARCHAR2(100);
    BEGIN
    l_str := 'SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER ';
    IF p_sort = 'LC'
    THEN
      l_order := ' ORDER BY LOAN_CODE ';
    ELSIF p_sort = 'LD'
    THEN
      l_order := ' ORDER BY LOAN_DATE ';
    END IF;
      l_str := l_str || l_order ;
    OPEN C_TESTSSK FOR l_str;
    return C_testssk;
    end;

Maybe you are looking for