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

Similar Messages

  • Decode in order by clause with desc

    I want to user order by clause with decode + desc order.
    somthing like
    ORDER BY DECODE ('SALE', e.sale, 'SALE DESC' ????)
    ????-> How to use desc order with decode
    Thanks in advance

    I thought smart people in this OTN community will understand that I am trying to order by the thisdate column that is timestamp datatype:). My apologize for not being that specific.
    The query I gave is a simple version of the stored procedure I am using. The point is I need to order by - depending on one of the parameters that is passed to the procedure. In simplest decode statements, its something like
    order by decode(p_in_var,'ABC','thisdate asc','DEF','thisdate desc',thisdate asc)
    Here p_in_var is varchar input parameter to the stored procedure.
    Please let me know if there is any more information needed.
    Thx!

  • Report with user parameter is not runnig

    Hi
    I have created the report with user parameter p_deptno and qyery"select * from emp where depno=:p_deptno";
    when i run the report in paper layout a popup kind page will open and ask us to enter the deptno and based on input parameter it fetches record in report.
    if i tried the same thing with url :http://localhost:portno/reports/rwservlet?destype=cache&desformat=pdf&report=emp.jsp&userid=scott/tiger@orcl
    the parameter window not opening and and blank report will open with coloumn headings.
    help me to solve the problem.
    i am using devsuite oracle10g release 2 on linux(OEL4).

    Hello,
    You have to provide the parameter in the URL :
    For example :
    http://localhost:portno/reports/rwservlet?destype=cache&desformat=pdf&report=emp.jsp&userid=scott/tiger@orcl&p_deptno=10
    or use the Web parameter Form :
    http://localhost:portno/reports/rwservlet?destype=cache&desformat=pdf&report=emp.jsp&userid=scott/tiger@orcl&paramform=true
    Regards

  • 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

  • SQL IN clause with Bind parameter?

    Hi
    I have a simple task that hasn't been so simple to figure out. I want to allow a user to search for one or more comma-separated values in a simple JClient ADF app. Is there a way to use a SQL IN clause with a single bind variable? e.g. SELECT TITLE FROM CITATION WHERE ID IN (:0)
    When I pass a single value it works fine but a comma separated list doesn't.
    Thanks
    John

    Update: I wanted to combine the techniques found in two of Steve Muench's articles -
    1) Providing Default Values for View Object Bind Variables (so I could display an ADF-bound JPanel with defaults)
    http://radio.weblogs.com/0118231/stories/2004/10/07/providingDefaultValuesForViewObjectBindVariables.html
    2) Array of String Domain Example (so a user could enter one or more comma-separated values into a text box for DB searches)
    http://radio.weblogs.com/0118231/stories/2004/09/23/notYetDocumentedAdfSampleApplications.html
    I learned some helpful stuff about the framework but spent lots of time banging my head against the wall because the two examples wouldn't work when directly combined. To best understand this, be sure to study Steve's examples above.
    In example 1 Steve passes an array of objects (Object[] DEFAULT_VALUES) to the ViewObject's where clause using the setWhereClauseParams(Object[] values). However, in example 2 he creates an Oracle Array which contains an Oracle ArrayDescriptor, Connection, and array of values to pass to the "IN" bind variable. Also, example 1 allows for multiple bind vars to be included whereas example 2 allows for an array of data to be passed to a single bind var. Even though my code provides an array to a single bind var (per ex. 2) it should still allow for the passage of multiple bind vars with minimal code modification.
    Code from Steve's example 1 was copied into my EmpView ViewObject but certain modifications were necessary:
    1) Change the ViewObject's DEFAULT_VALUES from Object[] to String[].
    2) Modify the executeQueryForCollection() method in the ViewObject to call a function which will set the bind variables as Oracle Arrays (effectively converting the "params" data type from that of String[] to Oracle Array[])
    3) Create a setManagerID(String[]) method in the EmpView object and expose it to the client.
    (there are a number of others so it's best for you to go through the code and compare)
    I finally got it working so I'm attaching the code, however beware - I'm new to this so there may be other, better ways to go about it. Also, there are no framework bind vars so that section of code is never executed...it compiles but may fail at run time.
    In order for this to work I suggest you use JDev to re-create the EmpView and Panel1 objects. This will ensure that the necessary ADF framework components are generated. Once complete, then copy in the code provided.
    *File: EmpViewImpl.java
    *Created as Read-Only access view object with the
    *query:
    *select manager_id, last_name from hr.employees
    *where manager_id IN
    *(select * from TABLE(CAST(:0 as TABLE_OF_VARCHAR)))
    *order by manager_id
    package model;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import oracle.jbo.domain.Array;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.sql.ArrayDescriptor;
    // --- File generated by Oracle ADF Business Components Design Time.
    // --- Custom code may be added to this class.
    // --- Warning: Do not modify method signatures of generated methods.
    public class EmpViewImpl extends ViewObjectImpl implements model.common.EmpView
    private ArrayDescriptor descriptor;
    private final static String[] DEFAULT_VALUES_STRING = new String[]{"100"};
    private final static int NUM_DEFAULT_VALUES = DEFAULT_VALUES_STRING.length;
    * This is the default constructor (do not remove)
    public EmpViewImpl()
    protected void executeQueryForCollection (Object qc, Object[] params, int numUserParams)
    Object pars[] = null;
    // Bind default variables only if none have been provided by the user
    if (numUserParams == 0)
    numUserParams = NUM_DEFAULT_VALUES;
    int numFwkSuppliedBindVals = (params != null) ? params.length : 0;
    if (numFwkSuppliedBindVals > 0)
    // Allocate a new Object[] array with enough room for both user- and framework-supplied vars
    Object[] newBinds = new Object[numFwkSuppliedBindVals + numUserParams];
    // Copy the framework-supplied bind variables into a new Object[] array
    // leaving enough slots at the beginning for the user-supplied vars
    System.arraycopy(params, 0, newBinds, numUserParams, numFwkSuppliedBindVals);
    // Now copy in the user-supplied vars to the beginning of the array
    System.arraycopy(DEFAULT_VALUES_STRING, 0, newBinds, 0, numUserParams);
    params = newBinds;
    } else
    params = DEFAULT_VALUES_STRING;
    // We have to call this method to convert the default values into the proper Oracle Array expected by the query.
    // If you set a debugger breakpoint at this line you can see that the "params" data type changes from String[] to Object[]
    setWhereClauseParamsToDefaultValues();
    // Now retrieve the params of the new data type
    params = this.getWhereClauseParams();
    super.executeQueryForCollection(qc, params, numUserParams);
    private void setWhereClauseParamsToDefaultValues()
    this.setManagerID(DEFAULT_VALUES_STRING);
    private Connection getCurrentConnection() throws SQLException
    // Create a bogus statement so that we can access our current connection
    // JBD note - Does this get run each time??
    PreparedStatement st = getDBTransaction().createPreparedStatement("commit", 1);
    Connection conn = st.getConnection();
    st.close();
    return conn;
    private synchronized void setupDescriptor(Connection conn) throws SQLException
    descriptor = new ArrayDescriptor("TABLE_OF_VARCHAR", conn);
    * setManagerID
    * Exposed to client to accept an array of values (presumably passed in by user-entry into text box
    * @param aryMan
    public void setManagerID(String[] aryMan)
    Array arr = null;
    try
    // Find the connection
    Connection conn = getCurrentConnection();
    //Create the ArrayDescriptor by looking for our custom data type in our connected DB
    if(descriptor == null)
    setupDescriptor(conn);
    // Create the Oracle Array by passing in the descriptor, connection, and object array of data
    arr = new Array(descriptor, conn, aryMan);
    } catch (SQLException se)
    System.out.println("SQL Exception: " + se.getMessage());
    // Now we can set the WHERE clause parameter bind variable (index = 0) to the Oracle Array
    if (arr != null) setWhereClauseParam(0, arr);
    * FILE: Panel1.java
    * Created as an empty panel. Then a JTextField, a
    * JButton, and an EmpView1 table were dragged on.
    * A custom actionPerformed method was created for the
    * JButton which grabs the data from the text box.
    * The user can enter either a single manager id or
    * multiple, comma-separated ids.
    * All code in this class was created by JDev except
    * for the Jbutton action
    package view;
    import java.awt.*;
    import javax.swing.*;
    import model.common.*;
    import oracle.jbo.ApplicationModule;
    import oracle.jbo.SQLStmtException;
    import oracle.jbo.uicli.jui.*;
    import oracle.jbo.uicli.controls.*;
    import oracle.jbo.uicli.binding.*;
    import oracle.jdeveloper.layout.*;
    import oracle.adf.model.*;
    import oracle.adf.model.binding.*;
    import java.util.ArrayList;
    import oracle.jdeveloper.layout.VerticalFlowLayout;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class Panel1 extends JPanel implements JUPanel
    * NOTE: You need to have previous created the Oracle8 type named
    * ==== TABLE_OF_VARCHAR by doing the following at the SQL*Plus
    * command prompt:
    * create type table_of_varchar as table of varchar2(20)
    // Panel binding definition used by design time
    private JUPanelBinding panelBinding = new JUPanelBinding("Panel1UIModel");
    private VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();
    private JTextField jTextField1 = new JTextField();
    private JButton jButton1 = new JButton();
    private JTable jTable1 = new JTable();
    * The default constructor for panel
    public Panel1()
    * the JbInit method
    public void jbInit() throws Exception
    this.setLayout(verticalFlowLayout1);
    jTextField1.setText("jTextField1");
    jButton1.setText("jButton1");
    jButton1.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    jButton1_actionPerformed(e);
    this.add(jTextField1, null);
    this.add(jButton1, null);
    this.add(jTable1, null);
    jTable1.setModel((TableModel)panelBinding.bindUIControl("EmpView1", jTable1));
    public static void main(String [] args)
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception exemp)
    exemp.printStackTrace();
    Panel1 panel = new Panel1();
    panel.setBindingContext(JUTestFrame.startTestFrame("DataBindings.cpx", "null", panel, panel.getPanelBinding(), new Dimension(400, 300)));
    panel.revalidate();
    * JUPanel implementation
    public JUPanelBinding getPanelBinding()
    return panelBinding;
    private void unRegisterProjectGlobalVariables(BindingContext bindCtx)
    JUUtil.unRegisterNavigationBarInterface(panelBinding, bindCtx);
    private void registerProjectGlobalVariables(BindingContext bindCtx)
    JUUtil.registerNavigationBarInterface(panelBinding, bindCtx);
    public void setBindingContext(BindingContext bindCtx)
    if (panelBinding.getPanel() == null)
    panelBinding = panelBinding.setup(bindCtx, this);
    registerProjectGlobalVariables(bindCtx);
    panelBinding.refreshControl();
    try
    jbInit();
    panelBinding.refreshControl();
    catch(Exception ex)
    panelBinding.reportException(ex);
    private void jButton1_actionPerformed(ActionEvent e)
    // Get the user-supplied values
    String txt = jTextField1.getText();
    String[] mIds = txt.split(",");
    // Now trim
    for (int i=0; i<mIds.length; i++)
    mIds[i] = mIds.trim();
    ApplicationModule am = (ApplicationModule)panelBinding.getDataControl().getDataProvider();
    EmpView vo = (EmpView)am.findViewObject("EmpView1");
    vo.setManagerID(mIds);
    try
    vo.executeQuery();
    } catch (SQLStmtException s)
    System.out.println("Query failed: " + s.getMessage());

  • ViewObjects Order by clause with DECODE

    Hello!
    I am using Jdeveloper 11g, version 11.1.1.2.0.
    The problem I'm having is this.
    If I use a DECODE statement in view objects ORDER BY clause, I get an error: "java.util.regex.PatternSyntaxException: Unmatched closing ')' near index 2".
    Let me give an example. I'll be using EmployeesView view object, which is using Employees entity from HR schema.
    This is a part of view objects XML.
    <ViewObject
    xmlns="http://xmlns.oracle.com/bc4j"
    Name="EmployeesView"
    Version="11.1.1.55.36"
    SelectList="Employees.EMPLOYEE_ID,
    Employees.FIRST_NAME,
    Employees.LAST_NAME,
    Employees.EMAIL,
    Employees.PHONE_NUMBER,
    Employees.HIRE_DATE,
    Employees.JOB_ID,
    Employees.SALARY,
    Employees.COMMISSION_PCT,
    Employees.MANAGER_ID,
    Employees.DEPARTMENT_ID"
    FromList="EMPLOYEES Employees"
    BindingStyle="OracleName"
    CustomQuery="false"
    PageIterMode="Full"
    UseGlueCode="false"
    OrderBy="Employees.MANAGER_ID">
    As you can see in this case, the Order by clause is very simple. This works like a charm.
    But, if put something like this "DECODE(Employees.MANAGER_ID, NULL, 1, 2)" in the Order by, I get an internal parsing error.
    I replicated this error on my home machine as well as on my work machine. I'm using the same version of Jdeveloper on both.
    Has anyone else stumbled upon this problem and solved it?
    Any thoughts would be greatly appreciated :)
    Kristjan

    The second example works, but the first one doesn't, unfortunately :/
    Also, the example I gave is unfortunately just that, a proof-of-concept example that there is a problem with DECODE if it is written inside the Order by clause.
    My real DECODE use case is a bit different. Like this: "DECODE(attribute, 'N', 1, 2) ASC".
    Since posting my original question, I did some research-by-example work and I discovered that this is not just a problem of DECODE, but more like a problem of brackets and commas.
    No database function that uses more than one parameter can be used in Order by clause.
    The reason is, if a function with more than one parameter is used, commas inside brackets have to be used. Something along the lines of: "database_function(param1, param2, ...)".
    The parser seems to have a problem with this kind of expressions.
    Is there a work around?
    Kristjan
    p.s.: Thank you for your quick response.

  • 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 with Empty Field values !

    Hello,
    In Oracle , the order by clause does not return the expected query result, if any of the field value in the order by clause has an empty string.
    Oracle treats the empty string as null value and ORDER BY gives a result with the empty string field values listed at last.
    For example :
    test is a sample table containing "name" field.
    Query: "select name from test order by name"
    In SQL Server/Access
    Result (1)
    NAME
    (blank)
    (blank)
    User1
    User2
    User3
    In Oracle
    Result (2)
    NAME
    User1
    User2
    User3
    (blank)
    (blank)
    I know some of the Work arounds for this as listed below :
    1) To use NVL in Order By Clause.
    i.e., the modified query
    "select name from test order by nvl(name,0)"
    gives the result same as Result (1).
    2) To have single blank space in the field value if it is empty.
    I dont want to use either of these two options b'se it would lead to a mass change in my existing code.
    Is there any way i can do a
    collation order settings in the Oracle databases to get the results as in MS SQL/Access.
    Can Any help me out in Solving this?
    Thanks
    Devi Shankar
    null

    Bharath,
    I am moving this question to the SQL forum.
    Regards,
    Geoff

  • Conditional order by clause with multiple columns

    I would like to know whether it is possible to include multiple columns in a conditional order by clause.
    Ex: I have written the following PL / SQL :
    CREATE PROCEDURE GetProducts
    @OrderBy VARCHAR(50),
    @Input2 VARCHAR(30)
    AS
    BEGIN
    SET NOCOUNT ON
    SELECT Id, ProductName, Description, Price, Quantity
    FROM Products
    WHERE ProductName LIKE @Input2
    ORDER BY
    CASE               
    WHEN @OrderBy = 'ProductNameAsc' THEN ProductName
    END ASC,
    CASE
    WHEN @OrderBy = 'ProductNameDesc' THEN ProductName
    END DESC
    END
    Now I want to include when the Orderby - "Productnameasc" then order by productname, price, stdate
    else
    orderby productname, crdate, category
    Could this be done? I tried it, but couldn't get this to work.
    Any help is greatly appreciated.

    Since matching ORDER BY columns have different data types (first column for CLERK is sal - number, first column for MANAGER deptno is number but first column for "else" is a string) we need to convert number to string but preserve number sort order. Since DEPTNO is NUMBER(2) we will use TO_CHAR with format 'S00'. Since SAL is NUMBER(7,2) we will use TO_CHAR with format model 'S00000D00'. For EMPNO we will use TO_CHAR with format model 'S0000'.
    select  deptno,
            empno,
            ename,
            job,
            sal
      from  emp
      order by case job
                 when 'CLERK' then to_char(sal,'S00000D00')
                 when 'MANAGER' then to_char(deptno,'S00')
                 else ename
               end,
               case job
                 when 'CLERK' then to_char(deptno,'S00')
                 else job
               end,
               case job
                 when 'CLERK' then job
                 when 'MANAGER' then to_char(empno,'S0000')
               end
        DEPTNO      EMPNO ENAME      JOB              SAL
            20       7369 SMITH      CLERK            800
            30       7900 JAMES      CLERK            950
            20       7876 ADAMS      CLERK           1100
            10       7934 MILLER     CLERK           1300
            10       7782 CLARK      MANAGER         2450
            20       7566 JONES      MANAGER         2975
            30       7698 BLAKE      MANAGER         2850
            30       7499 ALLEN      SALESMAN        1600
            20       7902 FORD       ANALYST         3000
            10       7839 KING       PRESIDENT       5000
            30       7654 MARTIN     SALESMAN        1250
        DEPTNO      EMPNO ENAME      JOB              SAL
            20       7788 SCOTT      ANALYST         3000
            30       7844 TURNER     SALESMAN        1500
            30       7521 WARD       SALESMAN        1250
    14 rows selected.
    SQL>  SY.

  • ORDER BY clause with expression

    Considering that all the column names and table name is valid, what happens internally when the following query is run?
    SQL> SELECT STU_ID, STU_NAME FROM STUDENT ORDER BY 2+3, STU_ID;
    What i found out was the rows get ordered in ascending order of STU_ID. It's quite clear that it is ignoring the expressing 2+3, so my doubts are:
    (a) Is it appending any pseudo-column to the table with 2+3 getting evaluated to 5?
    (b) If there exist a 5th column in the table student and we specify it in the select statement's select list (5 column names) then why its not considering it as 5 and sorting the data according that?
    (c) Is it true that, any expression we write is getting evaluated to NULL? Then is it that ORDER BY NULL evaluates to no ordering and the parser searches for next column-name or position (if specified) ?
    (d) if neither then, what's the reason of the ignorance?

    Hi,
    Welcome to the forum!
    987236 wrote:
    Considering that all the column names and table name is valid, what happens internally when the following query is run?
    SQL> SELECT STU_ID, STU_NAME FROM STUDENT ORDER BY 2+3, STU_ID;
    What i found out was the rows get ordered in ascending order of STU_ID. It's quite clear that it is ignoring the expressing 2+3, so my doubts are:
    (a) Is it appending any pseudo-column to the table with 2+3 getting evaluated to 5There's no pseduo-column involved. (Pseudo-columns are something that Oracle provides for you, without you having to spell out what you want. ROWID and LEVEL are examples of pseudo-columns. In this example, 2+3 is an Expression . Like pseudo-columns, expressions can usually appear in the ORDER BY clause, even though they are not actually stored in the table.)
    It's sorting first by the NUMBER 5 (= 2 + 3), not the 5th column. Since the NUMBER 5 has the same value on every row, every row ties for first place. The result of sorting by any constant is the same; the results are the same as not including that exrpression in the ORDER BY clause. That is the ORDER BY clause you posted is equivalent to
    ORDER BY  2 + 3
    ,         'foo'
    ,         SYSDATE
    ,         NULL
    ,         stu_idand it's also equivalent to
    ORDER BY  stu_idNone of the expressions except stu_id vary from row to row, so none of them affect the sorting.
    (b) If there exist a 5th column in the table student and we specify it in the select statement's select list (5 column names) then why its not considering it as 5 and sorting the data according that?As Solomon said, only number literals are taken to mean a column. 5 is a number literal, so
    ORDER BY  5means "sort by the 5th column", but 2 + 3 is not a literal (it's an expression that happens to include a couple of literals), so
    ORDER BY  2 + 3does not refer to the 5th colunmn.
    (c) Is it true that, any expression we write is getting evaluated to NULL? Then is it that ORDER BY NULL evaluates to no ordering and the parser searches for next column-name or position (if specified) ?No, when you way "ORDER BY x", the rows with lower values of x come first, followed by rows with higher values of x. Rows with the same value of x will be together, in no particular order with respect to each other (unless there is a tie-breaker expression later in the ORDER BY clause.
    That's exactly what happens when you say "ORDER BY NULL". NULL has the same value (actually, the same lack of any value) on all rows, so all the rows have the same value of x, and they will appear in no particular order.
    (d) if neither then, what's the reason of the ignorance?

  • How to run report on command line with user parameter?

    Hi,
    How do I run oracle report on command line (batch) with pre-set User Parameter values ? e.g. :P_1 ='SYSDATE' , :P_2 = 'DEPT_NO'
    Thanks

    Hello,
    If you are using rwrun :
    rwrun report=myreport destype=file desname=c:\temp\myreport.pdf desformat=pdf P_1='SYSDATE' P_2='DEPT_NO' userid=scott/tiger@dbalias
    If you are using rwclient , just add server=<reports server name> :
    rwclient server=myrepsevrername report=+myreport+ destype=file desname=c:\temp\myreport.pdf desformat=pdf P_1='SYSDATE' P_2='DEPT_NO' userid=scott/tiger@dbalias
    Regards

  • Order by clause with Named Query

    hi
    i have to give order by clause in Named Query
    how we have to specify is can any body help
    thanks
    Harish

    Assuming an Entity called Handset:
    select h from Handset h order by h.description

  • Using decode in where clause with user defined function

    Hi,
    I have a below query which is failing as the function in the decode taking all cust_account_id as input parameter instead of the one which satisfies the condition in the inner query.So please provide a solution how can i pass only the selected one.
    SELECT hca.cust_account_id
    FROM hz_cust_accounts hca
    WHERE hca.org_id=FND_PROFILE.value('ORG_ID')
    AND hca.cust_account_id = (SELECT DISTINCT hcasa.cust_account_id
    FROM hz_cust_acct_sites_all hcasa
    WHERE hcasa.cust_account_id =hca.cust_account_id
    AND hca.org_id = hcasa.org_id)
    AND DECODE (hca.status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(hca.cust_account_id)) IS NOT NULL
    Thanks,
    Abhilash

    I'm having to guess without access to your tables, but I think changing the IN to a join should produce the same results. The JOIN should be evaluated before applying the WHERE clause, so this may resolve your problem.
    SELECT hca.cust_account_id
    FROM   hz_cust_accounts hca
           INNER JOIN hz_cust_acct_sites_all hcasa
           ON    hcasa.cust_account_id = hca.cust_account_id
           AND   hca.org_id = hcasa.org_id
    WHERE  hca.org_id = FND_PROFILE.value('ORG_ID')
    AND    DECODE (hca.status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(hca.cust_account_id)) IS NOT NULLAlternately, you could next part of the query and break the DECODE into the parent so it is evaluated after the inner query. This is likely uglier from a performance standpoint, though:
    SELECT cust_account_id
    FROM
    SELECT hca.cust_account_id, hca.status
    FROM   hz_cust_accounts hca
    WHERE  hca.org_id=FND_PROFILE.value('ORG_ID')
    AND    hca.cust_account_id = (SELECT DISTINCT hcasa.cust_account_id
                                  FROM   hz_cust_acct_sites_all hcasa
                                  WHERE  hcasa.cust_account_id =hca.cust_account_id
                                  AND    hca.org_id = hcasa.org_id)
    WHERE DECODE (status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(cust_account_id)) IS NOT NULL;

  • TestStand Open SQL Statement does not support SQL's ORDER BY clause???

    TestStand 1.0.3
    Windows 2000 SP1
    SQL Server 2000 Personal
    You've got to be kidding me...
    It appears that the built-in TestStand Open SQL Step does NOT support the
    "ORDER BY" clause in the SELECT statement, even though the documentation
    says it does. Is this true?
    I have an Open SQL Statement query:
    "SELECT * FROM [MyTable] WHERE ([Batch ID]=1234)"
    it works fine, returning a correct record count 120 records. If I change
    the Open SQL Statement query simply by adding an ORDER BY clause, such as:
    "SELECT * FROM [MyTable] WHERE ([Batch ID]=1234) ORDER BY [MyField] ASC"
    it returns a record count of zero. I know that "MyField" exists in the
    MyTable table and contains valid data. The
    second query works fine in SQL
    Server Enterprise Manager.
    Am I missing something? Is it true that the TestStand Open SQL Step does
    NOT support the "ORDER BY" clause? If not, what &#$!ing good is it and why
    does the manual state it is supported? Is there any other way using just
    the TestStand steps to order a database recordset on one or more fields?
    Any help would be appreciated.
    Grrrrr....
    Bob Rafuse
    Etec Inc.

    > Bob -
    > The database step types do not do anything special to the SQL command
    > that you give it. The step just passes the command to the ADO
    > provider. I tried a simple query using the step types with the
    > following command,
    >
    > "SELECT UUT_RESULT.* FROM UUT_RESULT WHERE ([UUT_SERIAL_NUMBER] =
    > 12345) ORDER BY [EXECUTION_TIME] ASC"
    >
    > and this return the expected results and the record count parameter
    > was as expected. I tried this on TS 1.0.2 and TS 2.0 with MS Access
    > 2000 and MS SQL Server 7.0. I do not have MS SQL Server 2000 at this
    > time.
    >
    > It would be surprised if the step types are messing something up.
    I've been doing some experimenting over the past couple of days. Simple,
    one-table queries seem to handle the ORDER BY clause fine. Th
    ings seem to
    get messed up when I try multi-table queries with ORDER BY clause with the
    TestStand database steps. I get no errors but the returned record counts
    are always 0 with the ORDER BY and positive without the ORDER BY. The exact
    same queries work fine in Visual Basic/ADO and the SQL Server Query
    Analyzer.
    > Questions:
    > 1. Have you verified whether the data is actually returned even though
    > the record count is zero?
    Hmmm... yes data IS getting returned (at least on the two instances I just
    checked), but the record count is always zero. I was not proceeding with
    processing if the record count was 0.
    Still... I don't know how to loop through the recordset without knowing how
    many records there are an not eventually generate an error by passing EOF.
    Is there another way using the TestStand database steps to determine a) the
    number of records in the recordset or b) when I'm at EOF?
    > 2. Are you using any advanced options on the Opend SQL Statement step
    > type, specifically
    the cursor type set to forward only? Forward only
    > cursors do not allow for record counts.
    Everything on the Advanced tab of the Open SQL Statement step is set to "Use
    Default".
    Bob.

  • 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

Maybe you are looking for

  • Process chain AND process

    Hi, I have a process chain that has two parallel processes of loading DSO and Infocube data. There are two infopackages on one side and two on the other side. The two processes are connected with and AND process at the end and after that there is a d

  • My website won't go online

    I recently started hosting my site using Lion Server. It's my first experience administering a server, so I'm kind of new to this. I added a new server, my site's domain name, to the server list, alongside imac.local, my own computer. I then added We

  • ,pdf files not showing in iTunes podcast

    I have always successfully included .pdf files as accompanying notes for my students' enhanced podcasts. It's always worked very smoothly and well - up to Feb 2009. Since then this function has ceased to be successful. I have had to create a separate

  • Timed Out Error with ADDON

    Hi, When i am running application it works properly. But when i am developing ADDON . ADDON gets installed but <b>while installation it display Timed-Out Error.</b> I tried increasing installation time but it do not work. (i am using B1DE for develop

  • Issues with Watched Folder StartPoint.

    Hi, I'm using LiveCycle ES2 for developing a process with watched folder as optional startpoint. I have followed the instructions given in the LiveDocs and applied the properties to the Watched folder start point service. After deploying this service