Order by AND rownum in a function?

I have a table with articles sorted by an id. In the table is also a date field to tell when the article is written.
I want a query that returns the 20 latest articles, and this is what i have come up with:
SELECT * FROM (
SELECT articleid,writtendate
FROM articles
ORDER BY writtendate desc)
WHERE ROWNUM < 21;
This works alright, BUT I want it in a function! There it doesnt compile!!! Anyone got any suggestions?
I have tried to separate the stuff, like first sorting the records in a view and then selecting the top 20 after that. I could try a cursor and fetching out of that, but havent suceeded with that either.
Bye!

ok, the sql statement works perfectly in an sql editor, but wont compile in a function.
FUNCTION fnc_getLatest20 (
cur IN OUT pkg_cursor.refcur
)RETURN pkg_exception.return_type IS
BEGIN
OPEN cur FOR
SELECT * FROM (
SELECT articleid,writtendate
FROM articles
ORDER BY writtendate DESC)
WHERE ROWNUM < 21;
RETURN pkg_exception.err_none;
END;
The best I have is that either the rows returned in the cursor is all rows, ordered correctly or the top twenty in some other order.
I most be on the wrong track here, there has to be some easier way of doing this...
BTW, thanks for the help so far.

Similar Messages

  • Using order by and rownum in massive tables

    Hi,
    I need to retreive paginated and ordered data from a big table.
    I know some different tips using rownum or the RANK() function and subqueries, these tips work well for small amount of data, but I need to get the data from a table with 200.000 entries (not under my control), and with all those methods is necessary to order first the data and then select your range, so performance is extremely poor.
    Anybody knows a better solution? it doesn't matter if is plain SQL(better) or PL/SQL.
    Thanks in advance

    but I was looking for something like the LIMIT in MySQL or TOP in msSQL where all the sorting is made internally and it's really fast If the data needs sorting, I do not think Oracle would take any longer to do that than the others mentioned, unless the other DBs mentioned, only sort the rows that are actually being returned.
    As for the LIMIT clause, Oracle already has that clause available when FETCHing from a CURSOR:
    SQL> DECLARE
      2      CURSOR emp_cur IS
      3          SELECT * FROM scott.emp;
      4      TYPE emp_rec_table IS TABLE OF emp_cur%ROWTYPE INDEX BY BINARY_INTEGER;
      5      emp_tbl emp_rec_table;
      6  BEGIN
      7      OPEN emp_cur;
      8      LOOP
      9          emp_tbl.DELETE;
    10          FETCH emp_cur BULK COLLECT
    11              INTO emp_tbl LIMIT 5;
    12          EXIT WHEN emp_tbl.COUNT <= 0;
    13          dbms_output.put_line(emp_tbl.COUNT || ' rows fetched using LIMIT clause.');
    14      END LOOP;
    15      CLOSE emp_cur;
    16  END;
    17  /
    5 rows fetched using LIMIT clause.
    5 rows fetched using LIMIT clause.
    4 rows fetched using LIMIT clause.
    PL/SQL procedure successfully completed.
    SQL> disconnect
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.3.0 - Production
    SQL>

  • Question about order by and rownum and subqueries.

    Can you explain why test 4 below results as it results- with returning no rows?
    Identificator "PKG_INTRA_CUSTOMER_SEARCH.NAME" is a package function, which returns value from a variable declared in package body, the function returns value 'e%'.
    Please note that tests 1-3 all returned data, but test 4 didn't. Why? My porpouse is that test 4 would also return data.
    1. Query without "rownum" and with "Order by" returns 2 records:
    select q.*--, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                order by c.NAME, c.ID
                ) q
    10020     Ees Nimi     37810010237     e%
    10040     ewewrwe werwerwer          e%2. Query with "rownum" and without "Order by" returns 2 records:
    select q.*, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                --order by c.NAME, c.ID
                ) q
    10020     Ees Nimi     37810010237     e%
    10040     ewewrwe werwerwer          e%3.Query without "rownum" and with "Order by" returns 2 records:
    select q.*--, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                order by c.NAME, c.ID
                ) q
    10020     Ees Nimi     37810010237     e%
    10040     ewewrwe werwerwer          e% 4. Query with "rownum" and with "Order by" returns 0 records:
    select q.*, rownum
                ,PKG_INTRA_CUSTOMER_SEARCH.NAME
             from
                select c.ID,
                   c.NAME,
                   c.CODE     
                from V_CUSTOMER c  
                where 1=1 and  lower(c.NAME) like PKG_INTRA_CUSTOMER_SEARCH.NAME 
                order by c.NAME, c.ID
                ) q

    Hi,
    please reproduce the question in your test database with script below.
    My general question is that wht Test5 below returns only 1 row, but Test5 returns 3 rows.
    The difference between those two tests is only that one has "order by" clause, the other doesn't have.
    I need the "order by" clause to stay, but seems like it is not allowed.
    CREATE OR REPLACE
    PACKAGE PACKAGE1 AS
    function NAME return varchar2;
    END PACKAGE1;
    CREATE OR REPLACE
    PACKAGE body PACKAGE1 AS
    function NAME return varchar2
    is
    begin
       return 'e%';
    end NAME;
    END PACKAGE1;
    select PACKAGE1.name from dual--e%
    create table Tbl AS
       (SELECT 'e2b' Col1, 'A' Col2, 'AA' Col3 FROM dual
       UNION
       SELECT 'e3b', 'B','BB' FROM dual
    --Test5:  
    select q.*, rownum pos, PACKAGE1.name f         
             from
                select c.col1,
                   c.col2,
                   c.col3     
                from Tbl c  
                where 1=1 and  lower(c.col1) like PACKAGE1.name                      
                order by c.col2, c.col1
                ) q                               
                union all
             select '111' , '111' , '111' , 0 pos, PACKAGE1.name f from dual   --return 1 row
    --Test6
    select q.*, rownum pos, PACKAGE1.name f         
             from
                select c.col1,
                   c.col2,
                   c.col3     
                from Tbl c  
                where 1=1 and  lower(c.col1) like PACKAGE1.name                      
                --order by c.col2, c.col1
                ) q                               
                union all
             select '111' , '111' , '111' , 0 pos, PACKAGE1.name f from dual   --return 3 rowsEdited by: CharlesRoos on Feb 17, 2010 5:30 AM

  • Do you know the link between the sales order item and functional location ?

    How know the functional location if I know de sales order number and item ?
    Wich table or bapi ?
    Tks.

    Hi,
    I think there's all details in my question.
    You answer is right only if I need to know the functional location at AUFNR level.
    Is not my case, I need this information at sales order level.
    Regards,
    Roberto.

  • Table or Function module to get Internal order planning and Cost element pl

    Dear All,
    Table or Function module to get Internal order planning and Cost element planning.
    Internal order planning from T-code KO13.
    Thanks in advance.
    Regards,
    Ravi
    Edited by: Ravi Chandra on Sep 13, 2011 8:08 AM

    BPEJ, BPEG, BPEP

  • Dynamically pass Table name, Column Name and rownum to function

    Hi Guys
    I wanted to pass the table name, column name and rownum to function and get the relevant value for it. Please guide me to achieve this task
    Thanking You
    Regards
    Lakmal

    Thanks,
    Here is my test function
    CREATE or replace FUNCTION GET_COLUMN_VALUE (tab_name VARCHAR2,column_name VARCHAR2) RETURN varchar2 AS
    strsql varchar2 (500);
    ColVal varchar2;
    BEGIN
    strsql:='select '||column_name||' from '||tab_name|| ' Where rownum = 1' ;
    EXECUTE IMMEDIATE strsql into ColVal;
    RETURN ColVal ;
    END;
    Message was edited by:
    Lakmal Marasinghe

  • Trouble with subquery and rownum and ordering

    I'm having trouble making this subquery work. The basic idea is that the web app will show only so many rows of results on the page, but right now I'm just playing around in SQL*Plus. The address book holds mixed case, so in order to sort by name properly I need to use UPPER to ignore case sensitivity. This SQL statement works fine for me:
    select addressbookid from addressbook where addressbookid like '905430931|%' order by upper(addressbookid);I know that if you mention ROWNUM in the WHERE clause, you're referring to the row numbers of the ResultSet that Oracle returns. How do I use both ORDER BY UPPER(ADDRESSBOOKID) and WHERE ROWNUM > 25 AND ROWNUM <= 50? I figured a subquery would do it, but I can't write a correct one that does it! Below are my 2 attempts with the errors, and then I just tried to play with rownum:
    SQL> select addressbookid from addressbook where addressbookid in (select addressbookid from address book where addressbookid like '905430931|%' order by upper(addressbookid));
    select addressbookid from addressbook where addressbookid in (select addressbookid from addressbook
    ERROR at line 1:
    ORA-00907: missing right parenthesis
    SQL> select addressbookid from addressbook where addressbookid in upper(select addressbookid from addressbook where addressbookid like '905430931|%');
    select addressbookid from addressbook where addressbookid in upper(select addressbookid from address
    ERROR at line 1:
    ORA-00936: missing expression
    SQL> select addressbookid from addressbook where addressbookid like '905430931|%' and rownum > 25 and rownum <= 50 order by upper(addressbookid);
    no rows selected
    SQL> select addressbookid from addressbook where addressbookid like '905430931|%' and rownum > 25 and rownum <= 50;
    no rows selectedLike I said, if I can get a working subquery, then I'd like to attach that restriction on the rownum stuff. I'm wondering if it will be a problem trying to get the ordering to happen and then the rownum restriction after that, and all in the same query...
    Btw, we've made all the table and column names in our database uppercase, so that shouldn't matter.

    This is probably the most efficient way ...
    select addressbookid
    from
       select addressbookid,
       rownum rn
       from
          select addressbookid
          from addressbook
          where addressbookid like '905430931|%'
          order by addressbookid
       where rownum <= 50
    where rn > 25

  • Any function module or bapi to get sales order number and invoice number?

    hi all,
    with delivery order number provided, do we have any function module or bapi to get sales order number
    and invoice number?
    thanks.

    Hi,
    Check
    BAPI_SALESORDER_CREATEFROMDAT1
    BAPI_REMUREQSLISTA_CREATEMULT  Agency Business: BAPI Create Invoice Lists from Vendor Billing Documents
    BAPI_REMUREQSLISTB_CREATEMULT  Agency Business: BAPI Create Invoice Lists from Payment Documents
    BAPI_REMUREQSLISTC_CREATEMULT  Agency Business: BAPI Create Invoice Lists from Posting Lists
    BAPI_REMUREQSLIST_CHANGEMULT   Agency Business: Change Invoice List Documents BAPI
    BAPI_REMUREQSLIST_GETLIST      Agency Business: BAPI Determine Detailed Data for Invoice List Documents
    BAPI_REMUREQSLIST_RELEASE      Agency Business: BAPI Release Invoice List Documents to FI
    Edited by: Neenu Jose on Nov 26, 2008 8:53 AM

  • Urjent-Any function module for finding Sales order, Delivery and Invoic

    Hi Experts,
    I am having selection screen like
    Sales order
    Delivery
    Invoice
    Customer
    If i give sales order
             Delivery and Invoice should pull
    If i give delivery
             sales order and Invoice should pull
    If i give Invoice
             sales order and delivery should pull
    If i give customer
               all customer related data should pull
    Do we have any function modules to meet this reqirement?
    If we have please provide function modules.
    Thanks,
    mahe
    Edited by: Rob Burbank on Mar 30, 2009 4:17 PM
    Edited by: mahahe on Mar 31, 2009 9:12 PM

    You can use VBFA table, right? in the FM also, you can find the same logic, like pulling from VBFA table.
    thanq

  • Function module which uses both BAPI's for sales order create and change

    Please name the function module which uses both BAPI's for sales order create and change.
    BAPI_SALESORDER_CREATEFORMDAT2
    BAPI_SALESORDERCHANGE

    Yup.
    you must write a piece of code for this.
    with if else condition.first check if SO is exsist than use second FM to change it else create new SO from first FM.
    logic somethig like this.
    Amit.

  • Order by before rownum

    I am trying to select top 200 records from a really complex select query with order by. But Oracle does top 200 first then order by if I put rownum and order by in one select query, which will give me top 200 records redomly every time. I know a way to work around is doing following
    select * from (select................ order by ......) where rownum<=200
    but this will really take long time since the inner select query is big one. it joins 15 some tables to get all informations. I know in MS SQL, you can have select top(200)...... ordery by ...., it will do order by then top 200. This is making query running really fast.
    Is there other ways to make this run faster in Oracle. Possiblely puting oder by and rownum<200 in one select query?
    Thanks!
    Edited by: user4916474 on Jan 14, 2011 8:24 AM

    Hi,
    See these threads for the information you need to post when you have a performace issue:
    When your query takes too long ...
    HOW TO: Post a SQL statement tuning request - template posting
    If you have a complicated query involving 15 tables, the solution is likely to be complicated, too. For example, you might need to find the top 200 rows before joining all the tables, so just looking for an alternative to ROWNUM probably won't help all by itself, though it may be part of the overall solution.
    One alternative to ROWNUM is the analytic ROW_NUMBER function:
    SELECT  *
    FROM     (
             SELECT  ...
             ,         ROW_NUMBER () OVER (ORDER BY ...)     AS r_num
             FROM    ...
    WHERE     r_num     <= 200
    ;It might not be faster than ROWNUM, but it's probably not slower, either, and it can be adapted to other requirements (e.g., the top 200 for each department).

  • Sales Order Material and its MOQ mass change

    *The issue is related to our Spare parts Ordering process in our company.*
    We have a concept of having 65 days of back orders. Hence there will be
    lot many open orders in the system.
    The Material code will be changed from (for eg) M01 to M02. Hence forth the Material (M01) ordered will
    automatically changed to M02 through Material determination logic. But
    for the 65 days back orders, it is very difficult to change the
    material one by one in sales order. There may be more than 100 orders
    for a material. Even if the MASS change option in Transaction VA05
    doesn't address because of the following reasons;
    1. The changed new material (M02) may have new price with new validity
    periods, whereas the back orders will have old pricing dates. Its
    difficult to change individually in the open orders.
    2. Some materials may have partially delivered.
    Similar to ECM changes, there will be MOQ changes which also needs to
    be changed individually the order quantity in the old Open orders.
    For example,
    Initially the MOQ for a material in 10. Order inflow has happened based
    on this MOQ.
    Now if the MOQ is changed to 20, future orders are addressed. But for
    the 65 day back orders, we need to manually open the individual sales
    order and change the order quantity.
    Hence we require a mass change option for the open orders as below:
    1. For Material Changes (M01 to M02), I will give the list of orders and
    the line items and Qty for M01. The program should reject the existing
    line item for M01. An additional line item should be created with M02.
    Also the pricing date should be changed.
    2. For MOQ changes, I will give the list of orders and the line items
    and Qty. The program should reject the existing line item for those
    materials. An additional line item should be created with new Qty.
    If the material is partially delivered, the the existing qty should be
    updated to the extent it is delivered and the remaining qty should be
    updated with new material or New MOQ.

    You can use BAPI_SALESORDER_CHANGE.
    1. Get the SO detail using BAPISDORDER_GETDETAILEDLIST.
    2. MODIFY the ORDER_CFGS_* internal tables and  update.
            CALL FUNCTION 'BAPISDORDER_GETDETAILEDLIST'
              TABLES
                order_cfgs_value   = gt_char
                order_cfgs_ref       = gt_char_ref
                order_cfgs_inst      = gt_char_ins.
            MODIFY gt_cfgs_*.
            CALL FUNCTION 'BAPI_SALESORDER_CHANGE'
             TABLES
                order_cfgs_value   = gt_char
                order_cfgs_ref       = gt_char_ref
                order_cfgs_inst      = gt_char_ins.
    Refer SAP note 549563.

  • [b]how to use EJB QL for LIKE and ROWNUM[/b]

    Hi,
    i am using CMP EJB with OC4J server
    i face two problems in it when i make any query like
    select object(o) from Partymas o where o.stationCode like '?1' and o.rownum &gt;='?2' and o.rownum &lt;='?3' order by party_name
    then it shows error on rownum so i cant understand how to solve it
    second is when i use LIKE statment in EJB QL like this:-
    select object(o) from Partymas o where o.pinCode like '%?%'
    then it shows error so can any one help me
    thanks
    warm regards
    vikassheelgupta

    <ejb-ql>select object(o) from Partymas o where o.stationCode like '?1' and
    rownum >='?2' and rownum <='?3' order by party_name</ejb-ql>Try this:
    rownum >= ?2 and rownum <= ?3
    <ejb-ql>select object(o) from Partymas o where o.partyName like '%?%'</ejb-ql>Try this:
    like ?1

  • Automatic Service Order creation and OBD line item creation - Repair Order

    Hi ALL,
    I tried to run the Repair process based on the help document of SAP:
    Configs Followed:
    1) In Material master MRP3 view, strategy group is assigned as 84 (service orders). By default this str.grp is linked with Requirement type SERA and Requirement class 203.
    2 ) Requirement class is assigned with appropriate Service order type.
    SPRO>Sales and Distribution>Basic Functions>Availability Check and Transfer of Requirements>Transfer of Requirements-->Define Requirements Classes (OVZG)
    Actual Assignment:
    Reqt. Class Service Order Type
    039 SM01
    203 SM01
    3) Task list is assigned to your Service material - Service product - OISD
    Actual Assignment:
    Service Pdt Work Centre Plant B Area Gen TL Group Counter Task List Type
    R-1001 PC-SERV 1200 8000 62 1 A
    4) Check the Requirement class setting indicator for configuration (cnfg)
    Actual Assignment:
    = mandatory
    5) SPRO>Sales and Distribution>Basic Functions>Availability Check and Transfer of Requirements>Transfer of Requirements-->Define Requirements Classes --> Determination Of Requirement Types Using Transaction
    Actual Assignment:
    Item Category Reqt class Reqt. Type
    IRRS 039 SE
    IRRE 203 SERP
    IRRP 203 SERP
    IRAL 040 KE
    6) Sales and Distribution>Sales>Sales Document Item-->Assign Item Categories for determining the item category based on usage
    Actual Assignment:
    Sal. Doc. Type Item Cat. Group Item Usage H. L . Item Cat Item Category
    RAS NORM IRRS
    RAS NORM R101 IRRS IRRE
    RAS NORM R102 IRRS IRRP
    RAS NORM R103 IRRS IRAL
    Errors Faced:
    1. Service Order is not getting created automatically.
    Error in SAP - IDES :"A service order has not been found for action 'Repairs'"
    2. Also im not getting the automatic creation of the 4th line item(Item Category - IRAL) in the repair order, which in turn stops me from creating the Outbound delivery.
    Please HELP !
    Regards

    Hi PeteA,
    Sorry, here it is...
    Let me explain the process that has been followed:
    1) Initially to start with Service Notification was created with IW51 T-code.
        In that, Sold to party and material # were entered. Then from there directly i go for Create Repair Order from the Action Box.
        Order type for repair order - RAS, and when i save both Service Notification and the Repair gets saved.
        Now, in the repair order, two line items were getting created automatically and the requirement Types for those line items are:
        Line Item I : SE
        Line Item II: SERP
    2) After that i take the material in with the help of t-code VRRE.
    3) Then, i do the acceptance of the stock ( Technical Check) with t-code QA11.
        Once i do that, i get the Third line item in the Repair Order and the requirement Type for that line item is:
        Line Item III: SERP
    Now my query is, Once i do the QA11 transaction i need to get a Service Order automatically but thats not happening.
    Also if i create a Service Order manually, and do the repair and do the technically completion of the service order, then i need to get a third line item (IRAL) in the repair order automatically and thats also not happening.
    Regards

  • 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

