MWUser
MWUser

Reputation: 287

C#: SQL Getting the Last row from a SqlDataReader?

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 :)

Upvotes: 1

Views: 2231

Answers (2)

Vimal CK
Vimal CK

Reputation: 3563

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

Upvotes: 0

NDJ
NDJ

Reputation: 5194

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

Upvotes: 4

Related Questions