Order by clause dynamic

Hello,
I created a radio button to sort the data in the form.
STATIC2:Date Asc;1, Date Desc;2, Activity;3
The data is only sorted by date asc and activity asc. The sort by date desc didn't work.
ORDER BY DECODE(:P20010100_SORT,1,to_char(ENTRY_DT,'dd/mm/yyyy')|| 'Asc',2,to_char(ENTRY_DT,'dd/mm/yyyy')|| 'Desc',3,ACT_ID || 'Asc',to_char(entry_dt,'dd/mm/yyyy')|| 'Asc')
Do you have an idea how to do it ?
Thanks in advance

You cant do order bys with ASC / DESC unless you dynamic sql or some trickery.
For example:
Make columns that reverse the values for you so that you are always sorting ASC.
order by decode(:somevar,
1,created,
2,to_date('01-jan-2999','dd-mon-yyyy')-(created))

Similar Messages

  • 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;

  • 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.

  • How to make an ORDER BY clause dynamic

    is there anyway to make the ORDER BY clause in an SQL query within a DB control
    dynamic? I have tried to pass a String of the column name and place it in the
    statement within {}, but it doesn't work

    "Mark" <[email protected]> wrote:
    >
    is there anyway to make the ORDER BY clause in an SQL query within a
    DB control
    dynamic? I have tried to pass a String of the column name and place
    it in the
    statement within {}, but it doesn't workDid you find how ? please let me know, I also need to have a dynamic order by
    clause.

  • Sorting character column ( used in order by clause dynamically)

    Hi,
    I need help on sorting character-based numbers. Like say, I want to sort customers based on street numbers(which is a character string being used in the
    order by clause) they live in.
    The criteria are :
    i. Numbers must take precedence.
    This being a character string, 1000001 comes before 2. This shouldn't happen. And you cannot use to_number
    since using it with a string having characters in it would raise an error.
    ii. If only a single alphabet occurs as the last character, then treat the whole string as a number except the last character and then sort it
    as if sorting a number. Something like : if you have 1000A, 200D, 200B, 1000X, the result would be 200B,200D,1000A,1000X.
    iii. if a character occurs elsewhere in the string, then perform the search normally as if performing a character search.
    The output of the following data :
    100
    A101
    B100A
    110C
    C120B
    120
    100020
    120C
    C1100
    100D
    would be like :
    100
    100D
    110C
    120
    120C
    100020
    A101
    B100A
    C120B
    C1100
    Please note that the sort is being done dynamically, so I could have access to the values of the street numbers only during run time.
    Any help is really appreciated.
    Thanks in advance.
    Regards,
    Anil.

    Create a function to test whether the column is numeric :
    create FUNCTION is_numeric(v_number VARCHAR2)
    RETURN INTEGER
    IS
    l_number NUMBER;
    BEGIN
    IF INSTR(UPPER(v_number),'E') > 0 THEN
    RETURN 0;
    END IF;
    l_number := TO_NUMBER(v_number);
    RETURN 1;
    EXCEPTION
    WHEN OTHERS THEN
    RETURN 0;
    END;
    And try this query
    Assume the table name is TEST with column STREET
    select * from TEST
    order by case is_numeric(STREET) when 1 then LPAD(STREET,20, ' ') else STREET end
    Please make sure that 20 mentioned above is the column size for STREET.
    Hope this helps.
    -Nags

  • How to use "Order by" clause dynamically on LOV values in 10g r2 forms

    Hi ,
    I have following requirement,please guide me.
    1 Create a List Of Values with 2 fields, Code and Description
    2. Do not use order by clause in record Group Query
    3. Attach this LOV to a field in Form
    4. When user invokes the LOV user will see two fields in LOV with header as Code and Description
    5. Now when user clicks on Column Header “Code” then LOV should be sorted on Code
    6. And if User clicks on Column Header “Description” then LOV should be sorted on Description
    Thanks in Advance.

    Kindly post this problem in this forum ->
    [Forms Forum|http://forums.oracle.com/forums/forum.jspa?forumID=82]
    And, close this thread by marked it as answered. ;)
    Regards.
    Satyaki De.

  • Dynamic ORDER BY clause

    Hi all,
    I'm creating a webpage using jsp thats accessing a mysql database. When I get a ResultSet from a query, I was wondering if anyone could give me some pointers on how I could sort the results based on a field name that someone clicks on. For example:
    Column1   Column2
    5         2
    8         1
    3         6I'd like to create hyperlinks on the field names so when a user clicks on it, it will sort the data in according to that field. Here is my code that I am trying to modify:
    public String displayResultSet(ResultSet rs)
    {// return a result set as an html table
         String htmlTable = "";
         try {
              // get the number of columns
              ResultSetMetaData rsmd = rs.getMetaData();
              int numColumns = rsmd.getColumnCount();
              // create a table and display the mysql field names as table headers
              htmlTable += "<TABLE>\n<TR>\n";
              for(int i=1; i<=numColumns; i++)
                   htmlTable += "<TH>" + rsmd.getColumnName(i) + "</TH>\n";
              htmlTable += "</TR>\n\n";
              // create an object to temporarily hold a piece of ResultSet data
              Object cellData = null;
              // display the data in the ResultSet in rows of an html table
              while(rs.next())
              {// while the ResultSet has more rows, convert them to html
                   htmlTable += "<TR>";
                   for(int j=1; j<=numColumns; j++)
                   {// if the data is not null, display it, otherwise display a blank space
                        cellData = rs.getObject(j);
                        if(cellData != null)
                             htmlTable += "<TD>" + rs.getObject(j) + "</TD>\n";
                        else
                             htmlTable += "<TD> </TD>\n";
                   htmlTable += "</TR>\n\n";
              htmlTable += "</TABLE>\n\n";
         catch (Exception e)
              { return("Error accessing database: " + e); }
         return htmlTable;
    }Any help or references to where I can read up on it would be appreciated. Thanks
    Leon

    Your display code should not be mixed in with your database code. That functionality should be seperated classes.
    Generally GUIs do the ordering themselves. They do not repeatedly call the database.
    But if you want you pass in a descriptor that defines the fields that will be ordered on. You optionally map that to the exact database field names. You then use StringBuilder to construct the entire SQL string and add the order by clause dynamically at the end. Then you execute it.

  • Order by clause require dynamic value

    Hi
    I want to bind parameters to orderby clause. In where clause with bind parameter works fine. But in orderby clause ive done similar steps to have a dynamic sort which will be passed from the previous page in a session variable. Although it didnt show any error at the backend where i can see data getting binded, but no sorting is taking place.
    Can u help me to solve this.
    regards
    Jayashri

    Jayashri,
    I have tested this and you are right. And there does occur an error at the backend, only you wont see it unless you run with BC4J debug mode turned on. You can do this by providing -Djbo.debugoutput=console to the JVM. When running inside JDeveloper, you can accomplish this by going to Project Properties => PRofiles => Development => "Runner", and fill this in at the "Java Options" field.
    Doing that will show the reason of the problem. When a view object is queried, BC4J actually performs 2 queries. One to obtain the 'estimated row count', and then one to obtain the action rows.
    Now suppose your query looks like this:
    SELECT <somefields> FROM <table>
    WHERE <field> = :1 ORDER BY :2
    Bc4j will construct the following query to obtain the estimated rowcount:
    SELECT count(1) FROM (SELECT <somefields> FROM <table> WHERE <field> = :1)
    As you can see, it does NOT include the ORDER BY of the original query in this statement, probably for performance reasons (why order the set if you are only interested in the count). Unfortunately, it WILL try to bind both :1 AND :2 to this query, but because there is only one bind variable in this query, this throws an java.sql.SQLException which is unfortunately trapped somewhere in BC4J code, and not shown in the regular log file.
    I am pretty confident that this is actually a BC4J bug (or known restriction). You could post this problem at the JDeveloper Forum to determine this (without mentioning JHeadstart, because this would also happen if you wrote your own code for binding these parameters).
    As for a workaround, you could try the following:
    1.) Remove the (bind parameter from) the order by clause on the ViewObject
    2.) Remove that same bind parameter from the "Query Bind Parameters" property.
    You should now have gone back to a scenario where there are only bind parameters on the where clause. You would need to set the OrderBy clause programatically now. To do this, extend the JhsDataAction for this page, and override the method 'applyIterBindParams()'. Before calling super, try something like:
    ViewObject vo = ib.getRowSetIterator().getRowSet().getViewObject();
    vo.setOrderByClause(<your dynamic orderby>);
    Kind regards,
    Peter Ebell
    JHeadstart Team

  • JPA dynamic order by clause

    I need to dynamically build the order by clause of my query.
    I tried this:
    <named-query name="list">
      <query>
        <![CDATA[
          SELECT p FROM Person p
          ORDER BY :orderby
        ]]>
      </query>
    </named-query>
    @SuppressWarnings("unchecked")
    public List<Person> list(String sort) {
      Query query = getEntityManager().createNamedQuery("list");
      query.setParameter("orderby", sort);
      return query.getResultList();
    }But at runtime it throws an exception:
    com.microsoft.sqlserver.jdbc.SQLServerException:
    L'elemento SELECT identificato da ORDER BY 1 include una variabile nell'espressione che identifica la posizione di una colonna.
    Le variabili sono consentite solo nell'ordinamento in base a un'espressione che fa riferimento a un nome di colonna.The translation of the italian message is something like:
    The SELECT element identified by ORDER BY 1 includes a variable that identifies the position of a column.
    The valid variables in the order by clause must refer to the name of a columnThe value of the parameter sort is_ the name of a column!
    Any hint?

    My solution was to append the order clause to an "namedQuery" like this:
    - declare the named query as usual, with annotation
    - create a simple helper function like findNamedQuery to find the query string for a given class and queryName (using reflection)
    - if you need to execute the query without sort order - use EntityManager.createNamedQuery (as usual)
    - BUT: if you want to sort data: use EntityManager.createQuery with the string obtained from findNamedQuery and the sort clause
    I guess the is a performance penalty, but.. .it works.

  • Dynamically change the value in order by clause (urgent)

    Could any one help atall with this.
    I have a cursor within a procedure and i want to be able to pass parameter into the procedure so that the record fetched by the cursor can be ordered by the parameter passed in.
    For instance
    create or replace procedure select_all(p_order_by in varchar2) is
    cursor r_cur (c_order_by in varchar2) is
    select empno,empname,job,manager,salary
    from emp
    ordry by c_order_by;
    r_rec r_cur%rowtype;
    lv_order_by varchar2(30);
    begin
    lv_order_by := p_order_by;
    for r_rec in r_cur(lv_order_by) loop
    dbms_output.put_line(empno||empname||job||manager||salary);
    end loop;
    end;
    I have obviously done it as written above but the output is not ordered by the value i passed into the procedure when ran. Is the a better way to achieve the desired result?

    I handle dynamic order by using dynamic sql
    create or replace procedure select_all
                   (p_order_by  in varchar2) is
    TYPE               RefCurTyp is REF CURSOR;
    CV                    REFCURTYP;
    v_sql_stmt  VARCHAR2(4000) ;
    r_rec r_cur%rowtype;
    BEGIN
      v_sql_stmt := 'select empno,empname,job,manager,salary '||
                                ' from emp ' ||
                                ' ORDER BY '||p_order_by ;
      open CV for v_sql_stmt;
      loop
            fetch CV into r_rec ;
                    exit when CV%NotFound;
            dbms_output.put_line(r_rec.empno||' '||r_rec.empname||' '||r_rec.job||' '||r_rec.manager||' '||r_rec.salary);
      end loop;
    close CV;
    end;

  • 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?

  • OA Framework LOV – How to add where clause dynamically at runtime

    Hi All,
    Following is my page design:
    MainAM (This is root Application module) Package is: mycompany.oracle.apps.<product>.<project>.server
    MainPageVO (This is the View Object associated to Main AM)
    LovAM (This Application module is for LOVs) Package is: mycompany.oracle.apps.<product>.<project>.lov.server
    FileNameLovVO (This is the View Object is for "File Name" LOV. It is associated LovAM)
    I my main page is attached to the "Main AM". In the main page, I have a custom search region and in that there is a messageLovInput type of field based on "FileNameLovVO". The field name is File Name.
    Use Case:
    When a user opens the page, I determine user type. If the use is a clerk (not a superuser) then I need to restrict values in my File Name LOV by setting where clause dynamically.
    Issue1:
    ====
    In the main page controller when I do following, OA Framework is not able to access the "FileNameLovVo".
    1. Following code is from the main page's controller:
    String userId = 100;
    LovAMImpl lovAm = new LovAMImpl();
    Serializable[] lovParameters = {userId};
    Class[] lovParamTypes = { String.class };
    lovAm.invokeMethod("initLovQuery", lovParameters, lovParamTypes);
    2. In LovAMImpl class I have created following method:
    public void initLovQuery(String useId)
    FileNameLovVOImpl fileNameLovVo = getFileNameLovVO1(); // ******This returns NULL*******
    if (fileNameLovVo == null)
    MessageToken[] errTokens = { new MessageToken("OBJECT_NAME", "getFileNameLovVO1")};
    throw new OAException("AK", "FWK_TBX_OBJECT_NOT_FOUND", errTokens);
    fileNameLovVo.initQuery(userId);
    In the above code "FileNameLovVOImpl fileNameLovVo = getFileNameLovVO1();" is returning NULL.
    Please let me know what am I missing here.
    I resolved above issue with following work around:
    1. Attached "FileNameLovVO" to "MainAM"
    2. Moved initLovQuery(String useId) method to "MainAMImpl" class.
    Is that the correct way? I would prefer NOT to attach "FileNameLovVO" to "MainAM". Any suggestions?
    Issue2:
    ====
    After using above work around I tried to set WHERE clause dynamically:
    FileNameLovVO is based on following SQL query:
    SELECT DISTINCT file_name FROM <table> WHERE USER_ID like :1
    I need to pass value for USER_ID if the user is a clerk and I need to pass '%' if the user is a supper user. I'm passing value in "LovVo.initQuery(userId)" method using following code:
    public void initQuery(String userId)
    StringBuffer whereClause = new StringBuffer(1000);
    Vector parameters = new Vector(1);
    int bindCount = 0;
    setWhereClauseParams(null);
    if ((userId != null) && (!("".equals(userId.trim()))))
    parameters.addElement(servicerId);
    whereClause.append(++bindCount);
    if (bindCount > 0)
    Object[] params = new Object[bindCount];
    parameters.copyInto(params);
    setWhereClauseParams(params);
    executeQuery();
    When I select LOV at runtime in the page, it fails with following error:
    oracle.apps.fnd.framework.OAException: oracle.jbo.SQLStmtException: JBO-27122: SQL error during statement preparation. Statement: SELECT * FROM (SELECT DISTINCT file_name FROM <table> WHERE user_id LIKE :1) QRSLT WHERE (( UPPER(FILE_NAME) like :1 AND (FILE_NAME like :2 OR FILE_NAME like :3 OR FILE_NAME like :4 OR FILE_NAME like :5))) ORDER BY file_name desc
    OA Framework tries to create following statement:
    SELECT *
    FROM (SELECT DISTINCT file_name
    FROM <table>
    WHERE user_id LIKE :1) qrslt
    WHERE (( UPPER (file_name) LIKE :1
    AND ( file_name LIKE :2
    OR file_name LIKE :3
    OR file_name LIKE :4
    OR file_name LIKE :5
    ORDER BY file_name DESC
    Any help is greatly appreciated.
    Thanks for your help guys.
    Mitesh

    I have a lovinput item which has an external LOV attached to it - the VO uses the below sql query. I want to display the addresses of the customer accounts belonging to the customer name or account entered. I have a PPR event in the account number field which is calling the onAccountNumber method in my AM - the method is getting triggered when you enter the account number and the vo returns the rowcount as 3 exactly but if you click the lovinput item - it brings back all the addresses available instead bringing back addresses beloning to the account number.
    public void OnAccountNumber(String accountNumber,String partyName,
    Boolean executeQuery)
    System.out.println("Im here on account number" + accountNumber + " PartyName:" + partyName);
    AddressVOImpl Addrvo= getAddressVO1();
    Vector parameters = new Vector(2);
    StringBuffer whereClause = new StringBuffer(100);
    int clauseCount = 0;
    int bindCount = 0;
    Addrvo.setWhereClauseParams(null); // Always reset
    if ((accountNumber != null) && (!("".equals(accountNumber.trim()))))
    whereClause.append(" Account_Number = :");
    whereClause.append(++bindCount);
    parameters.addElement(accountNumber);
    clauseCount++;
    if ((partyName != null) && (!("".equals(partyName.trim()))))
    if (clauseCount >0){
    whereClause.append(" AND ");
    whereClause.append(" Party_Name like :");
    whereClause.append(++bindCount);
    parameters.addElement(partyName);
    clauseCount++;
    Addrvo.setWhereClause(whereClause.toString());
    if (bindCount >0)
    Object[] params=new Object[bindCount];
    parameters.copyInto(params);
    Addrvo.setWhereClauseParams(params);
    System.out.println("AddressVO:" + Addrvo.getQuery() );
    //Addrvo.executeQuery();
    System.out.println("Addr Cnt:" + Addrvo.getRowCount());
    SQL used in VO
    =========
    SELECT hl.address1
    || ' '
    || hl.address2
    || ' '
    || hl.address3
    || ' '
    || hl.city
    || ' '
    || hl.postal_code
    || ' '
    || hl.state
    || ' '
    || hl.country address,
    hca.account_number,hp.party_name
    FROM hz_cust_accounts hca,
    hz_cust_site_uses_all hcsu,
    hz_cust_acct_sites_all hcs,
    hz_party_sites hps,
    hz_locations hl,
    hz_parties hp
    WHERE hcsu.cust_acct_site_id = hcs.cust_acct_site_id
    AND hcs.party_site_id = hps.party_site_id
    AND hps.location_id = hl.location_id
    AND hca.cust_account_id = hcs.cust_account_id
    AND hcsu.site_use_code = 'SHIP_TO'
    AND hcsu.status = 'A'
    AND hp.party_id = hps.party_id
    AND hp.party_id = hca.party_id
    -- AND account_number=6028
    Can someone please tell me how to restrict the addresses lov to an entered account number or customer name??

  • 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 in runtime

    Hi All,
    I want to order my SELECT using "dynamic ORDER BY". I have a CURSOR (in my PL/SQL procedure) contains a select with ORDER BY clause. I have implemented two combobox in my form (the first contains the column name, the second contains ASC and DESC).I tried with the next:
    1) Dynamic ORDER BY in CURSOR with combobox results. IT DOESN'T WORK.
    2) Using a block property named "ORDER BY CLAUSE". Here I put, for example, :myBlock.comboColumnOrder. IT DOESN'T WORK.
    3) Using a function: set_block_property(myBlock,order_by,:myBlock.comboColumnOrder) or set_block_property(myBlock,default_where,:myBlock.comboColumnOrder). IT DOESN'T WORK.
    4) Using dynamic CURSOR: ORACLE FORMS give me an error that said: "...it can't to the CLIENT-SIDE".
    I have thought my last solution, but it maybe cumbersome. I do a TEMPORARY TABLE, and my CURSOR insert in this TABLE, and then I'll fetch to my BLOCK.
    Thanks a lot.
    PS: My ORACLE Version is 10g.

    PROCEDURE CHEQUEAR_V0 IS
         V_ORDEN VARCHAR2(50) := '' || :BLOCK_CHECK.ORDER_BY_NAME || ' ' || :BLOCK_CHECK.ORDER_BY_ASC_DES ;
    CURSOR FILA_RESULTADO_TABLA IS
         SELECT Last_name,First_name,App_user, App_role, UserDB
         FROM adm_users
         WHERE
         ((Last_name IS NULL OR Last_name LIKE '%'||:BLOCK_CHECK.Last_name||'%') AND
         (First_name IS NULL OR First_name LIKE '%'||:BLOCK_CHECK.First_name||'%') AND
         (App_user IS NULL OR App_user LIKE '%'||:BLOCK_CHECK.App_user||'%') AND
         (App_role IS NULL OR App_role LIKE '%'||:BLOCK_CHECK.App_role||'%') AND
         (UserDB IS NULL OR UserDB LIKE '%'||:BLOCK_CHECK.User_DB||'%'))
    ORDER BY V_ORDEN;
         V_Last_name VARCHAR2(50);
         V_First_name VARCHAR2(50);
         V_App_user VARCHAR2(50);
         V_App_role VARCHAR2(50) ;
         V_User_DB VARCHAR2(50);
         CONT NUMBER ;
    BEGIN
         CONT := 1 ;
              GO_BLOCK('BLOCK_APPS_GRANTS');     
              CLEAR_BLOCK;
         SYNCHRONIZE;     
              OPEN FILA_RESULTADO_TABLA;
              LOOP
                   FETCH FILA_RESULTADO_TABLA INTO V_Last_name,V_First_name,V_App_user,V_App_role,V_User_DB ;
              EXIT WHEN FILA_RESULTADO_TABLA%NOTFOUND;
                        :BLOCK_APPS_GRANTS.Last_name := V_Last_name ;           
                        :BLOCK_APPS_GRANTS.First_name := V_First_name ;                               
                        :BLOCK_APPS_GRANTS.App_user := V_App_user ;
                        :BLOCK_APPS_GRANTS.App_role := V_App_role ;
                        :BLOCK_APPS_GRANTS.User_DB := V_User_DB ;                                         
                   NEXT_RECORD;
                   CONT := CONT+1;          
              END LOOP;
              IF FILA_RESULTADO_TABLA%ISOPEN THEN
                   CLOSE FILA_RESULTADO_TABLA;
              END IF;
              SET_BLOCK_PROPERTY('BLOCK_APPS_GRANTS', ORDER_BY, :BLOCK_CHECK.ORDER_BY_NAME || ' ' || :BLOCK_CHECK.ORDER_BY_ASC_DES);
              GO_BLOCK('BLOCK_APPS_GRANTS');
              EXECUTE_QUERY;
    synchronize;
              exception when others then
                   raise;
    END;
    Thanks a lot.
    Edited by: user11285646 on 22-jul-2009 2:30

  • IN clause with ORDER BY clause in sub-queries

    Hello,
    We generate dynamic queries with the following statement pattern (could be many union/intersect sub-queries):
    select my_col
    from my_table
    where my_col IN
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    I know that I can do just the sub-queries w/ an ORDER BY clause as follows (as long as the 2nd parameter in the select stmts are of the same type):
    select table_2.my_col , x_col from table_2 where x_col > 10
    UNION
    select table_3.my_col , y_col from table_3 where y_col > 20
    INTERSECT
    select table_4.my_col , z_col from table_4 where z_col is between 30 and 50
    order by 2 desc
    But my questions are:
    1. What is (if there is) the syntax that will ensure that the result set order will be that of the ordering of the sub-queries?
    Or does my SQL stmt have to have syntactically (but not semantically) change to achieve this?
    Thanks,
    Jim

    Randolf Geist wrote:
    just a minor doubt - I think it is not officially supported to have separate ORDER BYs in a compound query with set operators (e.g. UNION / UNION ALL subsets). Of course one could use inline views with NO_MERGE + NO_ELIMINATE_OBY hints, but I think the only officially supported approach is to use a single, final ORDER BY (that needs to use positional notation as far as I remember).
    Randolf,
    You're right, of course, about the separate "order by" clauses.
    Interestingly the following type of thing does work though (in 10.2.0.3, at least):
    with v1 as (
        select * from t1 where col1 = 'ABC' order by col2
    v2 as (
        select * from t1 where col1 = 'DEF' order by col2
    select * from v1
    union all
    select * from v2
    ;A quick check the execution plan suggsts that Oracle appears to be convering this to the following - even though its technically not acceptable in normal circumstances:
    select * from t1 where col1 = 'ABC' order by col2
    union all
    select * from t1 where col1 = 'DEF' order by col2
    ;Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk
    To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
    "Science is more than a body of knowledge; it is a way of thinking"
    Carl Sagan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for