Maybe you are looking for

  • Help on creating a ServerSession in Eclipse with XML file

    Hi, I am using Toplink in Eclipse with Tomcat/Apache (or at least trying to :) I am trying to make the following code work: Project myProject = XMLProjectReader.read("myproject.xml"); Server serverSession = myProject.createServerSession(); but I get

  • URGENT!!! Need help with drawImage program.

    Hi..., This is my first time dealing with drawImage. This is my program: public void init () img=getImage (getDocumentBase (), "knight.gif"); do row=Integer.parseInt (JOptionPane.showInputDialog ("Enter starting row: ")); while (row<1 || row>8); do c

  • Creating acrobat 9.1 PDF mailmerge documents from Word 2007

    When I try to use the mail merge PDF feature of Acrobat 9.1, with a Word 2007 document I get the following error message: PDF maker cannot locate the Adobe PDF printer's printer driver.  Please reinstall Adobe Acrobat 9.1 I am running Windows Vista.

  • Work Flow Setting for Vendor Payment Release using TCode F-53

    Hi Experts, We want to 3 level payment release strategy for Vendor using Workflow in F-53 Regards, Gaurav.

  • IPhoto has become "unreadable"!!!!

    Hi all, My iPhoto has suddenly stopped "working", how do I get it back to normal and keep all my photos? I have followed the instructions given by Apple but it hasn't worked. It says i can try restoring my library from a backup and I don't know how t