Getting the last inserted row

Hi
I want to get the ID for the last inserted row in another view (not the ones I have in my page), to pass it to a web service. How can I get it?
This returns the first ID in the table: ${bindings.myIterator.RequestId}
This one doesn’t work either: ${bindings.myIterator.currentRow.RequestId}
It shows the following exception
1. JBO-29000: Unexpected exception caught: java.lang.RuntimeException, msg=javax.servlet.jsp.el.ELException: Unable to find a value for "RequestId" in object of class "model.Travel_ViewRowImpl" using operator "."
2. javax.servlet.jsp.el.ELException: Unable to find a value for "RequestId" in object of class "model.Travel_ViewRowImpl" using operator "."
What does ${bindings.myIterator.currentRow.dataProvider} returns?

Hi,
while this is close to the correct syntax it is not complete
${bindings.myIterator.currentRow.RequestId}
this would attempt to call set/get RequestId on the Row class, which doesn't have this property. It has a property getAttribute() but this doesn't allow you to pass an argumentbecause of EL limitations.
Work around: Create an attribute binding for the "RequestId" attribute and call it with
#{bindings.RequestId.inputValue}
ADF always ensures that the currentRow's RequestId is the one obtained from the Attribute binding
Frank

Similar Messages

  • How to get the last inserted record from a table ?

    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

    I'm not sure about 8i features.
    I assume here that you don't have 'Date-Time' stamp columns on the table which is the easiest way to determine the last inserted row in the table.
    If not try the following :-
    select address, piece, SQL_TEXT
    from V$SQLTEXT
    where upper(sql_text) like '%INSERT INTO TABLE_NAME%'
    Substiute the TABLE_NAME with the name of the actual table.
    Have fun.
    Regards,
    Shailender
    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

  • How to get the last inserted Autoincrement value in Java for Pervasive DB

    Hi, I need to get the last inserted auto incremented value after the record is inserted IN JAVA For ex. consider we have 4 columns for the myTable in the PERVASIVE DATABASE V10 autoid - identity column (auto increment column) userID userName pageID insertSqlExpression = insert into myTable (userID , userName, pageID) values( ? ,? ,?); prepareInsert = connection.prepareStatement(insertSqlExpression); prepareInsert .excuteUpdate; After inserting the new record how can I get the autoid value (last inserted value) in the Java. Please help me.
    Thanks in advance. Arthik

    JavaArthikBabu wrote:
    I dont have privileges to write new stored procedures in database.I need to do in the Java side only. In many databases that irrelevant. The same way you would do it in a proc can be done with the correctly conceived statement (singular.)
    For ex – if we insert and then the select record's identity value as a single transaction and would this guarantee that what is returned by the select would not include inserts that another might have made?Please do not take that path unless you are absolutely certain that your database does not support any other way to do it.

  • Getting the last inserted ID

    I found out about a mySQL function that will get the last inserted autoincrement ID and I want to use it in my page. The prepared statement i am using look like this.
    PreparedStatement insertQuestion1 = ConninsertQuestion1.prepareStatement("INSERT INTO Question.question (Topic_ID, Description, Image, Author, Created_Date, Max_Score, Question_Type)  VALUES ('" + questionData.topicID + "', '" + questionData.questionText + "', '" + questionData.questionImage + "', '" +insertQuestion1__username+ "', '" + currentDate + "', " + questionData.maxScore + ", '" + questionData.questionType + "') ");
              insertQuestion1.executeUpdate();there is a function in mysql which looks like this.
    int mysql_insert_id (resource [link_identifier])
    How can i implement this in my code so i will be able to use the integer value later on to insert more records in another table.
    Help would be much appreciated
    Thanks

    If you are using Java1.4 the approach would be to use :
    public boolean execute(String sql,
    int autoGeneratedKeys)
    throws SQLException
    where the autoGeneratedKeys flag is set to Statement.RETURN_GENERATED_KEYS
    After the insert you can call the method :
    public ResultSet getGeneratedKeys()
    throws SQLException
    Which will return a ResultSet containing the mySQL auto-generated keys.
    Check the documentation
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html
    Note that PreparedStatement inherits these methods from Statement

  • Getting the last insert id

    Hi there,
    I'm trying to get the id of the last inserted record. Normally would use $last_id = mysql_insert_id() after the insert statemant but I can't work out how to get this value when I use a ADDT insert transaction.
    Any help much appreciated.
    Cheers

    I´m locking this thread because the OP has additionally added a related question to an existing thread, and a solution to this problem has been provided there too: using  mysql_insert_id() with the ADDT

  • How to get the Interface inserted rows fom ODI Reporsitory

    hi,
    I need select query that will select the Interface inserted rows
    (Count) from ODI repository tables. because I want to maintain these records into another Oracle tables?????

    import datetime
    import sys
    import optparse
    document = []
    def docprint(string):
    document.append('%s' % string)n
    def docprintnocr(string):
    document.append('%s' % string)
    p = optparse.OptionParser()
    p.add_option('-a','--server',dest='server',default='XXX',help='The server with the ODI_W catalog')
    p.add_option('-b','--beginningday',dest='beginningday',type=int,default=1,help='The day to begin retrieval')
    p.add_option('-e','--endingday',dest='endingday',type=int,default=0,help='The day to end retrieval')
    p.add_option('-n','--session',dest='session',default='',help='Session to retrieve')
    p.add_option('-s','--step',dest='step',action='store_true',help='Print the step data')
    p.add_option('-t','--task',dest='task',action='store_true',help='Print the task data')
    p.add_option('-x','--recipientlist',dest='recipientlist',default='XXX',help='report recipient(s)')
    p.add_option('-y','--mailserver',dest='mailserver',default='XXX',help='mail server')
    p.add_option('-z','--mailuser',dest='mailuser',default='XXX',help='mail user')
    p.add_option('-p','--printonly',dest='printonly',action='store_true',help='Print, no e-mail')
    options,args = p.parse_args()
    docprint( '%s %s' \
    '\n\tserver=%s' \
    '\n\tbeginningday=%s' \
    '\n\tendingday=%s' \
    '\n\tsession=%s' \
    '\n\tstep=%s' \
    '\n\ttask=%s' \
    '\n\tprintonly=%s'
    sys.argv[0]
    ,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    ,options.server
    ,options.beginningday
    ,options.endingday
    ,options.session
    ,options.step
    ,options.task
    ,options.printonly
    if options.server.upper() in ('XXX','YYY'):
    catalog = 'ODI_W'
    elif options.server in ('WWW','ZZZ'):
    catalog = 'SNP_W'
    else:
    print 'Unknown server %s' % options.server
    sys.exit(1)
    TimeEnd = datetime.datetime.now() - datetime.timedelta(options.endingday)
    TimeBegin = datetime.datetime.now() - datetime.timedelta(options.beginningday)
    TimeFormat = '%Y-%m-%d %H:%M:%S'
    if options.task:
    options.step = True
    docprint( '\n%s between %s and %s' %(
    options.server
    ,TimeBegin.strftime(TimeFormat)
    ,TimeEnd.strftime(TimeFormat)
    OptionString = ''
    if options.session:
    OptionString = '\nPrinting session %s' % options.session
    else:
    OptionString = '\nPrinting all sessions'
    if options.step:
    OptionString = '%s %s' % (OptionString,'with step detail')
    if options.task:
    OptionString = '%s %s' % (OptionString, 'and task detail')
    docprint(OptionString)
    import pyodbc
    ConnectString = 'DRIVER={SQL SERVER};SERVER=%s;DATABASE=%s;Trusted_Connection=yes' % (options.server.upper(),catalog)
    try:
    Connection = pyodbc.connect(ConnectString,autocommit=False)
    Cursor = Connection.cursor()
    except Exception, e:
    raise RuntimeError, '%s %s connect failed\n%s' % (options.server,catalog,e)
    SelectSession = """
    select
    S.SESS_NO
    ,S.SESS_NAME
    ,S.SESS_BEG
    ,S.SESS_END
    ,coalesce(S.SESS_DUR,0)
    ,S.SESS_STATUS
    ,S.CONTEXT_CODE
    from SNP_SESSION as S
    where S.SESS_BEG between ? and ?
    and S.SESS_BEG = (
    select max(SESS_BEG)
    from SNP_SESSION
    where SESS_NAME = S.SESS_NAME)
    order by S.SESS_BEG ASC
    SelectSessionHistory = """
    select Top 3
    SESS_NO
    ,SESS_NAME
    ,SESS_BEG
    ,SESS_END
    ,coalesce(SESS_DUR,0)
    ,SESS_STATUS
    ,CONTEXT_CODE
    from SNP_SESSION
    where SESS_NAME = ?
    and SESS_NO <> ?
    order by SESS_BEG DESC
    SESS_NO = 0
    SESS_NAME = 1
    SESS_BEG = 2
    SESS_END = 3
    SESS_DUR = 4
    SESS_STATUS = 5
    CONTEXT_CODE = 6
    SelectStep = """
    select
    LOG.STEP_BEG
    ,LOG.STEP_END
    ,coalesce(LOG.STEP_DUR,0)
    ,LOG.STEP_STATUS
    ,coalesce(LOG.NB_ROW,0)
    ,coalesce(LOG.NB_INS,0)
    ,coalesce(LOG.NB_UPD,0)
    ,coalesce(LOG.NB_DEL,0)
    ,coalesce(LOG.NB_ERR,0)
    ,STEP.STEP_NAME
    ,STEP.NNO
    from SNP_STEP_LOG LOG
    inner join SNP_SESS_STEP STEP
    on STEP.SESS_NO = LOG.SESS_NO
    and STEP.NNO = LOG.NNO
    WHERE LOG.SESS_NO = ?
    ORDER BY STEP.NNO
    STEP_BEG = 0
    STEP_END = 1
    STEP_DUR = 2
    STEP_STATUS = 3
    NB_ROW = 4
    NB_INS = 5
    NB_UPD = 6
    NB_DEL = 7
    NB_ERR = 8
    STEP_NAME = 9
    STEP_NO = 10
    SelectTask = """
    select
    LOG.TASK_BEG
    ,LOG.TASK_END
    ,coalesce(LOG.TASK_DUR,0)
    ,LOG.TASK_STATUS
    ,coalesce(LOG.NB_ROW,0)
    ,coalesce(LOG.NB_INS,0)
    ,coalesce(LOG.NB_UPD,0)
    ,coalesce(LOG.NB_DEL,0)
    ,coalesce(LOG.NB_ERR,0)
    ,TASK.TASK_NAME3
    from SNP_SESS_TASK_LOG LOG
    inner join SNP_SESS_TASK TASK
    on TASK.SESS_NO = LOG.SESS_NO
    and TASK.NNO = LOG.NNO
    and TASK.SCEN_TASK_NO = LOG.SCEN_TASK_NO
    WHERE LOG.SESS_NO = ?
    AND LOG.NNO = ?
    ORDER BY LOG.SCEN_TASK_NO
    TASK_BEG = 0
    TASK_END = 1
    TASK_DUR = 2
    TASK_STATUS = 3
    TASK_ROW = 4
    TASK_INS = 5
    TASK_UPD = 6
    TASK_DEL = 7
    TASK_ERR = 8
    TASK_NAME = 9
    SessionStatuses = {'M':'Warning','E':'Err','D':'Done','R':'Run'}
    StepStatuses = {'M':'Warn','E':'Err','D':'Done','W':'Wait','R':'Run'}
    SessionRows =Cursor.execute(SelectSession,(TimeBegin,TimeEnd)).fetchall()
    for SessionRow in SessionRows:
    if options.session and options.session.upper() != SessionRow[SESS_NAME].upper():
    # Not requested
    continue
    if SessionRow[SESS_NAME] in ('SOCKETSERVER','PROCESSHUB'):
    # Skip these utilities
    continue
    if SessionRow[SESS_STATUS] == 'R':
    # Still running, nothing to print(
    docprint( '\n%s, status %s' % (
    SessionRow[SESS_NAME]
    ,SessionStatuses[SessionRow[SESS_STATUS]]
    continue
    if SessionRow[SESS_END]:
    SessionEnd = SessionRow[SESS_END].strftime(TimeFormat)
    else:
    SessionEnd = ' '
    SessionHistories = Cursor.execute(SelectSessionHistory,(SessionRow[SESS_NAME],SessionRow[SESS_NO])).fetchall()
    docprintnocr( '\n%-20s\n\t%s / %s %6i secs %s' % (
    SessionRow[SESS_NAME][:20]
    ,SessionRow[SESS_BEG].strftime(TimeFormat)
    ,SessionEnd
    ,SessionRow[SESS_DUR]
    ,SessionStatuses[SessionRow[SESS_STATUS]]
    for SessionHistory in SessionHistories:
    if SessionHistory[SESS_END]:
    SessionHistoryEnd = SessionHistory[SESS_END].strftime(TimeFormat)
    else:
    SessionHistoryEnd = ' '
    docprintnocr( '\t%s / %s %6i secs %s' % (
    SessionHistory[SESS_BEG].strftime(TimeFormat)
    ,SessionHistoryEnd
    ,SessionHistory[SESS_DUR]
    ,SessionStatuses[SessionHistory[SESS_STATUS]]
    if not options.step:
    # Step detail not requested
    continue
    docprint( '\n %-22s %5s %4s %8s %8s %8s %8s %8s' % (
    ,'Secs'
    ,'Stat'
    ,'Rows'
    ,'Inserts'
    ,'Updates'
    ,'Deletes'
    ,'Errors'
    for StepRow in Cursor.execute(SelectStep,SessionRow[SESS_NO]).fetchall():
    try:
    docprint( ' %-22s %5i %-4s %8i %8i %8i %8i %8i' % (
    StepRow[STEP_NAME][:22]
    ,StepRow[STEP_DUR]
    ,StepStatuses[StepRow[STEP_STATUS]]
    ,StepRow[NB_ROW]
    ,StepRow[NB_INS]
    ,StepRow[NB_UPD]
    ,StepRow[NB_DEL]
    ,StepRow[NB_ERR]))
    except Exception, e:
    docprint(e)
    continue
    if not options.task:
    # Task detail not requested
    continue
    try:
    for TaskRow in Cursor.execute(SelectTask,(SessionRow[SESS_NO],StepRow[STEP_NO])).fetchall():
    docprint( ' %-21s %5i %-4s %8i %8i %8i %8i %8i' % (
    TaskRow[TASK_NAME][:21]
    ,TaskRow[TASK_DUR]
    ,TaskRow[TASK_STATUS]
    ,TaskRow[TASK_ROW]
    ,TaskRow[TASK_INS]
    ,TaskRow[TASK_UPD]
    ,TaskRow[TASK_DEL]
    ,TaskRow[TASK_ERR]
    except Exception, e:
    docprint( e )
    docprint( '\nEnd of report')
    Connection.close()
    if options.printonly:
    for line in document:
    print line
    sys.exit(0)
    import smtplib
    Message = """From: %s
    To: %s
    MIME-Version: 1.0
    Content-type: text/html
    Subject: %s
    <font face="courier" size="4"><b>%s</b></font>
    options.mailuser
    ,options.recipientlist
    ,'Session Report'
    ,'<br>'.join(document).replace('\n','<br>').replace('\t',' ').replace(' ',' ')
    server = smtplib.SMTP(options.mailserver)
    server.sendmail(options.mailuser,options.recipientlist,Message)
    server.quit()

  • How to retrieve the last inserted row

    This may be a question with a very known answer but I couldn't find any within this forum.
    What is the proper way to retrieve the just inserted record ?
    I'm accessing the DB from external Java and at this moment I use a timestamp column in order to retrieve the inserted row. So I generate an unique timestamp ('20020615184524356') which I inserted during the insert operation. I retrieve the just inserted row using "select * from fooTable where(timestamp='20020615184524356')".
    Is this the general idea or am I totally wrong ?

    hi Shaik Khaleel,
    Just wanted to clarify my doubts regarding rowid.
    Please refer the subject as "abt rowid" in previous posting and ur reply for that was
    "its an unique number throughout the database, its an hexadecimal number. it assigns the rowid of the deleted row in future , but not to the immediate insertation row."
    As u have mentioned the rowid of the deleted row can be assigned to a new row in future,
    wont the following query fail.
    select * from temp where rowid=(select max(rowid) from temp); -- in oracle. ~chandru

  • How to fetch last inserted row in MySQL

    Hi,
    I am trying to get the last inserted row in MySql..but not able to fetch it.
    this is what i used
    i have one column order_id which is auto_increment
    SELECT * FROM tablename WHERE order_id=(SELECT MAX(order_id) FROM tablename)
    any help is appreciated .
    the usage of lastinsert() method is also not successful
    chintan

    Hello
    Given you have a date column, you can use it to determine the latest row. However, there is still a chance that two rows were inserted at exactly the same time in which case you will need something in addition to your date column to decide which is the latest...
    The first option uses a sub query and the second uses analytics, as does the 3rd - however with the 3rd, if 2 rows have exactly the same date and time, it will pick one at random unless you include another column in the order by to determine the latest...
    select
    FROM
        your_table
    WHERE
        your_date_column = (SELECT MAX(your_date_column) from your_table)
    SELECT
    FROM
            select
                a.*,
                MAX(your_date_column) OVER() max_date_column
            FROM
                your_table a
    WHERE
        your_date_column = max_date_column
    SELECT
    FROM
            select
                a.*,
                ROW_NUMBER OVER(ORDER BY your_date_column DESC) rn
            FROM
                your_table a
    WHERE
        rn = 1HTH
    David

  • Rownum and last inserted row !!!!!!!!!!!!

    hi everybody,
    I am at present using oracle 8i Release 2. According to my knowledge and "Oracle 8 complete reference", when we use ROWNUM, the rownum is decided when the data is selected from the database. So when we use "order by" clause actually the rownum gets jumbled up.
    But to my surprise when i did something like this on my SQl prompt row num is acting very "innocent" :)
    <Code>
    1* select rownum, empno from emp
    SQL> /
    ROWNUM EMPNO
    1 7369
    2 7499
    3 7521
    4 7566
    5 7654
    6 7698
    7 7782
    8 7788
    9 7839
    10 7844
    11 7876
    12 7900
    13 7902
    14 7934
    15 1
    15 rows selected.
    SQL> select rownum, empno from emp order by empno;
    ROWNUM EMPNO
    1 1
    2 7369
    3 7499
    4 7521
    5 7566
    6 7654
    7 7698
    8 7782
    9 7788
    10 7839
    11 7844
    12 7876
    13 7900
    14 7902
    15 7934
    15 rows selected.
    </Code>
    As you can see rownum is ordered again .. m i missing something.
    B)
    Is it possible to get a row that was inserted last. Does oracle guarantee that data retrieval will be according to the time of inssertion !!
    Thanx in advance
    Chetan

    Rownum is decided afeter the complete execution of ur SQL statment (it includes ordey by, group by, where etc.).
    you can get the last inserted row using:
    select * from emp where rowid=
    (select max(rowid) from emp);
    Regards
    Riaz

  • How to get the last row in a resultset or query

    Hi All
    Say If I have a complex query which returns a resultset say 15 rows. Now I want to limit the output showing only the last row.
    How can we do this

    Keep in mind Oracle does not keep "row" order as such. Unlike a graphical type db like Access, Oracle will not always give you back the results in order.
    Even if you were to use a sequence, your query is never guaranteed to give back the results in the order you are expecting. You must then give an order by statement to all queries expecting the order.
    Your definition of last row too is vague - if it is in fact the greatest amount, use the inline view suggestion. If you simply want to see the last inserted row, consider adding a last_update_date column inserting the sysdate (by a trigger perhaps). This would then allow you to see the last inserted row.
    Enjoy!

  • How can I get only the last 2 rows?

    How can I narrow down a query to get only the last two rows in a table ?
    Thanks,
    Mohan

    Thanks a lot Ram for your suggestion but already I have a query which returns a set of rows, of which I would like to further filter and get the last two rows
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Ramanuj Bangad ([email protected]):
    try out something like this if it helps.
    Example:
    select * from users
    where rownum <= (select count(*) from users)
    minus
    select * from users
    where rownum <= (select count(*) -2 from users )
    <HR></BLOCKQUOTE>
    null

  • Last Inserted Row in a Table

    Hi,
    I want to select only the last inserted row in a table. Can anybody help me how can i get it.
    Eg
    select * from emp;
    empno ename sal
    12 abc 100
    13 xyz 200
    Now i have inserted a row as
    Insert into emp values (14,'Rohit',500);
    So i only want to select the last inserted row i.e.. empno 14 (in this case).
    Thanks
    Bye
    Rohit Taneja

    Thanks to all for replying.
    But the result is not which i desire.
    I have deleted the existing row in the same table as
    SQL> Delete from emp where empno = 13;
    1 row deleted.
    Then i inserted a new row as
    SQL> insert into emp values(10,'SRI',200);
    1 row created.
    Then i committed the work
    SQL> commit;
    Commit complete.
    But still am getting the last row as
    SQL> select * from emp
    where rowid=(select max(rowid)
    from emp);
    EMPNO ENAME SAL
    14 ROHIT 500
    as the solution.
    But here i am supposed to get the row with empno 10.
    I have tried both the queries and still geting the same result.
    Please look aat it again,
    Thanks in advance
    Bye
    Rohit Taneja
    Hi,
    I want to select only the last inserted row in a
    table. Can anybody help me how can i get it.
    Eg
    select * from emp;
    empno ename sal
    12 abc 100
    13 xyz 200
    Now i have inserted a row as
    Insert into emp values (14,'Rohit',500);
    So i only want to select the last inserted row i.e..
    empno 14 (in this case).
    Thanks
    Bye
    Rohit Taneja

  • Cant get the last row in jtable

    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
            //creating the table
        for (i=0;i<this.rows;i++)
         model.insertRow(i,new Object[]{"input Y1:",""});
                for ( i=i;i<this.Amount+this.rows;i++)
         model.insertRow(i,new Object[]{"input Amount:",""});
    //end of creatingthis code creats the table that i need and its works right.
    for(i=0;i<rows;i++){
                  fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
            int j=0;
            String s=GetData(table, 1, 4).toString();
            //the problem line
            String s1=GetData(table, 1, 5).toString();
        public Object GetData(JTable table, int col_index, int row_index){
        return table.getModel().getValueAt(row_index, col_index);
      }this line i get ""
    String s1=GetData(table, 1, 5).toString();
    Edited by: vitaly87 on 00:41 08/04/2011

    vitaly87 wrote:
    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
    this line i get ""
    String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
    If it hadn't found the row, I expect you would have got an Exception
    Winston

  • How to get the last transaction in a row in SQL Developer?

    What syntax would I use to get the last transaction of a row in SQL developer?
    The way I have my query set-up currently it is not returning the correct data, here is my current syntax:
    select ssn, max(tran_id), chng_type,tran_id
    from pda_tran
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type,tran_id;
    It returns a 'C' chng_type but it is not the last one. when I query on this ssn this is what I get:
    ssn tran_id chng_type
    xxx-xxx-0011 001 A
    xxx-xxx-0011 002 E
    xxx-xxx-0011 003 C
    xxx-xxx-0011 004 S
    xxx-xxx-0011 005 C
    xxx-xxx-0011 006 T
    I only want to return the ssn's with a last transaction chng_type of 'C'. How can I get the correct information returned. Please advise.

    From what I see and read... there is one to many group by
    You wrote
    select ssn, max(tran_id), chng_type,tran_id
    from pda_tran
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type,tran_id;
    If you want the max(tran_id), remove it from the "group by"
    select ssn, chng_type, max(tran_id)
    FROM
    (SELECT 'xxx-xxx-0011' ssn, '001' tran_id, 'A' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '002' tran_id, 'E' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '003' tran_id, 'C' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '004' tran_id, 'S' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '005' tran_id, 'C' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '006'tran_id, 'T' chng_type FROM DUAL )
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type;

  • Need to query the database to get the last sequence number

    Hi all
    I am trying to get the last sequence number of the last row inserted into my Oracle database. Please could someone give me the SQL which would allow me to do this - using Oracle SQL Explorer I have confirmed that there is a sequence on the table which is called: XYZ_SEQ and the code for this is:
    CREATE SEQUENCE "MY_USER_NAME"."XYZ_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 21 CACHE 20 NOORDER NOCYCLE ;
    My Java application is inserting a row into my table and to insert a new row I need to have the last sequence inserted +1 so the new row can be added.
    Any help would be much appreciated.

    Hi,
    Welcome to the forum!
    If you are using a sequence just do (example):
    INSERT INTO TABLE_NAME
       (COL1,
        COL2)
    VALUES
       (SEQUENCE_NAME.NEXTVAL,
        OTHER_VALUE);to obtain (and use) the next number in the sequence when you are inserting.
    If you have a sequence to use for a specific table, you should use it when your insert new data (no matter your are doing that: java application, procedure, etc). Doing this you avoid some problems when you have the sequence 'out of date' about the associated data.
    Regards,
    Edited by: Walter Fernández on Sep 19, 2009 10:08 AM
    Edited by: Walter Fernández on Sep 19, 2009 10:10 AM

Maybe you are looking for