Addrow() and #rownum#

Hello every one. I have searched this forum extensively for a solution but haven't been able to find one.
Apex: 4.1.00.23
DB: 11.1.07
In a tabular fomr, I am using APEX_ITEM.TEXT in the following way:
APEX_ITEM.TEXT(10,email,40,null,'STYLE="background:#d3d3d3;" readonly="readonly" onclick="window.open(''f?p=106:10:&APP_SESSION.::::'',''Search_User'',''width=700,height=350'')"','f10_'||'#ROWNUM#')
There is an add button that calls JavaScript addrow() function to add rows to the form. When a row is added, the tabular form built in text boxes get the next #ROWNUM# for the id. For example f01_010, f02_010. The custom
APEX_ITEM.TEXT mentioned above gets 0 for the rownum so the id is f10_0. So my question is how can I get the next value of the rownum to populate the id? I understand that #ROWNUM# comes from the database and since the page has not been submitted, the new row does not have a value. Is there a way to get current maximum rownum and may be add 1 to it to get the next value for the id?
Thanks,
Usman

Thanks for the reply. I took your suggestion and decided to do it without custom tabular form. The behavior I wanted was that when a user clicks on the text box it opens a pop up window from which the user can select the list of values. This pop up window displays a report with various custom information (hence I could not use built in pop up LOV). I ended up doing this with dynamic action.
Element Attributes of the tabular form column: class="email" STYLE="background:#d3d3d3;" readonly="readonly"
Dynamic Action:
Event= Click
JQuery Selector = .email
Action= The following java script code:
var id=this.triggeringElement.id;
var name=this.triggeringElement.value;
window.open('f?p=106:10:&APP_SESSION.::::P10_SET_ITEM,P10_USER,P10_SUBMIT_FLAG:'+id+','+name+',N','Search_User','width=700,height=350');Thanks for your help.
Usman

