Cursor ORDER BY Clause Changing Row Count In BULK COLLECT ... FOR LOOP?

Oracle 10g Enterprise Edition Release 10.2.0.4.0 running on Windows Server 2003
Oracle Client 10.2.0.2.0 running on Windows 2000
I have some PL/SQL code that's intended to update a column in a table based on a lookup from another table. I started out by testing it with the UPDATE statement commented out, just visually inspecting the DBMS_OUTPUT results to see if it was sane. During this testing I added/changed the cursor ORDER BY clause to make it easier to read the output, and saw some strange results. I've run the code 3 times with:
1. no ORDER BY clause
2. ORDER BY with two columns (neither indexed)
3. ORDER BY with one column (not indexed)
and get three different "rows updated" counts - in fact, when using the ORDER BY clauses it appears that the code is processing more rows than without either ORDER BY clause. I'm wondering why adding / changing an ORDER BY <non-indexed column> clause in a cursor would affect the row count?
The code structure is:
TYPE my_Table_t IS TABLE OF table1%ROWTYPE ;
my_Table my_Table_t ;
CURSOR my_Cursor IS SELECT * FROM table1 ; -- initial case - no ORDER BY clause
-- ORDER BY table1.column1, table1.column2 ; -- neither column indexed
-- ORDER BY table1.column2 ; -- column not indexed
my_Loop_Count NUMBER := 0 ;
OPEN my_Cursor ;
LOOP
FETCH my_Cursor BULK COLLECT INTO my_Table LIMIT 100 ;
EXIT WHEN my_Table.COUNT = 0 ;
FOR i IN 1..my_Table.COUNT LOOP
my_New_Value := <call a pkg.funct to retrieve expected value from another table> ;
EXIT WHEN my_New_Value IS NULL ;
EXIT WHEN my_New_Value = <an undesirable value> ;
IF my_New_Value <> my_Table(i).column3 THEN
DBMS_OUTPUT.PUT_LINE( 'Changing ' || my_Table(i).column3 || ' to ' || my_New_Value ) ;
UPDATE table1 SET column3 = my_New_Value WHERE column_pk = my_Table(i).column_pk ;
my_Loop_Count := my_Loop_Count + 1 ;
END IF ;
END LOOP ;
COMMIT ;
END LOOP ;
CLOSE my_Cursor ;
DBMS_OUTPUT.PUT_LINE( 'Processed ' || my_Loop_Count || ' Rows ' ) ;

Hello (and welcome),
Your handling the inner cursor exit control is suspect, which will result in (seemingly) erratic record counts.
Instead of:
LOOP
FETCH my_Cursor BULK COLLECT INTO my_Table LIMIT 100 ;
EXIT WHEN my_Table.COUNT = 0 ;
FOR i IN 1..my_Table.COUNT LOOP
my_New_Value := <call a pkg.funct to retrieve expected value from another table> ;
EXIT WHEN my_New_Value IS NULL ;
EXIT WHEN my_New_Value = <an undesirable value> ;
IF my_New_Value my_Table(i).column3 THEN
DBMS_OUTPUT.PUT_LINE( 'Changing ' || my_Table(i).column3 || ' to ' || my_New_Value ) ;
UPDATE table1 SET column3 = my_New_Value WHERE column_pk = my_Table(i).column_pk ;
my_Loop_Count := my_Loop_Count + 1 ;
END IF ;
END LOOP ;
COMMIT ;
END LOOP ;Try this:
LOOP
FETCH my_Cursor BULK COLLECT INTO my_Table LIMIT 100 ;
FOR i IN 1..my_Table.COUNT LOOP
my_New_Value := <call a pkg.funct to retrieve expected value from another table> ;
EXIT WHEN my_New_Value IS NULL ;
EXIT WHEN my_New_Value = <an undesirable value> ;
IF my_New_Value my_Table(i).column3 THEN
DBMS_OUTPUT.PUT_LINE( 'Changing ' || my_Table(i).column3 || ' to ' || my_New_Value ) ;
UPDATE table1 SET column3 = my_New_Value WHERE column_pk = my_Table(i).column_pk ;
my_Loop_Count := my_Loop_Count + 1 ;
END IF ;
EXIT WHEN my_Cursor%NOTFOUND;
END LOOP ;
END LOOP ;
COMMIT ;Which also takes the COMMIT outside of the LOOP -- try to never have a COMMIT inside of any LOOP.
Additionally, not too sure about these:
my_New_Value := <call a pkg.funct to retrieve expected value from another table> ;
EXIT WHEN my_New_Value IS NULL ;
EXIT WHEN my_New_Value = <an undesirable value> ;Any one of those EXITs will bypass your my_Loop_Count increment.
Edited by: SeánMacGC on Jul 9, 2009 8:37 AM
Had the cursor not found in the wrong place, now corrected.

