How to get the last row of a database table.

HI ,
I want to get record exactly from the last row of a database table.
How is that possible?

Hi,
To fetch last record from an internal table, just do find the number of records in it and read using index.
DESCRIBE TABLE ITAB LINES L_LINES.
READ TABLE ITAB INDEX L_LINES.
You can also use LOOP .. ENDLOOP but the above method is better (performance wise).
using LOOP .. ENDLOOP.
LOOP AT ITAB.
**do nothing
ENDLOOP.
**process ITAB (Header record of ITAB).
**after ENLOOP, ITAB will have the last record of the internal table.
[here ITAB is internal table as well as header record.]
But what is the requirement?
If you are looking for the current record of an employee then you can use ENDDA = HIGH_DATE.
My advice is to review your requirement again and try to fetch only that record which you need.
Mubeen

Similar Messages

  • HELP! How te retrieve the last row in MYSQL database using Servlet!

    Hi ,
    I am new servlets. I am trying to retireve the last row id inserted using the servlet.
    Could someone show me a working sample code on how to retrieve the last record inserted?
    Thanks
    MY CODE
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class demo_gr extends HttpServlet {
    //***** Servlet access to data base
    public void doPost (HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
         String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
              String param1 = req.getParameter("param1");
              PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");
              String semail, sfname, slname, rfname, rlname, remail, message;
              int cardType;
              sfname = req.getParameter("sfname");
              slname = req.getParameter("slname");
              rfname = req.getParameter("rfname");
              rlname = req.getParameter("rlname");
              semail = req.getParameter("semail");
              remail = req.getParameter("remail");
              message = req.getParameter("message");
              //cardType = req.getParameter("cardType");
              cardType = Integer.parseInt(req.getParameter("cardType"));
              out.println(" param1 " + param1 + "\n");
         String query = "SELECT * FROM greeting_db "
    + "WHERE id =" + param1 + "";
              String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
              query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
              //out.println(" query2 " + query2 + "\n");
              if (semail.equals("") || sfname.equals("") ||
              slname.equals("") || rfname.equals("") ||
              rlname.equals("") || remail.equals("") ||
              message.equals(""))
                        out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
                        out.close();
                        return;
              String title = "Your Card Has Been Sent";
              out.println("<BODY>\n" +
    "<H1 ALIGN=CENTER>" + title + "</H1>\n" );
                   out.println("\n" +
    "\n" +
    " From  " + sfname + ", " + slname + "\n <br> To  "
                                            + rfname + ", " + rlname + "\n <br>Receiver Email  " + remail + "\n<br> Your Message "
                                            + message + "\n<br> <br> :");
                   if (cardType ==1)
                        out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
                   else if(cardType ==2) {
                        out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
                   else if(cardType ==3) {
                        out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
    else if(cardType ==4) {
                        out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
    else if(cardType ==5) {
                        out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
    else if(cardType ==6) {
                        out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
    out.println("</BODY></HTML>");
         try {
              Class.forName ("com.mysql.jdbc.Driver");
              Connection con = DriverManager.getConnection
              ( url, "*****", "******" );
    Statement stmt = con.createStatement ();
                   stmt.execute (query2);
                   //String query3 = "SELECT LAST_INSERT_ID()";
                   //ResultSet rs = stmt.executeQuery (query3);
                   //int questionID = rs.getInt(1);
                   System.out.println("Total rows:"+questionID);
    stmt.close();
    con.close();
    } // end try
    catch (SQLException ex) {
              //PrintWriter out = resp.getWriter();
         resp.setContentType("text/html");
              while (ex != null) { 
         out.println ("SQL Exception: " + ex.getMessage ());
         ex = ex.getNextException ();
    } // end while
    } // end catch SQLException
    catch (java.lang.Exception ex) {
         //PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");     
              out.println ("Exception: " + ex.getMessage ());
    } // end doGet
    private void printResultSet ( HttpServletResponse resp, ResultSet rs )
    throws SQLException {
    try {
              PrintWriter out = resp.getWriter();
         out.println("<html>");
         out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
         out.println("<body>");
         out.println("<center><font color=AA0000>");
         out.println("<table border='1'>");
         int numCols = rs.getMetaData().getColumnCount ();
    while ( rs.next() ) {
              out.println("<tr>");
         for (int i=1; i<=numCols; i++) {
    out.print("<td>" + rs.getString(i) + "</td>" );
    } // end for
    out.println("</tr>");
    } // end while
         out.println("</table>");
         out.println("</font></center>");
         out.println("</body>");
         out.println("</html>");
         out.close();
         } // end try
    catch ( IOException except) {
    } // end catch
    } // end returnHTML
    } // end jbsJDBCServlet

    I dont know what table names and fields you have but
    say you have a table called XYZ which has a primary
    key field called keyID.
    So in order to get the last row inserted, you could
    do something like
    Select *
    from XYZ
    where keyID = (Select MAX(keyID) from XYZ);
    Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
    This works fine if the emp_id is incremental and of type integer
    Query:
    select      *
    from      employee e,  (select max(emp_id) as emp_id from employee) z
    where      e.emp_id = z.emp_id
    or
    select top 1 * from employee order by emp_id descUday

  • 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 record of an internall table ....

    Hi All..
    i want to get the last record of an internal table itab, and i want the the value of the last record.

    Hi,
         Use describe statment.
    data: lv_line type i.
        Describe table itab lines lv_line.
        read table itab into wa_itab index lv_line.
    regards,
    Santosh Thorat

  • 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 to get the last row

    I have 10 rows in my table and I have to retrive last row using rownum.
    For this I use
    SELECT * from <table_name>
    where rownum<=10
    minus
    SELECT * from <table_name>
    where rownum<=9
    The result is no rows selected
    In the same case if I use
    SELECT rownum from <table_name>
    Where rownum <= 10
    minus
    SELECT rownum from <table_name>
    where rownum <=9
    The result is 10
    Why this happend.
    If the result is 10, then why the row whose rowid is 10 is not retrived

    All
    Please bear in mind that ROWNUM is an attribute of the query NOT the table. The last row returned by an unORDERed SELECT statement may be the most recently inserted row but is not guaranteed to be so.
    The only way of assuring yourself of returning the most recent row is either to timestamp all your tables with a date_created column or to use a primary key with an ascending value.
    rgds, APC

  • How to get the last update time for a table ?

    I want to know the last change of the table data , for example, a record has been changed, how can i get that time?
    Regards,
    Lament

    Hello
    check the tables CDHDR & CDPOS
    But the condition when u r checking the these table.for a particular field the at data element level- futhur charactestictab level we have one check box called change document it as tick
    Thank u,
    santhosh

  • How to get the field row name of database from a form?

    Hello experts,
    I am newer in OIM and developments with the API's.
    I have this environment,
    one resource that have the attribute department
    relationship with the database row
    UD_RESOURCE1_DEPARTMENT and other resource with the same attribute in, UD_RESOURCE2_DEPARTMENT
    I am programing one java class that put values in the
    form field through the table name, sample,
    UD_RESOURCE_DEPARTMENT.
    I let some code:
    # Hash table with the value of Department
    myMap.put("UD_RESOURCE_DEPARTMENT", value);
    # and save in the resource form
    tcFormInstanceOperationsIntf tcform = (tcFormInstanceOperationsIntf)tcUtilityFactory.getUtility(dataProvider,"Thor.API.Operations.tcFormInstanceOperationsIntf");
    tcform.setProcessFormData(Long.parseLong(formKey), myMap);
    But this solution implies know the name of the field in the database and not is a global solution.
    I am interesting in know how I can obtain the name of the
    row field of the database for the atribute. Does anybody know how to obtain the row field name of database from an IT Resource or through the field name of the form?
    Is this the correct way to store data in a form?
    Thanks in advanced.

    Hi,
    Thank you.
    I have seen this function in the OTN help, but how can i get the index number. My requirment is when saving the data, I need to save both the value and the element name into the database,
    Also it is tabular block, more than one rows
    Thanks again

  • How to get the latest row from my Logical Table Source?

    Hi everyone,
    I have a SALARY_HISTORY table that holds the Salary Date and the Salary Amount for an employee, as a simple example. In my Business Model, I want to have a Display Folder called "Current Salary" and use the Where Clause restriction to derive the latest salary for each of my employees.
    In standard SQL Plus, I used a nested SQL statement, e.g. "where a.SalaryDate = (select max(b.SalaryDate) from SALARY_HISTORY b where b.employeeid = a.employeeid)".
    Is there anyway in the "Where Clause" filter of the LTS to derive this type of a query?
    I have tried things like "DB".""."SCHEMA"."AL_SALARY_HISTORY"."SalaryDate" = EVALUATE('SELECT_PHYSICAL MAX(SALARY_DATE) FROM "DB".."SCHEMA"."AL_SALARY_HISTORY" WHERE employeeid = %1)', "DB".""."SCHEMA"."AL_SALARY_HISTORY"."employeeid"). And I know I can't use any of the analytic functions in a where clause.
    So how do I go about this other than creating a View in the database or creating a function in the database to give me the maximum salary date for my employee?
    Thanks
    Paul

    Hi Paul,
    You could achieve this requirement using a sub query. Briefly, the steps are
    1. Just create one report with max(salary_date) for each employee.
    2. Create another report with SALARY_DATE included.
    3. Create a filter (Based on another analysis) on this report, as employee is in(Employee of report in step1) AND SALARY_DATE IS IN(SALARY_DATE of report in step1)(this is the max_salary_date for him)
    You could notice that BI Server would send two queries to the backend for this info.
    Hope this helps.
    Thank you,
    Dhar

  • How to get the last day of the week?

    Hii
    i can get the calender week number for any given date using
    SELECT to_char(to_date('04/04/2011','MM/DD/YYYY'),'WW') FROM dual
    can any body tell me, how to get the last day of that week ?
    and the answer should be 04/08/2011(8th april )
    thanks
    San
    Edited by: sandeep9 on Apr 4, 2011 3:50 AM

    Hi, San,
    Here's one way:
    WITH     sample_data     AS
         SELECT  DATE '2011-04-04'     AS dt
         FROM     dual
    SELECT  dt
    ,     TO_CHAR (dt, 'WW')     AS week_num
    ,     NEXT_DAY ( dt - 1
               , TO_CHAR ( TRUNC (dt, 'YEAR') - 1
                      , 'Day'
               )          AS end_o_week
    FROM     sample_data;Another way is to use date arrithmetic:
    WITH     sample_data     AS
         SELECT  DATE '2011-04-09'     AS dt
         FROM     dual
    SELECT  dt
    ,     TO_CHAR (dt, 'WW')     AS week_num
    ,     TRUNC (dt, 'YEAR')
          + (7 * CEIL ( (dt - (TRUNC (dt, 'YEAR') - 1))
                / 7
          - 1               AS using_date_arithmetic
    FROM     sample_data;

  • How to get the last day of a month?

    HI,
    I want to know how to get the last day of a month.
    In my JClient form, I tried to get it by using oracle.sql.Date method, that is:
    lastday=oracle.sql.Date anydate.lastDayOfMonth();
    But it does not work. The result is lastday=anydate.
    Why?
    Stephen

    You can use the Calender class...
    Calendar c = Calendar.getInstance();
    and then something like...
    c.add(c.MONTH, 1);
    int dayOfMonth = c.get(Calender.MONTH);
    c.add(c.DAY_OF_MONTH, - (dayOfMonth-1) );
    other usefull functions are:
    System.out.println(" YEAR : " + c.get(Calendar.YEAR));
    System.out.println(" MONTH : " + c.get(Calendar.MONTH));
    System.out.println(" DAY_OF_MONTH : " + c.get(Calendar.DAY_OF_MONTH));
    System.out.println(" DAY_OF_WEEK : " + c.get(Calendar.DAY_OF_WEEK));
    System.out.println(" DAY_OF_YEAR : " + c.get(Calendar.DAY_OF_YEAR));
    System.out.println(" WEEK_OF_YEAR : " + c.get(Calendar.WEEK_OF_YEAR));
    System.out.println(" WEEK_OF_MONTH : " + c.get(Calendar.WEEK_OF_MONTH));
    System.out.println(" DAY_OF_WEEK_IN_MONTH : " + c.get(Calendar.DAY_OF_WEEK_IN_MONTH));
    System.out.println(" HOUR : " + c.get(Calendar.HOUR));
    System.out.println(" AM_PM : " + c.get(Calendar.AM_PM));
    System.out.println(" HOUR_OF_DAY (24-hour): " + c.get(Calendar.HOUR_OF_DAY));
    System.out.println(" MINUTE : " + c.get(Calendar.MINUTE));
    System.out.println(" SECOND : " + c.get(Calendar.SECOND));
    System.out.println();*/

  • How to get the last day according to fiscal period input in selection scree

    Hello expert
    how to get the last day of fiscal period input.
    the fiscal period inculdes 1-16
    when fiscal period is greater than 12, only calculate the last day of 12nd month
    your solution will be apprecaited, FM existing?
    thank you
    Kevin

    Hi,
    when you give a particular date in any month
    the following fm will give you the last date of that month
    here you can give
    R_FDATE-HIGH  as 01 and month as the period you wnat and year for current year
    concatenates '01'  month year  into r_fdate-high separated by '.'.
    then it will give g_ltdt for that month and year which wil be the last date of that month
        CALL FUNCTION 'RP_LAST_DAY_OF_MONTHS'
          EXPORTING
            DAY_IN            = R_FDATE-HIGH
          IMPORTING
            LAST_DAY_OF_MONTH = G_LTDT
          EXCEPTIONS
            DAY_IN_NO_DATE    = 1
            OTHERS            = 2.
        IF SY-SUBRC <> 0.
          MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                  WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
        ENDIF.
    thanks & regards,
    Venkatesh

  • How to get the last error for while loop?

    How to get the last error for while loop? I just want transfer the last error for while loop, but the program use the shift register shift all error every cycle.

    What do you mean by "get" and "transfer"?
    If the shift register is not what you want, use a plan tunnel instead.
    Typically, programmers are interested in the first, not last, error.
    Can you show us your code so we have a better idea what you are trying to?
    LabVIEW Champion . Do more with less code and in less time .

  • How to get the last version of flash in MSI format automatically?

    How to get the last version of flash in MSI format automatically?
    Roberto Neigenfind
    Bravo Tecnologia
    www.bravotecnologia.com.br

    Hi Barbara,
    Flash Professional CS5.5 is a 32-bit application which can be installed on computers with either 32-bit or 64-bit operating systems.
    You can purchase this by Adobe's backward Licensing policy :
    " Adobe allows program members to order a current-version license but use a prior version. These members can contact Adobe Customer Service to request a serial number for the earlier version if they do not already have one. Prior-version software is available via ESD and can be purchased through standard resellers. The program member must follow all guidelines of the current-version EULA. "
    Please check the doc : http://www.adobe.com/volume-licensing/policies.html

  • How to get the "last changed by" for a set of function modules?

    How to get the "last changed by" for a set of function modules?
    is there any table to get it??

    See [this|Re: Date of creation of function module] I posted earlier.
    >TFDIR will give you the name of the function group program and the include number.
    >E.g. SAPLZFUNCGROUP Include 01.
    >From this you can construct the include name: LZFUNCGROUPU01.
    >You can look this up in TRDIR to find the creation date (CDAT) of the function module.
    In your case, you need unam and udat.
    matt

Maybe you are looking for

  • White/black stripes on my screen for a few seconds on my Macbook Pro Retina

    Hello, Sometimes there appear on white/black stripes on my screen for a few seconds. There isn't a specific programm or anything when he does that. It comes and it goes. I don't know if it's serieus problem. Do somebody know what to do? Thanks

  • Compiling files with the 'package'-statement

    Hi, I have a problem compiling files that uses the 'package'-statement: I have 2 files ClassA.java and ClassB.java. ClassA uses objects of type ClassB. When I compile ClassA.java the compiler also automatically compiles ClassB.java. No problem so far

  • ME55 DUMP error after EHP upgrade

    Hi all, We recently upgraded to SAP ECC EHP7 version (Basis 740) and we are getting some kind of dump error upon entering ME55. Is this a common issue? I could not find the same issue noted before. How can I resolve it? I attached the error screen th

  • My iPod classic will not sync the rest of my podcasts

    I have recently tried synching my podcast collection to my classic 160GB...and I can only get 3 of my podcasts on there...each with about 100-300 episodes...and the space is not filled up at all....what might cause that the rest of my podcasts won't

  • WindowServer is taking up a ridiculous amount of RAM

    I just noticed that WindowServer is taking up a ridiculous amount of RAM on my computer. It is not slowing my computer down at all, it is more just odd than actually causing a problem (i.e. when i opened up finale or another large application, the Wi