Similar Messages

  • [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 >='?2' and o.rownum <='?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

  • What are ROWID and ROWNUM? Are they stored in database and where?

    Hi All,
    can anybody please answer this question
    What are ROWID and ROWNUM? Are they stored in database and where?
    Thanks,
    Srini

    ROWID can be thought of as a pointer to the physical location (on disk) of the (table) row.
    From a ROWID value, Oracle can extract the file, block-within-that-file and offset-of-the-row-within-that-block. Using these, Oracle can directly access a disk block to retrieve a row.
    ROWNUM is a just sequence number of a row within a result set of a query.
    As said by other repliers, both are not stored. They are 'constructed' when you reference them inside a query.

  • 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

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

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

  • Using union all and rownum

    Hello again.
    Another question.
    Can I query with union all and stop it when I get N rows.
    For example:
    select 1 from dba_segments
    union all
    select 2 from dba_segments where
    union all
    select 3 from dba_segments where;
    and get the 100 first rows without doing the whole query:(not like that-->)
    select * from (
    select 1 from dba_segments
    union all
    select 2 from dba_segments where
    union all
    select 3 from dba_segments where)
    where rownum < 100);
    I want the query will stop when there are 100 rows in the result set.
    thank you!

    You already posted your own answer. It just seems you don't want to use it.
    ROWNUM is NOT assigned until the rows are selected to be returned. So you need to wrap the three inner queries into a query that uses ROWNUM.

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

  • 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

  • Order by multiple columns and ROWNUM

    Hi -
    I am trying to use rownum in colloboration with order by multiple columns but I guess I am doing something wrong
    and I am always getting a single row per emp_id rather than getting single row for a particular emp_id,role_id,inst_id,exp_date.
    Below is the table ddl and data insertion script.
    ====
    create table tab_details
    (emp_id varchar2(50),
    role_id integer,
    inst_id integer,
    exp_date date,
    chk_ind char(1),
    trans_type char(1),
    trans_date date);
    insert all
    into tab_details values ('JBRAMS',12,4556,'07/15/2011','Y','U','05/21/2011')
    into tab_details values ('JBRAMS',12,4556,'07/15/2011','N','U','05/22/2011')
    into tab_details values ('JBRAMS',12,4556,'07/15/2011','N','D','05/23/2011')
    into tab_details values ('JBRAMS',12,4556,'07/15/2011','N','U','05/24/2011')
    into tab_details values ('KCASOT',98,9001,'08/03/2011','Y','U','04/11/2011')
    into tab_details values ('KCASOT',98,9001,'08/03/2011','N','U','04/12/2011')
    into tab_details values ('KCASOT',98,9001,'08/03/2011','N','U','04/13/2011')
    into tab_details values ('JBRAMS',43,7875,'06/28/2011','Y','U','03/19/2011')
    into tab_details values ('JBRAMS',43,7875,'06/28/2011','N','U','03/20/2011')
    into tab_details values ('BHAYEN',28,4098,'07/01/2011','Y','U','02/13/2011')
    into tab_details values ('BHAYEN',28,4098,'07/01/2011','N','U','02/14/2011')
    into tab_details values ('BHAYEN',28,4098,'07/01/2011','N','D','02/15/2011')
    into tab_details values ('BHAYEN',28,4098,'07/01/2011','Y','U','02/16/2011')
    into tab_details values ('BHAYEN',28,4098,'07/01/2011','N','U','02/17/2011')
    into tab_details values ('BHAYEN',28,4098,'07/01/2011','N','U','02/18/2011')
    select * from dual;
    commit;
    ====
    So for the first four rows inserted above, I need only following row:
    'JBRAMS',12,4556,'07/15/2011','N','U','05/22/2011'
    Basically, I need only the rows with chk_ind='N' and trans_type<>'D' and if there is a row with
    chk_ind='N' and trans_type='U' after trans_type='D" for a emp_id,role_id,inst_id,exp_date then it should be ignored.
    Following are the only rows I am looking for:
    'JBRAMS',12,4556,'07/15/2011','N','U','05/22/2011'
    'KCASOT',98,9001,'08/03/2011','N','U','04/12/2011'
    'JBRAMS',43,7875,'06/28/2011','N','U','03/20/2011'
    'BHAYEN',28,4098,'07/01/2011','N','U','02/14/2011'
    'BHAYEN',28,4098,'07/01/2011','N','U','02/17/2011'
    Please share your thought over this.
    Thanks,
    -Seenu

    Hi, Seenu,
    Seenu001 wrote:
    Hi -
    I am trying to use rownum in colloboration with order by multiple columns but I guess I am doing something wrong
    and I am always getting a single row per emp_id rather than getting single row for a particular emp_id,role_id,inst_id,exp_date.Thanks for posting the CREATE TABLE and INSERT statements. It would help if you posted your query, too: even if it's not qute right, it could help to understand the problem, and modifying it might be more efficient than writing a completely new query.
    What are the multiple columns you are sorting on? Why isn't trans_date enough?
    Here's one way:
    WITH     got_okay     AS
         SELECT     t.*
         ,     CASE
                   WHEN  LAG (chk_ind)    OVER ( PARTITION BY  emp_id
                                     ,           role_id
                                     ,           inst_id
                                     ,           exp_date
                                     ORDER BY      trans_date
                                      ) = 'N'
                   AND   LAG (trans_type) OVER ( PARTITION BY  emp_id
                                     ,           role_id
                                     ,           inst_id
                                     ,           exp_date
                                     ORDER BY      trans_date
                                      ) IN ('D', 'U')
                   THEN  0
                   ELSE  1
              END          AS okay
         FROM     tab_details     t
    SELECT       *     -- or list all columns except d_cnt
    FROM       got_okay
    WHERE       chk_ind     = 'N'
    AND       trans_type     != 'D'
    AND       (     trans_type     != 'U'
           OR     okay          = 1
    ;

  • ROWID and rownum

    Hello World!
    I have a large table I want to trancate to 10 rows.
    I use the staement:
    delete from aa where rowid in (select rowid from (select rowid from aa) where rownum > 11);
    This result in 0 records deleted due to select rowid from (select rowid from aa) where rownum > 11; results in 0 records selected.
    At the same time select rowid from (select rowid from aa) where rownum < 17;
    produce correct result.
    Any suugestions?
    TIA

    You should NOT use ";" symbol at the end of sql statement you call using
    EXECUTE IMMEDIATE.
    Change your function (and use binding variable whereever it's possible):
    SQL> CREATE or replace function delete_rows (
      2  table_name IN VARCHAR2,
      3  nrows IN NUMBER DEFAULT NULL) return NUMBER IS
      4  l_sql VARCHAR2(32767);
      5  BEGIN
      6 
      7  IF TABLE_NAME IS NOT NULL and nrows IS NOT NULL THEN
      8   l_sql := 'delete from '||table_name ||
      9   ' where rowid not in (select rowid from (select rowid from '|
    10   table_name||') where rownum < :1)';
    11   EXECUTE IMMEDIATE l_sql using nrows;
    12  END IF;
    13 
    14  commit;
    15 
    16  return null;
    17 
    18  EXCEPTION
    19  WHEN OTHERS THEN
    20   DBMS_OUTPUT.PUT_LINE(SQLERRM);
    21   return null;
    22  END delete_rows;
    23  /
    Function created.
    SQL> select delete_rows('emp',11) from dual;
    DELETE_ROWS('EMP',11)
    ORA-14551: cannot perform a DML operation inside a query
    SQL> begin
      2   dbms_output.put_line(delete_rows('emp',11));
      3  end;
      4  /
    PL/SQL procedure successfully completed.Rgds.

  • Order By clause problem with ENAME and Rownum?

    From Scott/Tiger user I run this query from EMP table.
    select rownum,EMPNO,ENAME,JOB from emp
    order by Ename;
    Output is like this
    ROWNUM EMPNO ENAME JOB
    11      11     ADAMS CLERK
    2      2      ALLEN SALESMAN
    6      6      BLAKE MANAGER
    7      7      CLARK MANAGER
    13      13     FORD ANALYST
    12      12     JAMES CLERK
    4      4      JONES MANAGER
    9      9      KING PRESIDENT
    5      5      MARTIN SALESMAN
    14      14      MILLER CLERK
    8      8      SCOTT ANALYST
    1      1      SMITH CLERK
    10      10      TURNER SALESMAN
    3      3      WARD SALESMAN
    Here Rownum order is disturb, I want it also in Ascending order with ENAME.
    Please send the solution of this problem
    Best Regards,
    Shahzad

    select row_number() over (order by ename) as rn, empno, ename, job from emp
      order by ename;

  • Problem in AddRow button and Matrix

    Hello everybody...
    Can anybody tell me...in my UDO Form AddRow button, matrix is not working...dont understand why???
    But Add and Cancel buttons are working fine...there is no problem in code still I am not able to update values using Matrix...
    See the code below...
    Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
            Try
                ' Events of the Blanket Agreement form
                If (FormUID = "FBLK") Then
                    If (pVal.Before_Action = False) Then
                        ' Click on Add Row
                        If (pVal.ItemUID = "AddRow") And (pVal.EventType = SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED) Then
                            Dim f As SAPbouiCOM.Form
                            Dim oMatrix As SAPbouiCOM.Matrix
                            f = SBO_Application.Forms.Item(FormUID)
                            oMatrix = f.Items.Item("mat").Specific
                            f.DataSources.DBDataSources.Item(1).Clear()
                            oMatrix.AddRow(1)
                        End If
                        End If
                        End If
      Catch ex As Exception
                    MessageBox.Show(u2018not workingu2019)
      End Try
        End Sub
    Please tell me where I am wrong...
    Thanks in advance

    Hi Satish,
    Thanks for the reply and yes I am using SetFilters and Item Uid is also correct, i have checked....
    See Code below for SetFilters()
    Private Sub SetFilters()
            '// Create a new EventFilters object
            oFilters = New SAPbouiCOM.EventFilters
            '// add an event type to the container
            '// this method returns an EventFilter object
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_VALIDATE)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_LOST_FOCUS)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_KEY_DOWN)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_MENU_CLICK)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_CLICK)
            '// assign the form type on which the event would be processed
            oFilter.AddEx("149") 'Quotation Form
            oFilter.AddEx("139") 'Orders Form
            oFilter.AddEx("133") 'Invoice Form
            oFilter.AddEx("169") 'Main Menu
            SBO_Application.SetFilter(oFilters)
        End Sub
    Now tell me where I am wrong...

  • Select and update rownum sender jdbc

    Dear all
    i am using PI 7.31 sender jdbc adapter.
    table(TB_AA)  has 10000 row with pi_stat = 'R'   and then  sender jdbc adapter tried  10 row  in using rownum  every  120 second and update same rownum
    but  result of select query and udpate query  were different.  not same record update for selecting data.
    co_cd,  memid  is PK.
    select co_cd , mem_id,  reg_n  FROM TB_AA  where PI_STAT = 'R' AND rownum <= 10
    update  TB_AA  set  PI_STAT = 'S', where  PI_STAT = 'R' and rownum <= 10
    query is wrong?  ,  what is correct update query with several PK ?

    Hi Arten Solohin.
    co_cd,  memid  is Primary Key.
    select co_cd , mem_id,  reg_n  FROM TB_AA  where PI_STAT = 'R' AND rownum <= 10
    update  TB_AA  set  PI_STAT = 'S', where  PI_STAT = 'R' and rownum <= 10
    could you make your query with above my query ?  because i am confusing ORDER BY <your unique id_field>   AND LINE_ID ....
    will be highly appreciated  in advance
    thanks you very much.

Maybe you are looking for