Similar Messages

  • Changing iteration count of a while/for loop

    Hi,
    By default the for/ while loop iteration count will start from '0'. I want my loop to start with any other value say '10'.
    Is it possible to change the value of loop count , so that it counts from '10' (in this case).

    Thnx a lot
    Bt I already know this method. I was looking for some other method if available.
    And we can also do the same using shift registers.
    Regards,
    Runjhun.

  • How to get count from new enhanced for loop

    Is there a better way to determine the count when new enhanced for loop is used as follows:
    String[] test = new String[]{"1","2","3"};
    int count = 0;
    for(String i: test)
    count++;
    system.out.println("count: "+count);
    }

    There are cases where I need to use the count inside
    the for loop. I can keep track of the count by using
    the increment. But, then I would rather using the old
    for loop. Go ahead and use it. Are you under the assumption that the old form should be avoided?
    There is no saving in term of efficiency and readability.If there is any added efficiency in the "for each" form of the loop, it is on the micro level, and you would never notice it.
    As far as readability, look at some of the crazy solutions you've been given to avoid the general for loop, then reconsider which is more readable.

  • Unable to get the row count of supplier site for each supplier

    Hi,
    In the sourcing module, suppliers page is having an advanced table in which there is a field 'supplier' and another filed 'supplier sites' (supplier field is of type picklist).Now, how can i get the count of 'supplier sites' for each supplier???

    Hi sumit,
    Thanks for the reply, can u please help in writing the code to loop through the VO...
    I was trying to get the first row and then finding the count of supplier sites, but in each iteration of for loop(for each row) i am getting the same count value for each and every row...
    Code :
    int j=vo.getrowcount();//count of no. of rows
    for (int i=0;i<j;i++)
    row=(xxVORowImpl)rowsetiterator.getRowAtRangeIndex(1);
    int a=am.getSupplierSitesVO.getRowCount();//this is the view object in the pick list
    oapagecontext.writeDiagnostics(this,"value of   a is :"+a,1);
    this code is giving row count of last row of supplier.
    How to get the count for each and every row of supplier sites ?
    Thanks.

  • What is the point in having multiple columns in ORDER BY clause?

    DB version:10gR2
    When using ORDER BY clause, the rows are always sorted according to the first column in the ORDER BY clause. So, what is point in having multiple columns in the ORDER BY clause(i always see this in production codes)?
    For the below SQLs' from SCOTT schema, the result sets are always ordered according the first column ename. When i added job asc and job desc, the result set doesn't change.
    SQL> select * from emp order by ename;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    20
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
    14 rows selected.
    SQL> select * from emp order by ename, job;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    20
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
    14 rows selected.
    SQL>  select * from emp order by ename, job desc;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    20
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
    14 rows selected.

    Because there is only one employee with the name SCOTT,FORD ...etc in the emp table and your first column in the order by list is ename
    you spot the difference now
    SQL> select * from emp order by job;
         EMPNO ENAME      JOB              MGR HIREDATE                  SAL       COMM     DEPTNO
          7788 SCOTT      ANALYST         7566 19-APR-87 00:00:00       3000                    20
          7902 FORD       ANALYST         7566 03-DEC-81 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-82 00:00:00       1300                    10
          7900 JAMES      CLERK           7698 03-DEC-81 00:00:00        950                    30
          7369 SMITH      CLERK           7902 17-DEC-80 00:00:00        800                    20
          7876 ADAMS      CLERK           7788 23-MAY-87 00:00:00       1100                    20
          7698 BLAKE      MANAGER         7839 01-MAY-81 00:00:00       2850                    30
          7566 JONES      MANAGER         7839 02-APR-81 00:00:00       2975                    20
          7782 CLARK      MANAGER         7839 09-JUN-81 00:00:00       2450                    10
          7839 KING       PRESIDENT            17-NOV-81 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81 00:00:00       1500          0         30
          7654 MARTIN     SALESMAN        7698 28-SEP-81 00:00:00       1250       1400         30
          7521 WARD       SALESMAN        7698 22-FEB-81 00:00:00       1250        500         30
          7499 ALLEN      SALESMAN        7698 20-FEB-81 00:00:00       1600        300         30
    14 rows selected.
    Elapsed: 00:00:00.00
    SQL> select * from emp order by job, deptno asc;
         EMPNO ENAME      JOB              MGR HIREDATE                  SAL       COMM     DEPTNO
          7902 FORD       ANALYST         7566 03-DEC-81 00:00:00       3000                    20
          7788 SCOTT      ANALYST         7566 19-APR-87 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-82 00:00:00       1300                    10
          7369 SMITH      CLERK           7902 17-DEC-80 00:00:00        800                    20
          7876 ADAMS      CLERK           7788 23-MAY-87 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-81 00:00:00        950                    30
          7782 CLARK      MANAGER         7839 09-JUN-81 00:00:00       2450                    10
          7566 JONES      MANAGER         7839 02-APR-81 00:00:00       2975                    20
          7698 BLAKE      MANAGER         7839 01-MAY-81 00:00:00       2850                    30
          7839 KING       PRESIDENT            17-NOV-81 00:00:00       5000                    10
          7654 MARTIN     SALESMAN        7698 28-SEP-81 00:00:00       1250       1400         30
          7844 TURNER     SALESMAN        7698 08-SEP-81 00:00:00       1500          0         30
          7521 WARD       SALESMAN        7698 22-FEB-81 00:00:00       1250        500         30
          7499 ALLEN      SALESMAN        7698 20-FEB-81 00:00:00       1600        300         30
    14 rows selected.
    Elapsed: 00:00:00.01
    SQL> select * from emp order by job,deptno desc;
         EMPNO ENAME      JOB              MGR HIREDATE                  SAL       COMM     DEPTNO
          7902 FORD       ANALYST         7566 03-DEC-81 00:00:00       3000                    20
          7788 SCOTT      ANALYST         7566 19-APR-87 00:00:00       3000                    20
          7900 JAMES      CLERK           7698 03-DEC-81 00:00:00        950                    30
          7369 SMITH      CLERK           7902 17-DEC-80 00:00:00        800                    20
          7876 ADAMS      CLERK           7788 23-MAY-87 00:00:00       1100                    20
          7934 MILLER     CLERK           7782 23-JAN-82 00:00:00       1300                    10
          7698 BLAKE      MANAGER         7839 01-MAY-81 00:00:00       2850                    30
          7566 JONES      MANAGER         7839 02-APR-81 00:00:00       2975                    20
          7782 CLARK      MANAGER         7839 09-JUN-81 00:00:00       2450                    10
          7839 KING       PRESIDENT            17-NOV-81 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81 00:00:00       1500          0         30
          7654 MARTIN     SALESMAN        7698 28-SEP-81 00:00:00       1250       1400         30
          7521 WARD       SALESMAN        7698 22-FEB-81 00:00:00       1250        500         30
          7499 ALLEN      SALESMAN        7698 20-FEB-81 00:00:00       1600        300         30
    14 rows selected.
    Elapsed: 00:00:00.01
    SQL>

  • ROWNUM can use with ORDER BY clause?

    Hi
    Following i have two quires in ROWNUM order for example..
    1:query
    select rownum,empno,ename,deptno from emp
    where rownum <= 14;
    result:
    rownum empno ename deptno
    1 7369 SMITH 20
    2 7499 ALLEN 30
    3 7521 WARD 30
    4 7566 JONES 20
    5 7654 MARTIN 30
    6 7698 BLAKE 30
    7 7782 CLARK 10
    8 7788 SCOTT 20
    9 7839 KING 10
    10 7844 TURNER 30
    11 7876 ADAMS 20
    12 7900 JAMES 30
    13 7902 FORD 20
    14 7934 MILLER 10
    2:Query , add ORDER BY clause it will change the sequence of ROWNUM.
    select rownum,empno,ename,deptno from emp
    where rownum <= 14
    order by deptno;
    result:
    rownum empno ename deptno
    7 7782 CLARK 10
    9 7839 KING 10
    14 7934 MILLER 10
    1 7369 SMITH 20
    11 7876 ADAMS 20
    13 7902 FORD 20
    8 7788 SCOTT 20
    and so on......
    but i want these records from 2 to 5...how i can query this through ROWNUM or any sequence because ORDER BY clause change the order of ROWNUM and i could get this result.
    rownum empno ename deptno
    9 7839 KING 10
    14 7934 MILLER 10
    1 7369 SMITH 20
    11 7876 ADAMS 20
    please send me general query which i can apply on any table.
    advance thanks.

    My guess is that you are looking for a pagination solution. If so, here is a thread on Asktom:
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:127412348064
    So, essentially, you ORDER BY first and then write a wrapper to get your the rownum.
    If you do it this way, You will also use the top-n optimization that Oracle uses.
    Rahul.

  • In Report,order by clause is not working

    Hi All,
    For the report i prepared the query in this one am using the order by clause,i run the query in the sql plus working fine am getting the data based on the order by clause.when i use the same query for the report am getting the data but not in the order(i.e order by clause in not working).
    Please help me how to do this one.
    Thanks in Advance.
    Regards,
    Leelakrishna.G

    Hi Dora,
    Data is coming in the proper sequence,but in the first group data is not coming(In first group data first line only displaying,remaining data is not comming).
    My req is:
    The report is executing based on the creation date(i.e.,from creation date to today).
    In this so many Purchase requisitions will be there for this one different approval in different times will be there.
    For Ex:
    we will take 2 PR number only(for the first one 3 approvals,second one 4 levels of approval).
    1. one supplier 1person raised by 1PR submit
    No Action
    Approve
    2. 2Supplier 2personraised by 2PR Submit
    NO Action
    Forword
    Approve
    with ur suggestion am trying data is gettin fine but first group first line is coming remaining data is not coing.
    EX:
    1. one supplier 1person raised by 1PR submit
    No Action
    Approve
    2PR Submit
    NO Action
    Forword
    Approve
    Note:"2. 2Supplier 2personraised by " this kind of lines data is missing.
    Can you pls check and suggest me how i can do this.
    Thanks in Advance.
    Regards,
    Leelakrishna.G

  • IDoc Configuration for Production Order Creation and Change

    Hi All,
    Please Help me out for IDoc Configuration for Production Order Creation and Change
    I have found the IDoc for Production Order
    Messgae Type : LOIPRO and IDoc type : LOIPRO01
    Actually my requirment is to send the (LOIPRO01 )IDoc from SAP R/3 to XI system ,when ever the Production Order Created and Changed,
    I have done following Configurations:
    1. RFC Destination created for XI system
    2. PORT was created for XI
    3. Partner profile created WE20 and LOIPRO01 IDoc is added in OutBound Perameter.
    I need to know how to do the followning.
    1. How do i configure the outbound Production order idocs when Production Order is created or changed.
    2. in NACE (Output control) which is the Application for Production Order.
    3. How can I set IDoc as output Type for Production Order Creation.
    Thanks in advance
    Dhanabal T

    Hi Michal,
    I know that it is the old thread but still want to get clarified from you out of curiosity.
    Unlike other IDOC, i actiavated change pointers for LOIPRO
    1.message and idoc type is linked
    2.function module , message type , idoc type is linked
    function module used is CLOI_MASTERIDOC_CREATE_LOIPRO
    3.BD64, distribution model is created and distributed
    4. port and partner profile is in place.
    5. IDOC is not getting generated after creating the process order.
    do we need to activate the change documents for the message type in BD52,
    if yes can you please provide the object types for the same.
    or i am missing something else. please guide me in this regards.
    Thanks in advance for your time.
    S.Janagar

  • Popup lov with order by clause

    I created a form manually using the document from the url:
    http://otn.oracle.com/products/database/htmldb/howtos/tabular_form.html#MANUAL
    I used the following query from that document.
    select htmldb_item.hidden(1,empno) empno,
    ename,
    htmldb_item.select_list_from_query(3,job,'select distinct job, job from emp') job,
    htmldb_item.popupkey_from_query(4,mgr,'select ename, empno from emp',10) mgr,
    wwv_flow_item.date_popup(6,null,hiredate) hiredate,
    htmldb_item.text(7,sal,10) sal,
    htmldb_item.text(8,comm,10) comm,
    htmldb_item.select_list_from_query(9,deptno,'select dname, deptno from dept') deptno
    from emp
    This works fine.
    But if I add an order by clause to the query the popup key for mgr column doesn't work.
    select htmldb_item.hidden(1,empno) empno,
    ename,
    htmldb_item.select_list_from_query(3,job,'select distinct job, job from emp') job,
    htmldb_item.popupkey_from_query(4,mgr,'select ename, empno from emp',10) mgr,
    wwv_flow_item.date_popup(6,null,hiredate) hiredate,
    htmldb_item.text(7,sal,10) sal,
    htmldb_item.text(8,comm,10) comm,
    htmldb_item.select_list_from_query(9,deptno,'select dname, deptno from dept') deptno
    from emp
    order by ename
    Thanks
    Chandra.

    Duplicate post, see:
    popup lov in a report is not working if I have an order by caluse
    Sergio

  • Order by clause in cursor problem

    Hello,
    I'm unable to compile package body when i'm using order by clause in cursor subquery in stored procedure.
    Sample code:
    CREATE PACKAGE Announces AS
    TYPE tRefCur IS REF CURSOR;
    PROCEDURE TopAnnounces(
    iiCount IN NUMBER,
    osAnnounces OUT tRefCur,
    oiRetVal OUT NUMBER
    END Announces;
    CREATE PACKAGE BODY Announces AS
    PROCEDURE TopAnnounces(
    iiCount IN NUMBER,
    osAnnounces OUT NUMBER,
    oiRetVal OUT NUMBER
    AS
    BEGIN
    OPEN osAnnounces FOR
    SELECT Id, Name, AnnCount FROM
    SELECT Id, Name, COUNT(CategoryId) AS AnnCount FROM tblAnnounces
    GROUP BY Id, Name
    -- bellow is the line, where the code crash
    ORDER BY AnnCount DESC
    WHERE ROWNUM < iiCount + 1;
    oiRetVal := 0;
    EXCEPTION
    WHEN OTHERS THEN
    oiRetVal := -255;
    END TopAnnounces;
    END Announces;
    If I compile the code above I will get this error:
    PLS-00103: Encoutered the symbol "ORDER" when expecting on of the following:
    After I remark the problematic line, the compilation is successful (but not the result :).
    Is there something I'm doing wrong?
    Thanks for advice
    Vojtech Novacek
    null

    Sorry you can not use order by clause into one temporal table created by subquery.
    Put the order by clause offside of subquery.
    Atte.
    CC.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Vojtech Novacek:
    Hello,
    I'm unable to compile package body when i'm using order by clause in cursor subquery in stored procedure.
    Sample code:
    CREATE PACKAGE Announces AS
    TYPE tRefCur IS REF CURSOR;
    PROCEDURE TopAnnounces(
    iiCount IN NUMBER,
    osAnnounces OUT tRefCur,
    oiRetVal OUT NUMBER
    END Announces;
    CREATE PACKAGE BODY Announces AS
    PROCEDURE TopAnnounces(
    iiCount IN NUMBER,
    osAnnounces OUT NUMBER,
    oiRetVal OUT NUMBER
    AS
    BEGIN
    OPEN osAnnounces FOR
    SELECT Id, Name, AnnCount FROM
    SELECT Id, Name, COUNT(CategoryId) AS AnnCount FROM tblAnnounces
    GROUP BY Id, Name
    -- bellow is the line, where the code crash
    ORDER BY AnnCount DESC
    WHERE ROWNUM < iiCount + 1;
    oiRetVal := 0;
    EXCEPTION
    WHEN OTHERS THEN
    oiRetVal := -255;
    END TopAnnounces;
    END Announces;
    If I compile the code above I will get this error:
    PLS-00103: Encoutered the symbol "ORDER" when expecting on of the following:
    After I remark the problematic line, the compilation is successful (but not the result :).
    Is there something I'm doing wrong?
    Thanks for advice
    Vojtech Novacek<HR></BLOCKQUOTE>
    null

  • 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

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

  • Sql count function in order by clause

    Post Author: krypton
    CA Forum: Data Connectivity and SQL
    Hi Guys
    Can i ask a quick question. I am trying to retrieve data remotely from a SQL Server via crystal reports.
    Within the Database Expert I have entered a SQL query to retrive the number of (call center) support calls raised by our customers:-
    Select `Primary_Company`, COUNT(`Calls`)From  `SPRT_Issue` GROUP BY  `Primary_Company`ORDER BY  COUNT(`Calls`) desc
    The customer's column is called 'Primary Company' and the calls they raise are in the 'Calls' column. the above is a normal sql query.
    However Crystal fails to run the query and generates an error message :-
    Failed to open a rowset. Details: 420: Driver&#93; Expected lexical element not found: <identifier>
    I dont understand why it wont run. In the ORDER BY clause if i replace field 'Calls' by the field 'Primary Company' then it works.
    I think the problem is that it wont accept the count function in the order by clause. which is what i want it to do i.e display the calls in descending order by each customer.
    Could someone tell me if there is a way around it.
    Thanks
    Krypton

    Post Author: krypton
    CA Forum: Data Connectivity and SQL
    Thanks Lynn
    I tried your suggestion. But there is one probelm.
    When i sort the data in descending order using the count(calls) field, the data is returned but the customer's name appears multiple times along with their calls raised.
    E.g, if customer Mark raised multiple calls i.e. 2, 5, and 10 calls, then the report will show
    Mark   2
    Mark  5
    Mark 10
    But is there a way to aggregate all the calls for mark and show them only once:
    such as Mark   17
    Thanks

  • How to change color of rows count dispalyed while debugging ssis packages

    Hello,
    in visual 2013 ssdt version I have row count displayed in white color on pale background: bit.ly/1oWP1Cm
    I'd like to have it in black. I know it should be changeable in Options -> Fonts and Colors, but what option should I change from myriads available?
    Thank you in advance.

    My colleague had the same issue in that we couldn't see the numbers.  We couldn't figure out why we couldn't see the numbers and the design screen was white.  It looked like the numbers were displaying in white over the connections lines.  So
    we changed the color scheme to light and the numbers appeared in black.  WHen we switched the color scheme back to dark, the canvas turned dark and the text was in white.
    So there must be a bug when selecting the color scheme on the first run of Visual Studio 2013 in that it doesn't set the correct canvas color for the SSIS designer.  Luckily toggling the color scheme resolves the issue.
    Christian Jones Software Developer, former Network/Sys Admin

  • How to change the order by clause of a standard VO in OAF

    Hi All,
          I need to change only the order by clause of a standard VO (Which is attached to a messageChoice item).
    Steps followed:
    1)Created a custom VO by extending the standard VO .
    2)VO Impl class files are not generated as seeded VO has no such class files.
    3)Created a substitution
    4)Imported it
    5)When I try access the specific page, getting Sys Admin error without any clue about the error.
    Even I tried to create the custom VO without extending the std VO ,
    Still getting the same error .
    Please provide your suggestions on this.
    Thanks,
    Thavam

    When I set the FND:Diagnostics profile option , I could see what was the exact error . It was SQL Wrapper exception error.
    The VO which is extended , has a dynamic where clause with bind variables. The binding style of the extended VO does not match with seeded VO. It works when the binding style is changed.
    Thanks,
    Thavam

