1

I needed to sort the dates in a table column and get the last row (i.e.: the latest date) from the reader. I tried the following:

using (SqlConnection con = new SqlConnection(conString))
{
   SqlCommand cmd = new SqlCommand("Select * From ActivityTable 
                                             ORDER BY CONVERT(DATE, Date) ASC", con);
   con.Open();
   SqlDataReader rdr = cmd.ExecuteReader();

   //I need to skip reading all the rows UNTIL the last row. I only need the last row
   while (rdr.Read())
   {
     locationOfPrevious = rdr["Location"].ToString();
     nodeid_previous = rdr["NodeID"].ToString();

   }
   rdr.Close();
}

I believe the query is right but I can't get the LAST row from the query results (that is the last date recorded according to the sort). What do yall suggest? Thanks folks :)

1

2 Answers 2

4

i'd suggest ordering by desc and taking the first row - more efficient

Sign up to request clarification or add additional context in comments.

4 Comments

Why didn't I think of that Lmao xD That was the best. Thanks man :P
I get a 'IndexOutOfRange Exception" though
check the fields "Location" and "NodeID" exist and are correctly spelled?
@MWUser edit what you changed your code to above so we can see why you would be getting that error.
0

Use below query

Select Top 1 * From ActivityTable ORDER BY CONVERT(DATE, Date) DESC //SQL

you can use LIMIT keyword to generate the same output in MySQL

Select * From ActivityTable ORDER BY CONVERT(DATE, Date) DESC LIMIT 0,1 //MYSQL

2 Comments

TOP is not valid MySQL syntax.
in MySql that would be equiv to the key word LIMIT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.