Maybe you are looking for

  • Please help - Copying items to another folder?

    I thought I was pretty good with Automator, but I've never done a folder action before, and I can't seem to get this one to work. I want to have any songs in my "Automatically add to iTunes" folder automatically copy themselves to my mom's "Automatic

  • Transferring old photos from one iPhone to another.

    I've recently upgraded to an iPhone 4S from a 3GS. The 3GS has several problems including not charging and not syncing with my macbook/iTunes. I've backed up on iCloud and when i got the 4S I used that to transfer all my apps and stuff. Anyway, only

  • Flashing/blinking black once awhile on certain website.

    Firefox is flashing/blinking black once awhile on my desktop PC. It only happen on certain websites (such as facebook or my personalized iGoogle). It doesn't happen with Chrome nor IE. Weirdly, it doesn't have the same problem on my laptop... To me,

  • Student grades query of two courses

    Hi everybody I need some advices from experts. I'm trying to make a suitable database for students grades. I'm a bit confused in how to gather all grades of each single student into one from. let say that the students have two courses, where each cou

  • ITunes 11.3.1 crashes within 1 minute of startup on Win7

    Before a couple of weeks ago, I had never had any problems with iTunes and have been using it since 2004.  Currently, I am on a Win7, 32-bit machine.  I started experiencing problems with the 11.3 update.  Typically, within a minute or so of starting